three.js 835 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. * @author bhouston / http://exocortex.com
  5. */
  6. var THREE = { REVISION: '67dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  15. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  16. // requestAnimationFrame polyfill by Erik Möller
  17. // fixes from Paul Irish and Tino Zijdel
  18. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  19. ( function () {
  20. var lastTime = 0;
  21. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  22. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  23. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  24. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  25. }
  26. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  27. self.requestAnimationFrame = function ( callback ) {
  28. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  29. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  30. lastTime = currTime + timeToCall;
  31. return id;
  32. };
  33. }
  34. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  35. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  36. }
  37. }() );
  38. // GL STATE CONSTANTS
  39. THREE.CullFaceNone = 0;
  40. THREE.CullFaceBack = 1;
  41. THREE.CullFaceFront = 2;
  42. THREE.CullFaceFrontBack = 3;
  43. THREE.FrontFaceDirectionCW = 0;
  44. THREE.FrontFaceDirectionCCW = 1;
  45. // SHADOWING TYPES
  46. THREE.BasicShadowMap = 0;
  47. THREE.PCFShadowMap = 1;
  48. THREE.PCFSoftShadowMap = 2;
  49. // MATERIAL CONSTANTS
  50. // side
  51. THREE.FrontSide = 0;
  52. THREE.BackSide = 1;
  53. THREE.DoubleSide = 2;
  54. // shading
  55. THREE.NoShading = 0;
  56. THREE.FlatShading = 1;
  57. THREE.SmoothShading = 2;
  58. // colors
  59. THREE.NoColors = 0;
  60. THREE.FaceColors = 1;
  61. THREE.VertexColors = 2;
  62. // blending modes
  63. THREE.NoBlending = 0;
  64. THREE.NormalBlending = 1;
  65. THREE.AdditiveBlending = 2;
  66. THREE.SubtractiveBlending = 3;
  67. THREE.MultiplyBlending = 4;
  68. THREE.CustomBlending = 5;
  69. // custom blending equations
  70. // (numbers start from 100 not to clash with other
  71. // mappings to OpenGL constants defined in Texture.js)
  72. THREE.AddEquation = 100;
  73. THREE.SubtractEquation = 101;
  74. THREE.ReverseSubtractEquation = 102;
  75. // custom blending destination factors
  76. THREE.ZeroFactor = 200;
  77. THREE.OneFactor = 201;
  78. THREE.SrcColorFactor = 202;
  79. THREE.OneMinusSrcColorFactor = 203;
  80. THREE.SrcAlphaFactor = 204;
  81. THREE.OneMinusSrcAlphaFactor = 205;
  82. THREE.DstAlphaFactor = 206;
  83. THREE.OneMinusDstAlphaFactor = 207;
  84. // custom blending source factors
  85. //THREE.ZeroFactor = 200;
  86. //THREE.OneFactor = 201;
  87. //THREE.SrcAlphaFactor = 204;
  88. //THREE.OneMinusSrcAlphaFactor = 205;
  89. //THREE.DstAlphaFactor = 206;
  90. //THREE.OneMinusDstAlphaFactor = 207;
  91. THREE.DstColorFactor = 208;
  92. THREE.OneMinusDstColorFactor = 209;
  93. THREE.SrcAlphaSaturateFactor = 210;
  94. // TEXTURE CONSTANTS
  95. THREE.MultiplyOperation = 0;
  96. THREE.MixOperation = 1;
  97. THREE.AddOperation = 2;
  98. // Mapping modes
  99. THREE.UVMapping = function () {};
  100. THREE.CubeReflectionMapping = function () {};
  101. THREE.CubeRefractionMapping = function () {};
  102. THREE.SphericalReflectionMapping = function () {};
  103. THREE.SphericalRefractionMapping = function () {};
  104. // Wrapping modes
  105. THREE.RepeatWrapping = 1000;
  106. THREE.ClampToEdgeWrapping = 1001;
  107. THREE.MirroredRepeatWrapping = 1002;
  108. // Filters
  109. THREE.NearestFilter = 1003;
  110. THREE.NearestMipMapNearestFilter = 1004;
  111. THREE.NearestMipMapLinearFilter = 1005;
  112. THREE.LinearFilter = 1006;
  113. THREE.LinearMipMapNearestFilter = 1007;
  114. THREE.LinearMipMapLinearFilter = 1008;
  115. // Data types
  116. THREE.UnsignedByteType = 1009;
  117. THREE.ByteType = 1010;
  118. THREE.ShortType = 1011;
  119. THREE.UnsignedShortType = 1012;
  120. THREE.IntType = 1013;
  121. THREE.UnsignedIntType = 1014;
  122. THREE.FloatType = 1015;
  123. // Pixel types
  124. //THREE.UnsignedByteType = 1009;
  125. THREE.UnsignedShort4444Type = 1016;
  126. THREE.UnsignedShort5551Type = 1017;
  127. THREE.UnsignedShort565Type = 1018;
  128. // Pixel formats
  129. THREE.AlphaFormat = 1019;
  130. THREE.RGBFormat = 1020;
  131. THREE.RGBAFormat = 1021;
  132. THREE.LuminanceFormat = 1022;
  133. THREE.LuminanceAlphaFormat = 1023;
  134. // Compressed texture formats
  135. THREE.RGB_S3TC_DXT1_Format = 2001;
  136. THREE.RGBA_S3TC_DXT1_Format = 2002;
  137. THREE.RGBA_S3TC_DXT3_Format = 2003;
  138. THREE.RGBA_S3TC_DXT5_Format = 2004;
  139. /*
  140. // Potential future PVRTC compressed texture formats
  141. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  142. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  143. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  144. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  145. */
  146. /**
  147. * @author mrdoob / http://mrdoob.com/
  148. */
  149. THREE.Color = function ( color ) {
  150. if ( arguments.length === 3 ) {
  151. return this.setRGB( arguments[ 0 ], arguments[ 1 ], arguments[ 2 ] );
  152. }
  153. return this.set( color )
  154. };
  155. THREE.Color.prototype = {
  156. constructor: THREE.Color,
  157. r: 1, g: 1, b: 1,
  158. set: function ( value ) {
  159. if ( value instanceof THREE.Color ) {
  160. this.copy( value );
  161. } else if ( typeof value === 'number' ) {
  162. this.setHex( value );
  163. } else if ( typeof value === 'string' ) {
  164. this.setStyle( value );
  165. }
  166. return this;
  167. },
  168. setHex: function ( hex ) {
  169. hex = Math.floor( hex );
  170. this.r = ( hex >> 16 & 255 ) / 255;
  171. this.g = ( hex >> 8 & 255 ) / 255;
  172. this.b = ( hex & 255 ) / 255;
  173. return this;
  174. },
  175. setRGB: function ( r, g, b ) {
  176. this.r = r;
  177. this.g = g;
  178. this.b = b;
  179. return this;
  180. },
  181. setHSL: function ( h, s, l ) {
  182. // h,s,l ranges are in 0.0 - 1.0
  183. if ( s === 0 ) {
  184. this.r = this.g = this.b = l;
  185. } else {
  186. var hue2rgb = function ( p, q, t ) {
  187. if ( t < 0 ) t += 1;
  188. if ( t > 1 ) t -= 1;
  189. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  190. if ( t < 1 / 2 ) return q;
  191. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  192. return p;
  193. };
  194. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  195. var q = ( 2 * l ) - p;
  196. this.r = hue2rgb( q, p, h + 1 / 3 );
  197. this.g = hue2rgb( q, p, h );
  198. this.b = hue2rgb( q, p, h - 1 / 3 );
  199. }
  200. return this;
  201. },
  202. setStyle: function ( style ) {
  203. // rgb(255,0,0)
  204. if ( /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.test( style ) ) {
  205. var color = /^rgb\((\d+), ?(\d+), ?(\d+)\)$/i.exec( style );
  206. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  207. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  208. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  209. return this;
  210. }
  211. // rgb(100%,0%,0%)
  212. if ( /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.test( style ) ) {
  213. var color = /^rgb\((\d+)\%, ?(\d+)\%, ?(\d+)\%\)$/i.exec( style );
  214. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  215. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  216. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  217. return this;
  218. }
  219. // #ff0000
  220. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  221. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  222. this.setHex( parseInt( color[ 1 ], 16 ) );
  223. return this;
  224. }
  225. // #f00
  226. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  227. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  228. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  229. return this;
  230. }
  231. // red
  232. if ( /^(\w+)$/i.test( style ) ) {
  233. this.setHex( THREE.ColorKeywords[ style ] );
  234. return this;
  235. }
  236. },
  237. copy: function ( color ) {
  238. this.r = color.r;
  239. this.g = color.g;
  240. this.b = color.b;
  241. return this;
  242. },
  243. copyGammaToLinear: function ( color ) {
  244. this.r = color.r * color.r;
  245. this.g = color.g * color.g;
  246. this.b = color.b * color.b;
  247. return this;
  248. },
  249. copyLinearToGamma: function ( color ) {
  250. this.r = Math.sqrt( color.r );
  251. this.g = Math.sqrt( color.g );
  252. this.b = Math.sqrt( color.b );
  253. return this;
  254. },
  255. convertGammaToLinear: function () {
  256. var r = this.r, g = this.g, b = this.b;
  257. this.r = r * r;
  258. this.g = g * g;
  259. this.b = b * b;
  260. return this;
  261. },
  262. convertLinearToGamma: function () {
  263. this.r = Math.sqrt( this.r );
  264. this.g = Math.sqrt( this.g );
  265. this.b = Math.sqrt( this.b );
  266. return this;
  267. },
  268. getHex: function () {
  269. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  270. },
  271. getHexString: function () {
  272. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  273. },
  274. getHSL: function ( optionalTarget ) {
  275. // h,s,l ranges are in 0.0 - 1.0
  276. var hsl = optionalTarget || { h: 0, s: 0, l: 0 };
  277. var r = this.r, g = this.g, b = this.b;
  278. var max = Math.max( r, g, b );
  279. var min = Math.min( r, g, b );
  280. var hue, saturation;
  281. var lightness = ( min + max ) / 2.0;
  282. if ( min === max ) {
  283. hue = 0;
  284. saturation = 0;
  285. } else {
  286. var delta = max - min;
  287. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  288. switch ( max ) {
  289. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  290. case g: hue = ( b - r ) / delta + 2; break;
  291. case b: hue = ( r - g ) / delta + 4; break;
  292. }
  293. hue /= 6;
  294. }
  295. hsl.h = hue;
  296. hsl.s = saturation;
  297. hsl.l = lightness;
  298. return hsl;
  299. },
  300. getStyle: function () {
  301. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  302. },
  303. offsetHSL: function ( h, s, l ) {
  304. var hsl = this.getHSL();
  305. hsl.h += h; hsl.s += s; hsl.l += l;
  306. this.setHSL( hsl.h, hsl.s, hsl.l );
  307. return this;
  308. },
  309. add: function ( color ) {
  310. this.r += color.r;
  311. this.g += color.g;
  312. this.b += color.b;
  313. return this;
  314. },
  315. addColors: function ( color1, color2 ) {
  316. this.r = color1.r + color2.r;
  317. this.g = color1.g + color2.g;
  318. this.b = color1.b + color2.b;
  319. return this;
  320. },
  321. addScalar: function ( s ) {
  322. this.r += s;
  323. this.g += s;
  324. this.b += s;
  325. return this;
  326. },
  327. multiply: function ( color ) {
  328. this.r *= color.r;
  329. this.g *= color.g;
  330. this.b *= color.b;
  331. return this;
  332. },
  333. multiplyScalar: function ( s ) {
  334. this.r *= s;
  335. this.g *= s;
  336. this.b *= s;
  337. return this;
  338. },
  339. lerp: function ( color, alpha ) {
  340. this.r += ( color.r - this.r ) * alpha;
  341. this.g += ( color.g - this.g ) * alpha;
  342. this.b += ( color.b - this.b ) * alpha;
  343. return this;
  344. },
  345. equals: function ( c ) {
  346. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  347. },
  348. fromArray: function ( array ) {
  349. this.r = array[ 0 ];
  350. this.g = array[ 1 ];
  351. this.b = array[ 2 ];
  352. return this;
  353. },
  354. toArray: function () {
  355. return [ this.r, this.g, this.b ];
  356. },
  357. clone: function () {
  358. return new THREE.Color().setRGB( this.r, this.g, this.b );
  359. }
  360. };
  361. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  362. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  363. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  364. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  365. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  366. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  367. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  368. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  369. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  370. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  371. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  372. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  373. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  374. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  375. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  376. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  377. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  378. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  379. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  380. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  381. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  382. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  383. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  384. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  385. /**
  386. * @author mikael emtinger / http://gomo.se/
  387. * @author alteredq / http://alteredqualia.com/
  388. * @author WestLangley / http://github.com/WestLangley
  389. * @author bhouston / http://exocortex.com
  390. */
  391. THREE.Quaternion = function ( x, y, z, w ) {
  392. this._x = x || 0;
  393. this._y = y || 0;
  394. this._z = z || 0;
  395. this._w = ( w !== undefined ) ? w : 1;
  396. };
  397. THREE.Quaternion.prototype = {
  398. constructor: THREE.Quaternion,
  399. _x: 0,_y: 0, _z: 0, _w: 0,
  400. _euler: undefined,
  401. _updateEuler: function ( callback ) {
  402. if ( this._euler !== undefined ) {
  403. this._euler.setFromQuaternion( this, undefined, false );
  404. }
  405. },
  406. get x () {
  407. return this._x;
  408. },
  409. set x ( value ) {
  410. this._x = value;
  411. this._updateEuler();
  412. },
  413. get y () {
  414. return this._y;
  415. },
  416. set y ( value ) {
  417. this._y = value;
  418. this._updateEuler();
  419. },
  420. get z () {
  421. return this._z;
  422. },
  423. set z ( value ) {
  424. this._z = value;
  425. this._updateEuler();
  426. },
  427. get w () {
  428. return this._w;
  429. },
  430. set w ( value ) {
  431. this._w = value;
  432. this._updateEuler();
  433. },
  434. set: function ( x, y, z, w ) {
  435. this._x = x;
  436. this._y = y;
  437. this._z = z;
  438. this._w = w;
  439. this._updateEuler();
  440. return this;
  441. },
  442. copy: function ( quaternion ) {
  443. this._x = quaternion._x;
  444. this._y = quaternion._y;
  445. this._z = quaternion._z;
  446. this._w = quaternion._w;
  447. this._updateEuler();
  448. return this;
  449. },
  450. setFromEuler: function ( euler, update ) {
  451. if ( euler instanceof THREE.Euler === false ) {
  452. throw new Error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  453. }
  454. // http://www.mathworks.com/matlabcentral/fileexchange/
  455. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  456. // content/SpinCalc.m
  457. var c1 = Math.cos( euler._x / 2 );
  458. var c2 = Math.cos( euler._y / 2 );
  459. var c3 = Math.cos( euler._z / 2 );
  460. var s1 = Math.sin( euler._x / 2 );
  461. var s2 = Math.sin( euler._y / 2 );
  462. var s3 = Math.sin( euler._z / 2 );
  463. if ( euler.order === 'XYZ' ) {
  464. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  465. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  466. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  467. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  468. } else if ( euler.order === 'YXZ' ) {
  469. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  470. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  471. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  472. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  473. } else if ( euler.order === 'ZXY' ) {
  474. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  475. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  476. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  477. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  478. } else if ( euler.order === 'ZYX' ) {
  479. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  480. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  481. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  482. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  483. } else if ( euler.order === 'YZX' ) {
  484. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  485. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  486. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  487. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  488. } else if ( euler.order === 'XZY' ) {
  489. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  490. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  491. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  492. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  493. }
  494. if ( update !== false ) this._updateEuler();
  495. return this;
  496. },
  497. setFromAxisAngle: function ( axis, angle ) {
  498. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  499. // assumes axis is normalized
  500. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  501. this._x = axis.x * s;
  502. this._y = axis.y * s;
  503. this._z = axis.z * s;
  504. this._w = Math.cos( halfAngle );
  505. this._updateEuler();
  506. return this;
  507. },
  508. setFromRotationMatrix: function ( m ) {
  509. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  510. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  511. var te = m.elements,
  512. m11 = te[0], m12 = te[4], m13 = te[8],
  513. m21 = te[1], m22 = te[5], m23 = te[9],
  514. m31 = te[2], m32 = te[6], m33 = te[10],
  515. trace = m11 + m22 + m33,
  516. s;
  517. if ( trace > 0 ) {
  518. s = 0.5 / Math.sqrt( trace + 1.0 );
  519. this._w = 0.25 / s;
  520. this._x = ( m32 - m23 ) * s;
  521. this._y = ( m13 - m31 ) * s;
  522. this._z = ( m21 - m12 ) * s;
  523. } else if ( m11 > m22 && m11 > m33 ) {
  524. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  525. this._w = (m32 - m23 ) / s;
  526. this._x = 0.25 * s;
  527. this._y = (m12 + m21 ) / s;
  528. this._z = (m13 + m31 ) / s;
  529. } else if ( m22 > m33 ) {
  530. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  531. this._w = (m13 - m31 ) / s;
  532. this._x = (m12 + m21 ) / s;
  533. this._y = 0.25 * s;
  534. this._z = (m23 + m32 ) / s;
  535. } else {
  536. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  537. this._w = ( m21 - m12 ) / s;
  538. this._x = ( m13 + m31 ) / s;
  539. this._y = ( m23 + m32 ) / s;
  540. this._z = 0.25 * s;
  541. }
  542. this._updateEuler();
  543. return this;
  544. },
  545. setFromUnitVectors: function () {
  546. // http://lolengine.net/blog/2014/02/24/quaternion-from-two-vectors-final
  547. // assumes direction vectors vFrom and vTo are normalized
  548. var v1, r;
  549. var EPS = 0.000001;
  550. return function( vFrom, vTo ) {
  551. if ( v1 === undefined ) v1 = new THREE.Vector3();
  552. r = vFrom.dot( vTo ) + 1;
  553. if ( r < EPS ) {
  554. r = 0;
  555. if ( Math.abs( vFrom.x ) > Math.abs( vFrom.z ) ) {
  556. v1.set( - vFrom.y, vFrom.x, 0 );
  557. } else {
  558. v1.set( 0, - vFrom.z, vFrom.y );
  559. }
  560. } else {
  561. v1.crossVectors( vFrom, vTo );
  562. }
  563. this.set( v1.x, v1.y, v1.z, r ).normalize();
  564. this._updateEuler();
  565. return this;
  566. }
  567. }(),
  568. inverse: function () {
  569. this.conjugate().normalize();
  570. return this;
  571. },
  572. conjugate: function () {
  573. this._x *= -1;
  574. this._y *= -1;
  575. this._z *= -1;
  576. this._updateEuler();
  577. return this;
  578. },
  579. lengthSq: function () {
  580. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  581. },
  582. length: function () {
  583. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  584. },
  585. normalize: function () {
  586. var l = this.length();
  587. if ( l === 0 ) {
  588. this._x = 0;
  589. this._y = 0;
  590. this._z = 0;
  591. this._w = 1;
  592. } else {
  593. l = 1 / l;
  594. this._x = this._x * l;
  595. this._y = this._y * l;
  596. this._z = this._z * l;
  597. this._w = this._w * l;
  598. }
  599. return this;
  600. },
  601. multiply: function ( q, p ) {
  602. if ( p !== undefined ) {
  603. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  604. return this.multiplyQuaternions( q, p );
  605. }
  606. return this.multiplyQuaternions( this, q );
  607. },
  608. multiplyQuaternions: function ( a, b ) {
  609. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  610. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  611. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  612. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  613. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  614. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  615. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  616. this._updateEuler();
  617. return this;
  618. },
  619. multiplyVector3: function ( vector ) {
  620. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  621. return vector.applyQuaternion( this );
  622. },
  623. slerp: function ( qb, t ) {
  624. var x = this._x, y = this._y, z = this._z, w = this._w;
  625. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  626. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  627. if ( cosHalfTheta < 0 ) {
  628. this._w = -qb._w;
  629. this._x = -qb._x;
  630. this._y = -qb._y;
  631. this._z = -qb._z;
  632. cosHalfTheta = -cosHalfTheta;
  633. } else {
  634. this.copy( qb );
  635. }
  636. if ( cosHalfTheta >= 1.0 ) {
  637. this._w = w;
  638. this._x = x;
  639. this._y = y;
  640. this._z = z;
  641. return this;
  642. }
  643. var halfTheta = Math.acos( cosHalfTheta );
  644. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  645. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  646. this._w = 0.5 * ( w + this._w );
  647. this._x = 0.5 * ( x + this._x );
  648. this._y = 0.5 * ( y + this._y );
  649. this._z = 0.5 * ( z + this._z );
  650. return this;
  651. }
  652. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  653. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  654. this._w = ( w * ratioA + this._w * ratioB );
  655. this._x = ( x * ratioA + this._x * ratioB );
  656. this._y = ( y * ratioA + this._y * ratioB );
  657. this._z = ( z * ratioA + this._z * ratioB );
  658. this._updateEuler();
  659. return this;
  660. },
  661. equals: function ( quaternion ) {
  662. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  663. },
  664. fromArray: function ( array ) {
  665. this._x = array[ 0 ];
  666. this._y = array[ 1 ];
  667. this._z = array[ 2 ];
  668. this._w = array[ 3 ];
  669. this._updateEuler();
  670. return this;
  671. },
  672. toArray: function () {
  673. return [ this._x, this._y, this._z, this._w ];
  674. },
  675. clone: function () {
  676. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  677. }
  678. };
  679. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  680. return qm.copy( qa ).slerp( qb, t );
  681. }
  682. /**
  683. * @author mrdoob / http://mrdoob.com/
  684. * @author philogb / http://blog.thejit.org/
  685. * @author egraether / http://egraether.com/
  686. * @author zz85 / http://www.lab4games.net/zz85/blog
  687. */
  688. THREE.Vector2 = function ( x, y ) {
  689. this.x = x || 0;
  690. this.y = y || 0;
  691. };
  692. THREE.Vector2.prototype = {
  693. constructor: THREE.Vector2,
  694. set: function ( x, y ) {
  695. this.x = x;
  696. this.y = y;
  697. return this;
  698. },
  699. setX: function ( x ) {
  700. this.x = x;
  701. return this;
  702. },
  703. setY: function ( y ) {
  704. this.y = y;
  705. return this;
  706. },
  707. setComponent: function ( index, value ) {
  708. switch ( index ) {
  709. case 0: this.x = value; break;
  710. case 1: this.y = value; break;
  711. default: throw new Error( "index is out of range: " + index );
  712. }
  713. },
  714. getComponent: function ( index ) {
  715. switch ( index ) {
  716. case 0: return this.x;
  717. case 1: return this.y;
  718. default: throw new Error( "index is out of range: " + index );
  719. }
  720. },
  721. copy: function ( v ) {
  722. this.x = v.x;
  723. this.y = v.y;
  724. return this;
  725. },
  726. add: function ( v, w ) {
  727. if ( w !== undefined ) {
  728. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  729. return this.addVectors( v, w );
  730. }
  731. this.x += v.x;
  732. this.y += v.y;
  733. return this;
  734. },
  735. addVectors: function ( a, b ) {
  736. this.x = a.x + b.x;
  737. this.y = a.y + b.y;
  738. return this;
  739. },
  740. addScalar: function ( s ) {
  741. this.x += s;
  742. this.y += s;
  743. return this;
  744. },
  745. sub: function ( v, w ) {
  746. if ( w !== undefined ) {
  747. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  748. return this.subVectors( v, w );
  749. }
  750. this.x -= v.x;
  751. this.y -= v.y;
  752. return this;
  753. },
  754. subVectors: function ( a, b ) {
  755. this.x = a.x - b.x;
  756. this.y = a.y - b.y;
  757. return this;
  758. },
  759. multiply: function ( v ) {
  760. this.x *= v.x;
  761. this.y *= v.y;
  762. return this;
  763. },
  764. multiplyScalar: function ( s ) {
  765. this.x *= s;
  766. this.y *= s;
  767. return this;
  768. },
  769. divide: function ( v ) {
  770. this.x /= v.x;
  771. this.y /= v.y;
  772. return this;
  773. },
  774. divideScalar: function ( scalar ) {
  775. if ( scalar !== 0 ) {
  776. var invScalar = 1 / scalar;
  777. this.x *= invScalar;
  778. this.y *= invScalar;
  779. } else {
  780. this.x = 0;
  781. this.y = 0;
  782. }
  783. return this;
  784. },
  785. min: function ( v ) {
  786. if ( this.x > v.x ) {
  787. this.x = v.x;
  788. }
  789. if ( this.y > v.y ) {
  790. this.y = v.y;
  791. }
  792. return this;
  793. },
  794. max: function ( v ) {
  795. if ( this.x < v.x ) {
  796. this.x = v.x;
  797. }
  798. if ( this.y < v.y ) {
  799. this.y = v.y;
  800. }
  801. return this;
  802. },
  803. clamp: function ( min, max ) {
  804. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  805. if ( this.x < min.x ) {
  806. this.x = min.x;
  807. } else if ( this.x > max.x ) {
  808. this.x = max.x;
  809. }
  810. if ( this.y < min.y ) {
  811. this.y = min.y;
  812. } else if ( this.y > max.y ) {
  813. this.y = max.y;
  814. }
  815. return this;
  816. },
  817. clampScalar: ( function () {
  818. var min, max;
  819. return function ( minVal, maxVal ) {
  820. if ( min === undefined ) {
  821. min = new THREE.Vector2();
  822. max = new THREE.Vector2();
  823. }
  824. min.set( minVal, minVal );
  825. max.set( maxVal, maxVal );
  826. return this.clamp( min, max );
  827. };
  828. } )(),
  829. floor: function () {
  830. this.x = Math.floor( this.x );
  831. this.y = Math.floor( this.y );
  832. return this;
  833. },
  834. ceil: function () {
  835. this.x = Math.ceil( this.x );
  836. this.y = Math.ceil( this.y );
  837. return this;
  838. },
  839. round: function () {
  840. this.x = Math.round( this.x );
  841. this.y = Math.round( this.y );
  842. return this;
  843. },
  844. roundToZero: function () {
  845. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  846. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  847. return this;
  848. },
  849. negate: function () {
  850. return this.multiplyScalar( - 1 );
  851. },
  852. dot: function ( v ) {
  853. return this.x * v.x + this.y * v.y;
  854. },
  855. lengthSq: function () {
  856. return this.x * this.x + this.y * this.y;
  857. },
  858. length: function () {
  859. return Math.sqrt( this.x * this.x + this.y * this.y );
  860. },
  861. normalize: function () {
  862. return this.divideScalar( this.length() );
  863. },
  864. distanceTo: function ( v ) {
  865. return Math.sqrt( this.distanceToSquared( v ) );
  866. },
  867. distanceToSquared: function ( v ) {
  868. var dx = this.x - v.x, dy = this.y - v.y;
  869. return dx * dx + dy * dy;
  870. },
  871. setLength: function ( l ) {
  872. var oldLength = this.length();
  873. if ( oldLength !== 0 && l !== oldLength ) {
  874. this.multiplyScalar( l / oldLength );
  875. }
  876. return this;
  877. },
  878. lerp: function ( v, alpha ) {
  879. this.x += ( v.x - this.x ) * alpha;
  880. this.y += ( v.y - this.y ) * alpha;
  881. return this;
  882. },
  883. equals: function( v ) {
  884. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  885. },
  886. fromArray: function ( array ) {
  887. this.x = array[ 0 ];
  888. this.y = array[ 1 ];
  889. return this;
  890. },
  891. toArray: function () {
  892. return [ this.x, this.y ];
  893. },
  894. clone: function () {
  895. return new THREE.Vector2( this.x, this.y );
  896. }
  897. };
  898. /**
  899. * @author mrdoob / http://mrdoob.com/
  900. * @author *kile / http://kile.stravaganza.org/
  901. * @author philogb / http://blog.thejit.org/
  902. * @author mikael emtinger / http://gomo.se/
  903. * @author egraether / http://egraether.com/
  904. * @author WestLangley / http://github.com/WestLangley
  905. */
  906. THREE.Vector3 = function ( x, y, z ) {
  907. this.x = x || 0;
  908. this.y = y || 0;
  909. this.z = z || 0;
  910. };
  911. THREE.Vector3.prototype = {
  912. constructor: THREE.Vector3,
  913. set: function ( x, y, z ) {
  914. this.x = x;
  915. this.y = y;
  916. this.z = z;
  917. return this;
  918. },
  919. setX: function ( x ) {
  920. this.x = x;
  921. return this;
  922. },
  923. setY: function ( y ) {
  924. this.y = y;
  925. return this;
  926. },
  927. setZ: function ( z ) {
  928. this.z = z;
  929. return this;
  930. },
  931. setComponent: function ( index, value ) {
  932. switch ( index ) {
  933. case 0: this.x = value; break;
  934. case 1: this.y = value; break;
  935. case 2: this.z = value; break;
  936. default: throw new Error( "index is out of range: " + index );
  937. }
  938. },
  939. getComponent: function ( index ) {
  940. switch ( index ) {
  941. case 0: return this.x;
  942. case 1: return this.y;
  943. case 2: return this.z;
  944. default: throw new Error( "index is out of range: " + index );
  945. }
  946. },
  947. copy: function ( v ) {
  948. this.x = v.x;
  949. this.y = v.y;
  950. this.z = v.z;
  951. return this;
  952. },
  953. add: function ( v, w ) {
  954. if ( w !== undefined ) {
  955. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  956. return this.addVectors( v, w );
  957. }
  958. this.x += v.x;
  959. this.y += v.y;
  960. this.z += v.z;
  961. return this;
  962. },
  963. addScalar: function ( s ) {
  964. this.x += s;
  965. this.y += s;
  966. this.z += s;
  967. return this;
  968. },
  969. addVectors: function ( a, b ) {
  970. this.x = a.x + b.x;
  971. this.y = a.y + b.y;
  972. this.z = a.z + b.z;
  973. return this;
  974. },
  975. sub: function ( v, w ) {
  976. if ( w !== undefined ) {
  977. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  978. return this.subVectors( v, w );
  979. }
  980. this.x -= v.x;
  981. this.y -= v.y;
  982. this.z -= v.z;
  983. return this;
  984. },
  985. subVectors: function ( a, b ) {
  986. this.x = a.x - b.x;
  987. this.y = a.y - b.y;
  988. this.z = a.z - b.z;
  989. return this;
  990. },
  991. multiply: function ( v, w ) {
  992. if ( w !== undefined ) {
  993. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  994. return this.multiplyVectors( v, w );
  995. }
  996. this.x *= v.x;
  997. this.y *= v.y;
  998. this.z *= v.z;
  999. return this;
  1000. },
  1001. multiplyScalar: function ( scalar ) {
  1002. this.x *= scalar;
  1003. this.y *= scalar;
  1004. this.z *= scalar;
  1005. return this;
  1006. },
  1007. multiplyVectors: function ( a, b ) {
  1008. this.x = a.x * b.x;
  1009. this.y = a.y * b.y;
  1010. this.z = a.z * b.z;
  1011. return this;
  1012. },
  1013. applyEuler: function () {
  1014. var quaternion;
  1015. return function ( euler ) {
  1016. if ( euler instanceof THREE.Euler === false ) {
  1017. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1018. }
  1019. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1020. this.applyQuaternion( quaternion.setFromEuler( euler ) );
  1021. return this;
  1022. };
  1023. }(),
  1024. applyAxisAngle: function () {
  1025. var quaternion;
  1026. return function ( axis, angle ) {
  1027. if ( quaternion === undefined ) quaternion = new THREE.Quaternion();
  1028. this.applyQuaternion( quaternion.setFromAxisAngle( axis, angle ) );
  1029. return this;
  1030. };
  1031. }(),
  1032. applyMatrix3: function ( m ) {
  1033. var x = this.x;
  1034. var y = this.y;
  1035. var z = this.z;
  1036. var e = m.elements;
  1037. this.x = e[0] * x + e[3] * y + e[6] * z;
  1038. this.y = e[1] * x + e[4] * y + e[7] * z;
  1039. this.z = e[2] * x + e[5] * y + e[8] * z;
  1040. return this;
  1041. },
  1042. applyMatrix4: function ( m ) {
  1043. // input: THREE.Matrix4 affine matrix
  1044. var x = this.x, y = this.y, z = this.z;
  1045. var e = m.elements;
  1046. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  1047. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  1048. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  1049. return this;
  1050. },
  1051. applyProjection: function ( m ) {
  1052. // input: THREE.Matrix4 projection matrix
  1053. var x = this.x, y = this.y, z = this.z;
  1054. var e = m.elements;
  1055. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  1056. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  1057. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  1058. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  1059. return this;
  1060. },
  1061. applyQuaternion: function ( q ) {
  1062. var x = this.x;
  1063. var y = this.y;
  1064. var z = this.z;
  1065. var qx = q.x;
  1066. var qy = q.y;
  1067. var qz = q.z;
  1068. var qw = q.w;
  1069. // calculate quat * vector
  1070. var ix = qw * x + qy * z - qz * y;
  1071. var iy = qw * y + qz * x - qx * z;
  1072. var iz = qw * z + qx * y - qy * x;
  1073. var iw = -qx * x - qy * y - qz * z;
  1074. // calculate result * inverse quat
  1075. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1076. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1077. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1078. return this;
  1079. },
  1080. transformDirection: function ( m ) {
  1081. // input: THREE.Matrix4 affine matrix
  1082. // vector interpreted as a direction
  1083. var x = this.x, y = this.y, z = this.z;
  1084. var e = m.elements;
  1085. this.x = e[0] * x + e[4] * y + e[8] * z;
  1086. this.y = e[1] * x + e[5] * y + e[9] * z;
  1087. this.z = e[2] * x + e[6] * y + e[10] * z;
  1088. this.normalize();
  1089. return this;
  1090. },
  1091. divide: function ( v ) {
  1092. this.x /= v.x;
  1093. this.y /= v.y;
  1094. this.z /= v.z;
  1095. return this;
  1096. },
  1097. divideScalar: function ( scalar ) {
  1098. if ( scalar !== 0 ) {
  1099. var invScalar = 1 / scalar;
  1100. this.x *= invScalar;
  1101. this.y *= invScalar;
  1102. this.z *= invScalar;
  1103. } else {
  1104. this.x = 0;
  1105. this.y = 0;
  1106. this.z = 0;
  1107. }
  1108. return this;
  1109. },
  1110. min: function ( v ) {
  1111. if ( this.x > v.x ) {
  1112. this.x = v.x;
  1113. }
  1114. if ( this.y > v.y ) {
  1115. this.y = v.y;
  1116. }
  1117. if ( this.z > v.z ) {
  1118. this.z = v.z;
  1119. }
  1120. return this;
  1121. },
  1122. max: function ( v ) {
  1123. if ( this.x < v.x ) {
  1124. this.x = v.x;
  1125. }
  1126. if ( this.y < v.y ) {
  1127. this.y = v.y;
  1128. }
  1129. if ( this.z < v.z ) {
  1130. this.z = v.z;
  1131. }
  1132. return this;
  1133. },
  1134. clamp: function ( min, max ) {
  1135. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1136. if ( this.x < min.x ) {
  1137. this.x = min.x;
  1138. } else if ( this.x > max.x ) {
  1139. this.x = max.x;
  1140. }
  1141. if ( this.y < min.y ) {
  1142. this.y = min.y;
  1143. } else if ( this.y > max.y ) {
  1144. this.y = max.y;
  1145. }
  1146. if ( this.z < min.z ) {
  1147. this.z = min.z;
  1148. } else if ( this.z > max.z ) {
  1149. this.z = max.z;
  1150. }
  1151. return this;
  1152. },
  1153. clampScalar: ( function () {
  1154. var min, max;
  1155. return function ( minVal, maxVal ) {
  1156. if ( min === undefined ) {
  1157. min = new THREE.Vector3();
  1158. max = new THREE.Vector3();
  1159. }
  1160. min.set( minVal, minVal, minVal );
  1161. max.set( maxVal, maxVal, maxVal );
  1162. return this.clamp( min, max );
  1163. };
  1164. } )(),
  1165. floor: function () {
  1166. this.x = Math.floor( this.x );
  1167. this.y = Math.floor( this.y );
  1168. this.z = Math.floor( this.z );
  1169. return this;
  1170. },
  1171. ceil: function () {
  1172. this.x = Math.ceil( this.x );
  1173. this.y = Math.ceil( this.y );
  1174. this.z = Math.ceil( this.z );
  1175. return this;
  1176. },
  1177. round: function () {
  1178. this.x = Math.round( this.x );
  1179. this.y = Math.round( this.y );
  1180. this.z = Math.round( this.z );
  1181. return this;
  1182. },
  1183. roundToZero: function () {
  1184. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1185. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1186. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1187. return this;
  1188. },
  1189. negate: function () {
  1190. return this.multiplyScalar( - 1 );
  1191. },
  1192. dot: function ( v ) {
  1193. return this.x * v.x + this.y * v.y + this.z * v.z;
  1194. },
  1195. lengthSq: function () {
  1196. return this.x * this.x + this.y * this.y + this.z * this.z;
  1197. },
  1198. length: function () {
  1199. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1200. },
  1201. lengthManhattan: function () {
  1202. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1203. },
  1204. normalize: function () {
  1205. return this.divideScalar( this.length() );
  1206. },
  1207. setLength: function ( l ) {
  1208. var oldLength = this.length();
  1209. if ( oldLength !== 0 && l !== oldLength ) {
  1210. this.multiplyScalar( l / oldLength );
  1211. }
  1212. return this;
  1213. },
  1214. lerp: function ( v, alpha ) {
  1215. this.x += ( v.x - this.x ) * alpha;
  1216. this.y += ( v.y - this.y ) * alpha;
  1217. this.z += ( v.z - this.z ) * alpha;
  1218. return this;
  1219. },
  1220. cross: function ( v, w ) {
  1221. if ( w !== undefined ) {
  1222. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1223. return this.crossVectors( v, w );
  1224. }
  1225. var x = this.x, y = this.y, z = this.z;
  1226. this.x = y * v.z - z * v.y;
  1227. this.y = z * v.x - x * v.z;
  1228. this.z = x * v.y - y * v.x;
  1229. return this;
  1230. },
  1231. crossVectors: function ( a, b ) {
  1232. var ax = a.x, ay = a.y, az = a.z;
  1233. var bx = b.x, by = b.y, bz = b.z;
  1234. this.x = ay * bz - az * by;
  1235. this.y = az * bx - ax * bz;
  1236. this.z = ax * by - ay * bx;
  1237. return this;
  1238. },
  1239. projectOnVector: function () {
  1240. var v1, dot;
  1241. return function ( vector ) {
  1242. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1243. v1.copy( vector ).normalize();
  1244. dot = this.dot( v1 );
  1245. return this.copy( v1 ).multiplyScalar( dot );
  1246. };
  1247. }(),
  1248. projectOnPlane: function () {
  1249. var v1;
  1250. return function ( planeNormal ) {
  1251. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1252. v1.copy( this ).projectOnVector( planeNormal );
  1253. return this.sub( v1 );
  1254. }
  1255. }(),
  1256. reflect: function () {
  1257. // reflect incident vector off plane orthogonal to normal
  1258. // normal is assumed to have unit length
  1259. var v1;
  1260. return function ( normal ) {
  1261. if ( v1 === undefined ) v1 = new THREE.Vector3();
  1262. return this.sub( v1.copy( normal ).multiplyScalar( 2 * this.dot( normal ) ) );
  1263. }
  1264. }(),
  1265. angleTo: function ( v ) {
  1266. var theta = this.dot( v ) / ( this.length() * v.length() );
  1267. // clamp, to handle numerical problems
  1268. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1269. },
  1270. distanceTo: function ( v ) {
  1271. return Math.sqrt( this.distanceToSquared( v ) );
  1272. },
  1273. distanceToSquared: function ( v ) {
  1274. var dx = this.x - v.x;
  1275. var dy = this.y - v.y;
  1276. var dz = this.z - v.z;
  1277. return dx * dx + dy * dy + dz * dz;
  1278. },
  1279. setEulerFromRotationMatrix: function ( m, order ) {
  1280. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1281. },
  1282. setEulerFromQuaternion: function ( q, order ) {
  1283. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1284. },
  1285. getPositionFromMatrix: function ( m ) {
  1286. console.warn( "DEPRECATED: Vector3\'s .getPositionFromMatrix() has been renamed to .setFromMatrixPosition(). Please update your code." );
  1287. return this.setFromMatrixPosition( m );
  1288. },
  1289. getScaleFromMatrix: function ( m ) {
  1290. console.warn( "DEPRECATED: Vector3\'s .getScaleFromMatrix() has been renamed to .setFromMatrixScale(). Please update your code." );
  1291. return this.setFromMatrixScale( m );
  1292. },
  1293. getColumnFromMatrix: function ( index, matrix ) {
  1294. console.warn( "DEPRECATED: Vector3\'s .getColumnFromMatrix() has been renamed to .setFromMatrixColumn(). Please update your code." );
  1295. return this.setFromMatrixColumn( index, matrix );
  1296. },
  1297. setFromMatrixPosition: function ( m ) {
  1298. this.x = m.elements[ 12 ];
  1299. this.y = m.elements[ 13 ];
  1300. this.z = m.elements[ 14 ];
  1301. return this;
  1302. },
  1303. setFromMatrixScale: function ( m ) {
  1304. var sx = this.set( m.elements[ 0 ], m.elements[ 1 ], m.elements[ 2 ] ).length();
  1305. var sy = this.set( m.elements[ 4 ], m.elements[ 5 ], m.elements[ 6 ] ).length();
  1306. var sz = this.set( m.elements[ 8 ], m.elements[ 9 ], m.elements[ 10 ] ).length();
  1307. this.x = sx;
  1308. this.y = sy;
  1309. this.z = sz;
  1310. return this;
  1311. },
  1312. setFromMatrixColumn: function ( index, matrix ) {
  1313. var offset = index * 4;
  1314. var me = matrix.elements;
  1315. this.x = me[ offset ];
  1316. this.y = me[ offset + 1 ];
  1317. this.z = me[ offset + 2 ];
  1318. return this;
  1319. },
  1320. equals: function ( v ) {
  1321. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1322. },
  1323. fromArray: function ( array ) {
  1324. this.x = array[ 0 ];
  1325. this.y = array[ 1 ];
  1326. this.z = array[ 2 ];
  1327. return this;
  1328. },
  1329. toArray: function () {
  1330. return [ this.x, this.y, this.z ];
  1331. },
  1332. clone: function () {
  1333. return new THREE.Vector3( this.x, this.y, this.z );
  1334. }
  1335. };
  1336. /**
  1337. * @author supereggbert / http://www.paulbrunt.co.uk/
  1338. * @author philogb / http://blog.thejit.org/
  1339. * @author mikael emtinger / http://gomo.se/
  1340. * @author egraether / http://egraether.com/
  1341. * @author WestLangley / http://github.com/WestLangley
  1342. */
  1343. THREE.Vector4 = function ( x, y, z, w ) {
  1344. this.x = x || 0;
  1345. this.y = y || 0;
  1346. this.z = z || 0;
  1347. this.w = ( w !== undefined ) ? w : 1;
  1348. };
  1349. THREE.Vector4.prototype = {
  1350. constructor: THREE.Vector4,
  1351. set: function ( x, y, z, w ) {
  1352. this.x = x;
  1353. this.y = y;
  1354. this.z = z;
  1355. this.w = w;
  1356. return this;
  1357. },
  1358. setX: function ( x ) {
  1359. this.x = x;
  1360. return this;
  1361. },
  1362. setY: function ( y ) {
  1363. this.y = y;
  1364. return this;
  1365. },
  1366. setZ: function ( z ) {
  1367. this.z = z;
  1368. return this;
  1369. },
  1370. setW: function ( w ) {
  1371. this.w = w;
  1372. return this;
  1373. },
  1374. setComponent: function ( index, value ) {
  1375. switch ( index ) {
  1376. case 0: this.x = value; break;
  1377. case 1: this.y = value; break;
  1378. case 2: this.z = value; break;
  1379. case 3: this.w = value; break;
  1380. default: throw new Error( "index is out of range: " + index );
  1381. }
  1382. },
  1383. getComponent: function ( index ) {
  1384. switch ( index ) {
  1385. case 0: return this.x;
  1386. case 1: return this.y;
  1387. case 2: return this.z;
  1388. case 3: return this.w;
  1389. default: throw new Error( "index is out of range: " + index );
  1390. }
  1391. },
  1392. copy: function ( v ) {
  1393. this.x = v.x;
  1394. this.y = v.y;
  1395. this.z = v.z;
  1396. this.w = ( v.w !== undefined ) ? v.w : 1;
  1397. return this;
  1398. },
  1399. add: function ( v, w ) {
  1400. if ( w !== undefined ) {
  1401. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1402. return this.addVectors( v, w );
  1403. }
  1404. this.x += v.x;
  1405. this.y += v.y;
  1406. this.z += v.z;
  1407. this.w += v.w;
  1408. return this;
  1409. },
  1410. addScalar: function ( s ) {
  1411. this.x += s;
  1412. this.y += s;
  1413. this.z += s;
  1414. this.w += s;
  1415. return this;
  1416. },
  1417. addVectors: function ( a, b ) {
  1418. this.x = a.x + b.x;
  1419. this.y = a.y + b.y;
  1420. this.z = a.z + b.z;
  1421. this.w = a.w + b.w;
  1422. return this;
  1423. },
  1424. sub: function ( v, w ) {
  1425. if ( w !== undefined ) {
  1426. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1427. return this.subVectors( v, w );
  1428. }
  1429. this.x -= v.x;
  1430. this.y -= v.y;
  1431. this.z -= v.z;
  1432. this.w -= v.w;
  1433. return this;
  1434. },
  1435. subVectors: function ( a, b ) {
  1436. this.x = a.x - b.x;
  1437. this.y = a.y - b.y;
  1438. this.z = a.z - b.z;
  1439. this.w = a.w - b.w;
  1440. return this;
  1441. },
  1442. multiplyScalar: function ( scalar ) {
  1443. this.x *= scalar;
  1444. this.y *= scalar;
  1445. this.z *= scalar;
  1446. this.w *= scalar;
  1447. return this;
  1448. },
  1449. applyMatrix4: function ( m ) {
  1450. var x = this.x;
  1451. var y = this.y;
  1452. var z = this.z;
  1453. var w = this.w;
  1454. var e = m.elements;
  1455. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1456. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1457. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1458. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1459. return this;
  1460. },
  1461. divideScalar: function ( scalar ) {
  1462. if ( scalar !== 0 ) {
  1463. var invScalar = 1 / scalar;
  1464. this.x *= invScalar;
  1465. this.y *= invScalar;
  1466. this.z *= invScalar;
  1467. this.w *= invScalar;
  1468. } else {
  1469. this.x = 0;
  1470. this.y = 0;
  1471. this.z = 0;
  1472. this.w = 1;
  1473. }
  1474. return this;
  1475. },
  1476. setAxisAngleFromQuaternion: function ( q ) {
  1477. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1478. // q is assumed to be normalized
  1479. this.w = 2 * Math.acos( q.w );
  1480. var s = Math.sqrt( 1 - q.w * q.w );
  1481. if ( s < 0.0001 ) {
  1482. this.x = 1;
  1483. this.y = 0;
  1484. this.z = 0;
  1485. } else {
  1486. this.x = q.x / s;
  1487. this.y = q.y / s;
  1488. this.z = q.z / s;
  1489. }
  1490. return this;
  1491. },
  1492. setAxisAngleFromRotationMatrix: function ( m ) {
  1493. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1494. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1495. var angle, x, y, z, // variables for result
  1496. epsilon = 0.01, // margin to allow for rounding errors
  1497. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1498. te = m.elements,
  1499. m11 = te[0], m12 = te[4], m13 = te[8],
  1500. m21 = te[1], m22 = te[5], m23 = te[9],
  1501. m31 = te[2], m32 = te[6], m33 = te[10];
  1502. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1503. && ( Math.abs( m13 - m31 ) < epsilon )
  1504. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1505. // singularity found
  1506. // first check for identity matrix which must have +1 for all terms
  1507. // in leading diagonal and zero in other terms
  1508. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1509. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1510. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1511. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1512. // this singularity is identity matrix so angle = 0
  1513. this.set( 1, 0, 0, 0 );
  1514. return this; // zero angle, arbitrary axis
  1515. }
  1516. // otherwise this singularity is angle = 180
  1517. angle = Math.PI;
  1518. var xx = ( m11 + 1 ) / 2;
  1519. var yy = ( m22 + 1 ) / 2;
  1520. var zz = ( m33 + 1 ) / 2;
  1521. var xy = ( m12 + m21 ) / 4;
  1522. var xz = ( m13 + m31 ) / 4;
  1523. var yz = ( m23 + m32 ) / 4;
  1524. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1525. if ( xx < epsilon ) {
  1526. x = 0;
  1527. y = 0.707106781;
  1528. z = 0.707106781;
  1529. } else {
  1530. x = Math.sqrt( xx );
  1531. y = xy / x;
  1532. z = xz / x;
  1533. }
  1534. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1535. if ( yy < epsilon ) {
  1536. x = 0.707106781;
  1537. y = 0;
  1538. z = 0.707106781;
  1539. } else {
  1540. y = Math.sqrt( yy );
  1541. x = xy / y;
  1542. z = yz / y;
  1543. }
  1544. } else { // m33 is the largest diagonal term so base result on this
  1545. if ( zz < epsilon ) {
  1546. x = 0.707106781;
  1547. y = 0.707106781;
  1548. z = 0;
  1549. } else {
  1550. z = Math.sqrt( zz );
  1551. x = xz / z;
  1552. y = yz / z;
  1553. }
  1554. }
  1555. this.set( x, y, z, angle );
  1556. return this; // return 180 deg rotation
  1557. }
  1558. // as we have reached here there are no singularities so we can handle normally
  1559. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1560. + ( m13 - m31 ) * ( m13 - m31 )
  1561. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1562. if ( Math.abs( s ) < 0.001 ) s = 1;
  1563. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1564. // caught by singularity test above, but I've left it in just in case
  1565. this.x = ( m32 - m23 ) / s;
  1566. this.y = ( m13 - m31 ) / s;
  1567. this.z = ( m21 - m12 ) / s;
  1568. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1569. return this;
  1570. },
  1571. min: function ( v ) {
  1572. if ( this.x > v.x ) {
  1573. this.x = v.x;
  1574. }
  1575. if ( this.y > v.y ) {
  1576. this.y = v.y;
  1577. }
  1578. if ( this.z > v.z ) {
  1579. this.z = v.z;
  1580. }
  1581. if ( this.w > v.w ) {
  1582. this.w = v.w;
  1583. }
  1584. return this;
  1585. },
  1586. max: function ( v ) {
  1587. if ( this.x < v.x ) {
  1588. this.x = v.x;
  1589. }
  1590. if ( this.y < v.y ) {
  1591. this.y = v.y;
  1592. }
  1593. if ( this.z < v.z ) {
  1594. this.z = v.z;
  1595. }
  1596. if ( this.w < v.w ) {
  1597. this.w = v.w;
  1598. }
  1599. return this;
  1600. },
  1601. clamp: function ( min, max ) {
  1602. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1603. if ( this.x < min.x ) {
  1604. this.x = min.x;
  1605. } else if ( this.x > max.x ) {
  1606. this.x = max.x;
  1607. }
  1608. if ( this.y < min.y ) {
  1609. this.y = min.y;
  1610. } else if ( this.y > max.y ) {
  1611. this.y = max.y;
  1612. }
  1613. if ( this.z < min.z ) {
  1614. this.z = min.z;
  1615. } else if ( this.z > max.z ) {
  1616. this.z = max.z;
  1617. }
  1618. if ( this.w < min.w ) {
  1619. this.w = min.w;
  1620. } else if ( this.w > max.w ) {
  1621. this.w = max.w;
  1622. }
  1623. return this;
  1624. },
  1625. clampScalar: ( function () {
  1626. var min, max;
  1627. return function ( minVal, maxVal ) {
  1628. if ( min === undefined ) {
  1629. min = new THREE.Vector4();
  1630. max = new THREE.Vector4();
  1631. }
  1632. min.set( minVal, minVal, minVal, minVal );
  1633. max.set( maxVal, maxVal, maxVal, maxVal );
  1634. return this.clamp( min, max );
  1635. };
  1636. } )(),
  1637. floor: function () {
  1638. this.x = Math.floor( this.x );
  1639. this.y = Math.floor( this.y );
  1640. this.z = Math.floor( this.z );
  1641. this.w = Math.floor( this.w );
  1642. return this;
  1643. },
  1644. ceil: function () {
  1645. this.x = Math.ceil( this.x );
  1646. this.y = Math.ceil( this.y );
  1647. this.z = Math.ceil( this.z );
  1648. this.w = Math.ceil( this.w );
  1649. return this;
  1650. },
  1651. round: function () {
  1652. this.x = Math.round( this.x );
  1653. this.y = Math.round( this.y );
  1654. this.z = Math.round( this.z );
  1655. this.w = Math.round( this.w );
  1656. return this;
  1657. },
  1658. roundToZero: function () {
  1659. this.x = ( this.x < 0 ) ? Math.ceil( this.x ) : Math.floor( this.x );
  1660. this.y = ( this.y < 0 ) ? Math.ceil( this.y ) : Math.floor( this.y );
  1661. this.z = ( this.z < 0 ) ? Math.ceil( this.z ) : Math.floor( this.z );
  1662. this.w = ( this.w < 0 ) ? Math.ceil( this.w ) : Math.floor( this.w );
  1663. return this;
  1664. },
  1665. negate: function () {
  1666. return this.multiplyScalar( -1 );
  1667. },
  1668. dot: function ( v ) {
  1669. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1670. },
  1671. lengthSq: function () {
  1672. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1673. },
  1674. length: function () {
  1675. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1676. },
  1677. lengthManhattan: function () {
  1678. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1679. },
  1680. normalize: function () {
  1681. return this.divideScalar( this.length() );
  1682. },
  1683. setLength: function ( l ) {
  1684. var oldLength = this.length();
  1685. if ( oldLength !== 0 && l !== oldLength ) {
  1686. this.multiplyScalar( l / oldLength );
  1687. }
  1688. return this;
  1689. },
  1690. lerp: function ( v, alpha ) {
  1691. this.x += ( v.x - this.x ) * alpha;
  1692. this.y += ( v.y - this.y ) * alpha;
  1693. this.z += ( v.z - this.z ) * alpha;
  1694. this.w += ( v.w - this.w ) * alpha;
  1695. return this;
  1696. },
  1697. equals: function ( v ) {
  1698. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1699. },
  1700. fromArray: function ( array ) {
  1701. this.x = array[ 0 ];
  1702. this.y = array[ 1 ];
  1703. this.z = array[ 2 ];
  1704. this.w = array[ 3 ];
  1705. return this;
  1706. },
  1707. toArray: function () {
  1708. return [ this.x, this.y, this.z, this.w ];
  1709. },
  1710. clone: function () {
  1711. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1712. }
  1713. };
  1714. /**
  1715. * @author mrdoob / http://mrdoob.com/
  1716. * @author WestLangley / http://github.com/WestLangley
  1717. * @author bhouston / http://exocortex.com
  1718. */
  1719. THREE.Euler = function ( x, y, z, order ) {
  1720. this._x = x || 0;
  1721. this._y = y || 0;
  1722. this._z = z || 0;
  1723. this._order = order || THREE.Euler.DefaultOrder;
  1724. };
  1725. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1726. THREE.Euler.DefaultOrder = 'XYZ';
  1727. THREE.Euler.prototype = {
  1728. constructor: THREE.Euler,
  1729. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1730. _quaternion: undefined,
  1731. _updateQuaternion: function () {
  1732. if ( this._quaternion !== undefined ) {
  1733. this._quaternion.setFromEuler( this, false );
  1734. }
  1735. },
  1736. get x () {
  1737. return this._x;
  1738. },
  1739. set x ( value ) {
  1740. this._x = value;
  1741. this._updateQuaternion();
  1742. },
  1743. get y () {
  1744. return this._y;
  1745. },
  1746. set y ( value ) {
  1747. this._y = value;
  1748. this._updateQuaternion();
  1749. },
  1750. get z () {
  1751. return this._z;
  1752. },
  1753. set z ( value ) {
  1754. this._z = value;
  1755. this._updateQuaternion();
  1756. },
  1757. get order () {
  1758. return this._order;
  1759. },
  1760. set order ( value ) {
  1761. this._order = value;
  1762. this._updateQuaternion();
  1763. },
  1764. set: function ( x, y, z, order ) {
  1765. this._x = x;
  1766. this._y = y;
  1767. this._z = z;
  1768. this._order = order || this._order;
  1769. this._updateQuaternion();
  1770. return this;
  1771. },
  1772. copy: function ( euler ) {
  1773. this._x = euler._x;
  1774. this._y = euler._y;
  1775. this._z = euler._z;
  1776. this._order = euler._order;
  1777. this._updateQuaternion();
  1778. return this;
  1779. },
  1780. setFromRotationMatrix: function ( m, order ) {
  1781. var clamp = THREE.Math.clamp;
  1782. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1783. var te = m.elements;
  1784. var m11 = te[0], m12 = te[4], m13 = te[8];
  1785. var m21 = te[1], m22 = te[5], m23 = te[9];
  1786. var m31 = te[2], m32 = te[6], m33 = te[10];
  1787. order = order || this._order;
  1788. if ( order === 'XYZ' ) {
  1789. this._y = Math.asin( clamp( m13, -1, 1 ) );
  1790. if ( Math.abs( m13 ) < 0.99999 ) {
  1791. this._x = Math.atan2( - m23, m33 );
  1792. this._z = Math.atan2( - m12, m11 );
  1793. } else {
  1794. this._x = Math.atan2( m32, m22 );
  1795. this._z = 0;
  1796. }
  1797. } else if ( order === 'YXZ' ) {
  1798. this._x = Math.asin( - clamp( m23, -1, 1 ) );
  1799. if ( Math.abs( m23 ) < 0.99999 ) {
  1800. this._y = Math.atan2( m13, m33 );
  1801. this._z = Math.atan2( m21, m22 );
  1802. } else {
  1803. this._y = Math.atan2( - m31, m11 );
  1804. this._z = 0;
  1805. }
  1806. } else if ( order === 'ZXY' ) {
  1807. this._x = Math.asin( clamp( m32, -1, 1 ) );
  1808. if ( Math.abs( m32 ) < 0.99999 ) {
  1809. this._y = Math.atan2( - m31, m33 );
  1810. this._z = Math.atan2( - m12, m22 );
  1811. } else {
  1812. this._y = 0;
  1813. this._z = Math.atan2( m21, m11 );
  1814. }
  1815. } else if ( order === 'ZYX' ) {
  1816. this._y = Math.asin( - clamp( m31, -1, 1 ) );
  1817. if ( Math.abs( m31 ) < 0.99999 ) {
  1818. this._x = Math.atan2( m32, m33 );
  1819. this._z = Math.atan2( m21, m11 );
  1820. } else {
  1821. this._x = 0;
  1822. this._z = Math.atan2( - m12, m22 );
  1823. }
  1824. } else if ( order === 'YZX' ) {
  1825. this._z = Math.asin( clamp( m21, -1, 1 ) );
  1826. if ( Math.abs( m21 ) < 0.99999 ) {
  1827. this._x = Math.atan2( - m23, m22 );
  1828. this._y = Math.atan2( - m31, m11 );
  1829. } else {
  1830. this._x = 0;
  1831. this._y = Math.atan2( m13, m33 );
  1832. }
  1833. } else if ( order === 'XZY' ) {
  1834. this._z = Math.asin( - clamp( m12, -1, 1 ) );
  1835. if ( Math.abs( m12 ) < 0.99999 ) {
  1836. this._x = Math.atan2( m32, m22 );
  1837. this._y = Math.atan2( m13, m11 );
  1838. } else {
  1839. this._x = Math.atan2( - m23, m33 );
  1840. this._y = 0;
  1841. }
  1842. } else {
  1843. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1844. }
  1845. this._order = order;
  1846. this._updateQuaternion();
  1847. return this;
  1848. },
  1849. setFromQuaternion: function ( q, order, update ) {
  1850. var clamp = THREE.Math.clamp;
  1851. // q is assumed to be normalized
  1852. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1853. var sqx = q.x * q.x;
  1854. var sqy = q.y * q.y;
  1855. var sqz = q.z * q.z;
  1856. var sqw = q.w * q.w;
  1857. order = order || this._order;
  1858. if ( order === 'XYZ' ) {
  1859. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1860. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ), -1, 1 ) );
  1861. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1862. } else if ( order === 'YXZ' ) {
  1863. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ), -1, 1 ) );
  1864. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1865. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1866. } else if ( order === 'ZXY' ) {
  1867. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ), -1, 1 ) );
  1868. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1869. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1870. } else if ( order === 'ZYX' ) {
  1871. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1872. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ), -1, 1 ) );
  1873. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1874. } else if ( order === 'YZX' ) {
  1875. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1876. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1877. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ), -1, 1 ) );
  1878. } else if ( order === 'XZY' ) {
  1879. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1880. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1881. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ), -1, 1 ) );
  1882. } else {
  1883. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1884. }
  1885. this._order = order;
  1886. if ( update !== false ) this._updateQuaternion();
  1887. return this;
  1888. },
  1889. reorder: function () {
  1890. // WARNING: this discards revolution information -bhouston
  1891. var q = new THREE.Quaternion();
  1892. return function ( newOrder ) {
  1893. q.setFromEuler( this );
  1894. this.setFromQuaternion( q, newOrder );
  1895. };
  1896. }(),
  1897. fromArray: function ( array ) {
  1898. this._x = array[ 0 ];
  1899. this._y = array[ 1 ];
  1900. this._z = array[ 2 ];
  1901. if ( array[ 3 ] !== undefined ) this._order = array[ 3 ];
  1902. this._updateQuaternion();
  1903. return this;
  1904. },
  1905. toArray: function () {
  1906. return [ this._x, this._y, this._z, this._order ];
  1907. },
  1908. equals: function ( euler ) {
  1909. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1910. },
  1911. clone: function () {
  1912. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1913. }
  1914. };
  1915. /**
  1916. * @author bhouston / http://exocortex.com
  1917. */
  1918. THREE.Line3 = function ( start, end ) {
  1919. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1920. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1921. };
  1922. THREE.Line3.prototype = {
  1923. constructor: THREE.Line3,
  1924. set: function ( start, end ) {
  1925. this.start.copy( start );
  1926. this.end.copy( end );
  1927. return this;
  1928. },
  1929. copy: function ( line ) {
  1930. this.start.copy( line.start );
  1931. this.end.copy( line.end );
  1932. return this;
  1933. },
  1934. center: function ( optionalTarget ) {
  1935. var result = optionalTarget || new THREE.Vector3();
  1936. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1937. },
  1938. delta: function ( optionalTarget ) {
  1939. var result = optionalTarget || new THREE.Vector3();
  1940. return result.subVectors( this.end, this.start );
  1941. },
  1942. distanceSq: function () {
  1943. return this.start.distanceToSquared( this.end );
  1944. },
  1945. distance: function () {
  1946. return this.start.distanceTo( this.end );
  1947. },
  1948. at: function ( t, optionalTarget ) {
  1949. var result = optionalTarget || new THREE.Vector3();
  1950. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1951. },
  1952. closestPointToPointParameter: function() {
  1953. var startP = new THREE.Vector3();
  1954. var startEnd = new THREE.Vector3();
  1955. return function ( point, clampToLine ) {
  1956. startP.subVectors( point, this.start );
  1957. startEnd.subVectors( this.end, this.start );
  1958. var startEnd2 = startEnd.dot( startEnd );
  1959. var startEnd_startP = startEnd.dot( startP );
  1960. var t = startEnd_startP / startEnd2;
  1961. if ( clampToLine ) {
  1962. t = THREE.Math.clamp( t, 0, 1 );
  1963. }
  1964. return t;
  1965. };
  1966. }(),
  1967. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1968. var t = this.closestPointToPointParameter( point, clampToLine );
  1969. var result = optionalTarget || new THREE.Vector3();
  1970. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1971. },
  1972. applyMatrix4: function ( matrix ) {
  1973. this.start.applyMatrix4( matrix );
  1974. this.end.applyMatrix4( matrix );
  1975. return this;
  1976. },
  1977. equals: function ( line ) {
  1978. return line.start.equals( this.start ) && line.end.equals( this.end );
  1979. },
  1980. clone: function () {
  1981. return new THREE.Line3().copy( this );
  1982. }
  1983. };
  1984. /**
  1985. * @author bhouston / http://exocortex.com
  1986. */
  1987. THREE.Box2 = function ( min, max ) {
  1988. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1989. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1990. };
  1991. THREE.Box2.prototype = {
  1992. constructor: THREE.Box2,
  1993. set: function ( min, max ) {
  1994. this.min.copy( min );
  1995. this.max.copy( max );
  1996. return this;
  1997. },
  1998. setFromPoints: function ( points ) {
  1999. if ( points.length > 0 ) {
  2000. var point = points[ 0 ];
  2001. this.min.copy( point );
  2002. this.max.copy( point );
  2003. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2004. point = points[ i ];
  2005. if ( point.x < this.min.x ) {
  2006. this.min.x = point.x;
  2007. } else if ( point.x > this.max.x ) {
  2008. this.max.x = point.x;
  2009. }
  2010. if ( point.y < this.min.y ) {
  2011. this.min.y = point.y;
  2012. } else if ( point.y > this.max.y ) {
  2013. this.max.y = point.y;
  2014. }
  2015. }
  2016. } else {
  2017. this.makeEmpty();
  2018. }
  2019. return this;
  2020. },
  2021. setFromCenterAndSize: function () {
  2022. var v1 = new THREE.Vector2();
  2023. return function ( center, size ) {
  2024. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2025. this.min.copy( center ).sub( halfSize );
  2026. this.max.copy( center ).add( halfSize );
  2027. return this;
  2028. };
  2029. }(),
  2030. copy: function ( box ) {
  2031. this.min.copy( box.min );
  2032. this.max.copy( box.max );
  2033. return this;
  2034. },
  2035. makeEmpty: function () {
  2036. this.min.x = this.min.y = Infinity;
  2037. this.max.x = this.max.y = -Infinity;
  2038. return this;
  2039. },
  2040. empty: function () {
  2041. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2042. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  2043. },
  2044. center: function ( optionalTarget ) {
  2045. var result = optionalTarget || new THREE.Vector2();
  2046. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2047. },
  2048. size: function ( optionalTarget ) {
  2049. var result = optionalTarget || new THREE.Vector2();
  2050. return result.subVectors( this.max, this.min );
  2051. },
  2052. expandByPoint: function ( point ) {
  2053. this.min.min( point );
  2054. this.max.max( point );
  2055. return this;
  2056. },
  2057. expandByVector: function ( vector ) {
  2058. this.min.sub( vector );
  2059. this.max.add( vector );
  2060. return this;
  2061. },
  2062. expandByScalar: function ( scalar ) {
  2063. this.min.addScalar( -scalar );
  2064. this.max.addScalar( scalar );
  2065. return this;
  2066. },
  2067. containsPoint: function ( point ) {
  2068. if ( point.x < this.min.x || point.x > this.max.x ||
  2069. point.y < this.min.y || point.y > this.max.y ) {
  2070. return false;
  2071. }
  2072. return true;
  2073. },
  2074. containsBox: function ( box ) {
  2075. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2076. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  2077. return true;
  2078. }
  2079. return false;
  2080. },
  2081. getParameter: function ( point, optionalTarget ) {
  2082. // This can potentially have a divide by zero if the box
  2083. // has a size dimension of 0.
  2084. var result = optionalTarget || new THREE.Vector2();
  2085. return result.set(
  2086. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2087. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  2088. );
  2089. },
  2090. isIntersectionBox: function ( box ) {
  2091. // using 6 splitting planes to rule out intersections.
  2092. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2093. box.max.y < this.min.y || box.min.y > this.max.y ) {
  2094. return false;
  2095. }
  2096. return true;
  2097. },
  2098. clampPoint: function ( point, optionalTarget ) {
  2099. var result = optionalTarget || new THREE.Vector2();
  2100. return result.copy( point ).clamp( this.min, this.max );
  2101. },
  2102. distanceToPoint: function () {
  2103. var v1 = new THREE.Vector2();
  2104. return function ( point ) {
  2105. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2106. return clampedPoint.sub( point ).length();
  2107. };
  2108. }(),
  2109. intersect: function ( box ) {
  2110. this.min.max( box.min );
  2111. this.max.min( box.max );
  2112. return this;
  2113. },
  2114. union: function ( box ) {
  2115. this.min.min( box.min );
  2116. this.max.max( box.max );
  2117. return this;
  2118. },
  2119. translate: function ( offset ) {
  2120. this.min.add( offset );
  2121. this.max.add( offset );
  2122. return this;
  2123. },
  2124. equals: function ( box ) {
  2125. return box.min.equals( this.min ) && box.max.equals( this.max );
  2126. },
  2127. clone: function () {
  2128. return new THREE.Box2().copy( this );
  2129. }
  2130. };
  2131. /**
  2132. * @author bhouston / http://exocortex.com
  2133. * @author WestLangley / http://github.com/WestLangley
  2134. */
  2135. THREE.Box3 = function ( min, max ) {
  2136. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  2137. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  2138. };
  2139. THREE.Box3.prototype = {
  2140. constructor: THREE.Box3,
  2141. set: function ( min, max ) {
  2142. this.min.copy( min );
  2143. this.max.copy( max );
  2144. return this;
  2145. },
  2146. addPoint: function ( point ) {
  2147. if ( point.x < this.min.x ) {
  2148. this.min.x = point.x;
  2149. } else if ( point.x > this.max.x ) {
  2150. this.max.x = point.x;
  2151. }
  2152. if ( point.y < this.min.y ) {
  2153. this.min.y = point.y;
  2154. } else if ( point.y > this.max.y ) {
  2155. this.max.y = point.y;
  2156. }
  2157. if ( point.z < this.min.z ) {
  2158. this.min.z = point.z;
  2159. } else if ( point.z > this.max.z ) {
  2160. this.max.z = point.z;
  2161. }
  2162. },
  2163. setFromPoints: function ( points ) {
  2164. if ( points.length > 0 ) {
  2165. var point = points[ 0 ];
  2166. this.min.copy( point );
  2167. this.max.copy( point );
  2168. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2169. this.addPoint( points[ i ] )
  2170. }
  2171. } else {
  2172. this.makeEmpty();
  2173. }
  2174. return this;
  2175. },
  2176. setFromCenterAndSize: function() {
  2177. var v1 = new THREE.Vector3();
  2178. return function ( center, size ) {
  2179. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2180. this.min.copy( center ).sub( halfSize );
  2181. this.max.copy( center ).add( halfSize );
  2182. return this;
  2183. };
  2184. }(),
  2185. setFromObject: function() {
  2186. // Computes the world-axis-aligned bounding box of an object (including its children),
  2187. // accounting for both the object's, and childrens', world transforms
  2188. var v1 = new THREE.Vector3();
  2189. return function( object ) {
  2190. var scope = this;
  2191. object.updateMatrixWorld( true );
  2192. this.makeEmpty();
  2193. object.traverse( function ( node ) {
  2194. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2195. var vertices = node.geometry.vertices;
  2196. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2197. v1.copy( vertices[ i ] );
  2198. v1.applyMatrix4( node.matrixWorld );
  2199. scope.expandByPoint( v1 );
  2200. }
  2201. }
  2202. } );
  2203. return this;
  2204. };
  2205. }(),
  2206. copy: function ( box ) {
  2207. this.min.copy( box.min );
  2208. this.max.copy( box.max );
  2209. return this;
  2210. },
  2211. makeEmpty: function () {
  2212. this.min.x = this.min.y = this.min.z = Infinity;
  2213. this.max.x = this.max.y = this.max.z = -Infinity;
  2214. return this;
  2215. },
  2216. empty: function () {
  2217. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2218. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2219. },
  2220. center: function ( optionalTarget ) {
  2221. var result = optionalTarget || new THREE.Vector3();
  2222. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2223. },
  2224. size: function ( optionalTarget ) {
  2225. var result = optionalTarget || new THREE.Vector3();
  2226. return result.subVectors( this.max, this.min );
  2227. },
  2228. expandByPoint: function ( point ) {
  2229. this.min.min( point );
  2230. this.max.max( point );
  2231. return this;
  2232. },
  2233. expandByVector: function ( vector ) {
  2234. this.min.sub( vector );
  2235. this.max.add( vector );
  2236. return this;
  2237. },
  2238. expandByScalar: function ( scalar ) {
  2239. this.min.addScalar( -scalar );
  2240. this.max.addScalar( scalar );
  2241. return this;
  2242. },
  2243. containsPoint: function ( point ) {
  2244. if ( point.x < this.min.x || point.x > this.max.x ||
  2245. point.y < this.min.y || point.y > this.max.y ||
  2246. point.z < this.min.z || point.z > this.max.z ) {
  2247. return false;
  2248. }
  2249. return true;
  2250. },
  2251. containsBox: function ( box ) {
  2252. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2253. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2254. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2255. return true;
  2256. }
  2257. return false;
  2258. },
  2259. getParameter: function ( point, optionalTarget ) {
  2260. // This can potentially have a divide by zero if the box
  2261. // has a size dimension of 0.
  2262. var result = optionalTarget || new THREE.Vector3();
  2263. return result.set(
  2264. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2265. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2266. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2267. );
  2268. },
  2269. isIntersectionBox: function ( box ) {
  2270. // using 6 splitting planes to rule out intersections.
  2271. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2272. box.max.y < this.min.y || box.min.y > this.max.y ||
  2273. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2274. return false;
  2275. }
  2276. return true;
  2277. },
  2278. clampPoint: function ( point, optionalTarget ) {
  2279. var result = optionalTarget || new THREE.Vector3();
  2280. return result.copy( point ).clamp( this.min, this.max );
  2281. },
  2282. distanceToPoint: function() {
  2283. var v1 = new THREE.Vector3();
  2284. return function ( point ) {
  2285. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2286. return clampedPoint.sub( point ).length();
  2287. };
  2288. }(),
  2289. getBoundingSphere: function() {
  2290. var v1 = new THREE.Vector3();
  2291. return function ( optionalTarget ) {
  2292. var result = optionalTarget || new THREE.Sphere();
  2293. result.center = this.center();
  2294. result.radius = this.size( v1 ).length() * 0.5;
  2295. return result;
  2296. };
  2297. }(),
  2298. intersect: function ( box ) {
  2299. this.min.max( box.min );
  2300. this.max.min( box.max );
  2301. return this;
  2302. },
  2303. union: function ( box ) {
  2304. this.min.min( box.min );
  2305. this.max.max( box.max );
  2306. return this;
  2307. },
  2308. applyMatrix4: function() {
  2309. var points = [
  2310. new THREE.Vector3(),
  2311. new THREE.Vector3(),
  2312. new THREE.Vector3(),
  2313. new THREE.Vector3(),
  2314. new THREE.Vector3(),
  2315. new THREE.Vector3(),
  2316. new THREE.Vector3(),
  2317. new THREE.Vector3()
  2318. ];
  2319. return function ( matrix ) {
  2320. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2321. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2322. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2323. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2324. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2325. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2326. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2327. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2328. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2329. this.makeEmpty();
  2330. this.setFromPoints( points );
  2331. return this;
  2332. };
  2333. }(),
  2334. translate: function ( offset ) {
  2335. this.min.add( offset );
  2336. this.max.add( offset );
  2337. return this;
  2338. },
  2339. equals: function ( box ) {
  2340. return box.min.equals( this.min ) && box.max.equals( this.max );
  2341. },
  2342. clone: function () {
  2343. return new THREE.Box3().copy( this );
  2344. }
  2345. };
  2346. /**
  2347. * @author alteredq / http://alteredqualia.com/
  2348. * @author WestLangley / http://github.com/WestLangley
  2349. * @author bhouston / http://exocortex.com
  2350. */
  2351. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2352. this.elements = new Float32Array(9);
  2353. this.set(
  2354. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2355. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2356. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2357. );
  2358. };
  2359. THREE.Matrix3.prototype = {
  2360. constructor: THREE.Matrix3,
  2361. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2362. var te = this.elements;
  2363. te[0] = n11; te[3] = n12; te[6] = n13;
  2364. te[1] = n21; te[4] = n22; te[7] = n23;
  2365. te[2] = n31; te[5] = n32; te[8] = n33;
  2366. return this;
  2367. },
  2368. identity: function () {
  2369. this.set(
  2370. 1, 0, 0,
  2371. 0, 1, 0,
  2372. 0, 0, 1
  2373. );
  2374. return this;
  2375. },
  2376. copy: function ( m ) {
  2377. var me = m.elements;
  2378. this.set(
  2379. me[0], me[3], me[6],
  2380. me[1], me[4], me[7],
  2381. me[2], me[5], me[8]
  2382. );
  2383. return this;
  2384. },
  2385. multiplyVector3: function ( vector ) {
  2386. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2387. return vector.applyMatrix3( this );
  2388. },
  2389. multiplyVector3Array: function ( a ) {
  2390. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2391. return this.applyToVector3Array( a );
  2392. },
  2393. applyToVector3Array: function() {
  2394. var v1 = new THREE.Vector3();
  2395. return function ( a ) {
  2396. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2397. v1.x = a[ i ];
  2398. v1.y = a[ i + 1 ];
  2399. v1.z = a[ i + 2 ];
  2400. v1.applyMatrix3( this );
  2401. a[ i ] = v1.x;
  2402. a[ i + 1 ] = v1.y;
  2403. a[ i + 2 ] = v1.z;
  2404. }
  2405. return a;
  2406. };
  2407. }(),
  2408. multiplyScalar: function ( s ) {
  2409. var te = this.elements;
  2410. te[0] *= s; te[3] *= s; te[6] *= s;
  2411. te[1] *= s; te[4] *= s; te[7] *= s;
  2412. te[2] *= s; te[5] *= s; te[8] *= s;
  2413. return this;
  2414. },
  2415. determinant: function () {
  2416. var te = this.elements;
  2417. var a = te[0], b = te[1], c = te[2],
  2418. d = te[3], e = te[4], f = te[5],
  2419. g = te[6], h = te[7], i = te[8];
  2420. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2421. },
  2422. getInverse: function ( matrix, throwOnInvertible ) {
  2423. // input: THREE.Matrix4
  2424. // ( based on http://code.google.com/p/webgl-mjs/ )
  2425. var me = matrix.elements;
  2426. var te = this.elements;
  2427. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2428. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2429. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2430. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2431. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2432. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2433. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2434. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2435. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2436. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2437. // no inverse
  2438. if ( det === 0 ) {
  2439. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2440. if ( throwOnInvertible || false ) {
  2441. throw new Error( msg );
  2442. } else {
  2443. console.warn( msg );
  2444. }
  2445. this.identity();
  2446. return this;
  2447. }
  2448. this.multiplyScalar( 1.0 / det );
  2449. return this;
  2450. },
  2451. transpose: function () {
  2452. var tmp, m = this.elements;
  2453. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2454. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2455. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2456. return this;
  2457. },
  2458. getNormalMatrix: function ( m ) {
  2459. // input: THREE.Matrix4
  2460. this.getInverse( m ).transpose();
  2461. return this;
  2462. },
  2463. transposeIntoArray: function ( r ) {
  2464. var m = this.elements;
  2465. r[ 0 ] = m[ 0 ];
  2466. r[ 1 ] = m[ 3 ];
  2467. r[ 2 ] = m[ 6 ];
  2468. r[ 3 ] = m[ 1 ];
  2469. r[ 4 ] = m[ 4 ];
  2470. r[ 5 ] = m[ 7 ];
  2471. r[ 6 ] = m[ 2 ];
  2472. r[ 7 ] = m[ 5 ];
  2473. r[ 8 ] = m[ 8 ];
  2474. return this;
  2475. },
  2476. fromArray: function ( array ) {
  2477. this.elements.set( array );
  2478. return this;
  2479. },
  2480. toArray: function () {
  2481. var te = this.elements;
  2482. return [
  2483. te[ 0 ], te[ 1 ], te[ 2 ],
  2484. te[ 3 ], te[ 4 ], te[ 5 ],
  2485. te[ 6 ], te[ 7 ], te[ 8 ]
  2486. ];
  2487. },
  2488. clone: function () {
  2489. var te = this.elements;
  2490. return new THREE.Matrix3(
  2491. te[0], te[3], te[6],
  2492. te[1], te[4], te[7],
  2493. te[2], te[5], te[8]
  2494. );
  2495. }
  2496. };
  2497. /**
  2498. * @author mrdoob / http://mrdoob.com/
  2499. * @author supereggbert / http://www.paulbrunt.co.uk/
  2500. * @author philogb / http://blog.thejit.org/
  2501. * @author jordi_ros / http://plattsoft.com
  2502. * @author D1plo1d / http://github.com/D1plo1d
  2503. * @author alteredq / http://alteredqualia.com/
  2504. * @author mikael emtinger / http://gomo.se/
  2505. * @author timknip / http://www.floorplanner.com/
  2506. * @author bhouston / http://exocortex.com
  2507. * @author WestLangley / http://github.com/WestLangley
  2508. */
  2509. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2510. this.elements = new Float32Array( 16 );
  2511. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2512. // we should not support semi specification of Matrix4, it is just weird.
  2513. var te = this.elements;
  2514. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2515. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2516. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2517. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2518. };
  2519. THREE.Matrix4.prototype = {
  2520. constructor: THREE.Matrix4,
  2521. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2522. var te = this.elements;
  2523. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2524. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2525. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2526. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2527. return this;
  2528. },
  2529. identity: function () {
  2530. this.set(
  2531. 1, 0, 0, 0,
  2532. 0, 1, 0, 0,
  2533. 0, 0, 1, 0,
  2534. 0, 0, 0, 1
  2535. );
  2536. return this;
  2537. },
  2538. copy: function ( m ) {
  2539. this.elements.set( m.elements );
  2540. return this;
  2541. },
  2542. extractPosition: function ( m ) {
  2543. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2544. return this.copyPosition( m );
  2545. },
  2546. copyPosition: function ( m ) {
  2547. var te = this.elements;
  2548. var me = m.elements;
  2549. te[12] = me[12];
  2550. te[13] = me[13];
  2551. te[14] = me[14];
  2552. return this;
  2553. },
  2554. extractRotation: function () {
  2555. var v1 = new THREE.Vector3();
  2556. return function ( m ) {
  2557. var te = this.elements;
  2558. var me = m.elements;
  2559. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2560. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2561. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2562. te[0] = me[0] * scaleX;
  2563. te[1] = me[1] * scaleX;
  2564. te[2] = me[2] * scaleX;
  2565. te[4] = me[4] * scaleY;
  2566. te[5] = me[5] * scaleY;
  2567. te[6] = me[6] * scaleY;
  2568. te[8] = me[8] * scaleZ;
  2569. te[9] = me[9] * scaleZ;
  2570. te[10] = me[10] * scaleZ;
  2571. return this;
  2572. };
  2573. }(),
  2574. makeRotationFromEuler: function ( euler ) {
  2575. if ( euler instanceof THREE.Euler === false ) {
  2576. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2577. }
  2578. var te = this.elements;
  2579. var x = euler.x, y = euler.y, z = euler.z;
  2580. var a = Math.cos( x ), b = Math.sin( x );
  2581. var c = Math.cos( y ), d = Math.sin( y );
  2582. var e = Math.cos( z ), f = Math.sin( z );
  2583. if ( euler.order === 'XYZ' ) {
  2584. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2585. te[0] = c * e;
  2586. te[4] = - c * f;
  2587. te[8] = d;
  2588. te[1] = af + be * d;
  2589. te[5] = ae - bf * d;
  2590. te[9] = - b * c;
  2591. te[2] = bf - ae * d;
  2592. te[6] = be + af * d;
  2593. te[10] = a * c;
  2594. } else if ( euler.order === 'YXZ' ) {
  2595. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2596. te[0] = ce + df * b;
  2597. te[4] = de * b - cf;
  2598. te[8] = a * d;
  2599. te[1] = a * f;
  2600. te[5] = a * e;
  2601. te[9] = - b;
  2602. te[2] = cf * b - de;
  2603. te[6] = df + ce * b;
  2604. te[10] = a * c;
  2605. } else if ( euler.order === 'ZXY' ) {
  2606. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2607. te[0] = ce - df * b;
  2608. te[4] = - a * f;
  2609. te[8] = de + cf * b;
  2610. te[1] = cf + de * b;
  2611. te[5] = a * e;
  2612. te[9] = df - ce * b;
  2613. te[2] = - a * d;
  2614. te[6] = b;
  2615. te[10] = a * c;
  2616. } else if ( euler.order === 'ZYX' ) {
  2617. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2618. te[0] = c * e;
  2619. te[4] = be * d - af;
  2620. te[8] = ae * d + bf;
  2621. te[1] = c * f;
  2622. te[5] = bf * d + ae;
  2623. te[9] = af * d - be;
  2624. te[2] = - d;
  2625. te[6] = b * c;
  2626. te[10] = a * c;
  2627. } else if ( euler.order === 'YZX' ) {
  2628. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2629. te[0] = c * e;
  2630. te[4] = bd - ac * f;
  2631. te[8] = bc * f + ad;
  2632. te[1] = f;
  2633. te[5] = a * e;
  2634. te[9] = - b * e;
  2635. te[2] = - d * e;
  2636. te[6] = ad * f + bc;
  2637. te[10] = ac - bd * f;
  2638. } else if ( euler.order === 'XZY' ) {
  2639. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2640. te[0] = c * e;
  2641. te[4] = - f;
  2642. te[8] = d * e;
  2643. te[1] = ac * f + bd;
  2644. te[5] = a * e;
  2645. te[9] = ad * f - bc;
  2646. te[2] = bc * f - ad;
  2647. te[6] = b * e;
  2648. te[10] = bd * f + ac;
  2649. }
  2650. // last column
  2651. te[3] = 0;
  2652. te[7] = 0;
  2653. te[11] = 0;
  2654. // bottom row
  2655. te[12] = 0;
  2656. te[13] = 0;
  2657. te[14] = 0;
  2658. te[15] = 1;
  2659. return this;
  2660. },
  2661. setRotationFromQuaternion: function ( q ) {
  2662. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2663. return this.makeRotationFromQuaternion( q );
  2664. },
  2665. makeRotationFromQuaternion: function ( q ) {
  2666. var te = this.elements;
  2667. var x = q.x, y = q.y, z = q.z, w = q.w;
  2668. var x2 = x + x, y2 = y + y, z2 = z + z;
  2669. var xx = x * x2, xy = x * y2, xz = x * z2;
  2670. var yy = y * y2, yz = y * z2, zz = z * z2;
  2671. var wx = w * x2, wy = w * y2, wz = w * z2;
  2672. te[0] = 1 - ( yy + zz );
  2673. te[4] = xy - wz;
  2674. te[8] = xz + wy;
  2675. te[1] = xy + wz;
  2676. te[5] = 1 - ( xx + zz );
  2677. te[9] = yz - wx;
  2678. te[2] = xz - wy;
  2679. te[6] = yz + wx;
  2680. te[10] = 1 - ( xx + yy );
  2681. // last column
  2682. te[3] = 0;
  2683. te[7] = 0;
  2684. te[11] = 0;
  2685. // bottom row
  2686. te[12] = 0;
  2687. te[13] = 0;
  2688. te[14] = 0;
  2689. te[15] = 1;
  2690. return this;
  2691. },
  2692. lookAt: function() {
  2693. var x = new THREE.Vector3();
  2694. var y = new THREE.Vector3();
  2695. var z = new THREE.Vector3();
  2696. return function ( eye, target, up ) {
  2697. var te = this.elements;
  2698. z.subVectors( eye, target ).normalize();
  2699. if ( z.length() === 0 ) {
  2700. z.z = 1;
  2701. }
  2702. x.crossVectors( up, z ).normalize();
  2703. if ( x.length() === 0 ) {
  2704. z.x += 0.0001;
  2705. x.crossVectors( up, z ).normalize();
  2706. }
  2707. y.crossVectors( z, x );
  2708. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2709. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2710. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2711. return this;
  2712. };
  2713. }(),
  2714. multiply: function ( m, n ) {
  2715. if ( n !== undefined ) {
  2716. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2717. return this.multiplyMatrices( m, n );
  2718. }
  2719. return this.multiplyMatrices( this, m );
  2720. },
  2721. multiplyMatrices: function ( a, b ) {
  2722. var ae = a.elements;
  2723. var be = b.elements;
  2724. var te = this.elements;
  2725. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2726. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2727. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2728. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2729. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2730. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2731. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2732. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2733. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2734. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2735. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2736. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2737. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2738. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2739. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2740. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2741. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2742. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2743. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2744. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2745. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2746. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2747. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2748. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2749. return this;
  2750. },
  2751. multiplyToArray: function ( a, b, r ) {
  2752. var te = this.elements;
  2753. this.multiplyMatrices( a, b );
  2754. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2755. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2756. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2757. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2758. return this;
  2759. },
  2760. multiplyScalar: function ( s ) {
  2761. var te = this.elements;
  2762. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2763. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2764. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2765. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2766. return this;
  2767. },
  2768. multiplyVector3: function ( vector ) {
  2769. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2770. return vector.applyProjection( this );
  2771. },
  2772. multiplyVector4: function ( vector ) {
  2773. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2774. return vector.applyMatrix4( this );
  2775. },
  2776. multiplyVector3Array: function ( a ) {
  2777. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3Array() has been renamed. Use matrix.applyToVector3Array( array ) instead.' );
  2778. return this.applyToVector3Array( a );
  2779. },
  2780. applyToVector3Array: function() {
  2781. var v1 = new THREE.Vector3();
  2782. return function ( a ) {
  2783. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2784. v1.x = a[ i ];
  2785. v1.y = a[ i + 1 ];
  2786. v1.z = a[ i + 2 ];
  2787. v1.applyMatrix4( this );
  2788. a[ i ] = v1.x;
  2789. a[ i + 1 ] = v1.y;
  2790. a[ i + 2 ] = v1.z;
  2791. }
  2792. return a;
  2793. };
  2794. }(),
  2795. rotateAxis: function ( v ) {
  2796. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2797. v.transformDirection( this );
  2798. },
  2799. crossVector: function ( vector ) {
  2800. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2801. return vector.applyMatrix4( this );
  2802. },
  2803. determinant: function () {
  2804. var te = this.elements;
  2805. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2806. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2807. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2808. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2809. //TODO: make this more efficient
  2810. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2811. return (
  2812. n41 * (
  2813. +n14 * n23 * n32
  2814. -n13 * n24 * n32
  2815. -n14 * n22 * n33
  2816. +n12 * n24 * n33
  2817. +n13 * n22 * n34
  2818. -n12 * n23 * n34
  2819. ) +
  2820. n42 * (
  2821. +n11 * n23 * n34
  2822. -n11 * n24 * n33
  2823. +n14 * n21 * n33
  2824. -n13 * n21 * n34
  2825. +n13 * n24 * n31
  2826. -n14 * n23 * n31
  2827. ) +
  2828. n43 * (
  2829. +n11 * n24 * n32
  2830. -n11 * n22 * n34
  2831. -n14 * n21 * n32
  2832. +n12 * n21 * n34
  2833. +n14 * n22 * n31
  2834. -n12 * n24 * n31
  2835. ) +
  2836. n44 * (
  2837. -n13 * n22 * n31
  2838. -n11 * n23 * n32
  2839. +n11 * n22 * n33
  2840. +n13 * n21 * n32
  2841. -n12 * n21 * n33
  2842. +n12 * n23 * n31
  2843. )
  2844. );
  2845. },
  2846. transpose: function () {
  2847. var te = this.elements;
  2848. var tmp;
  2849. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2850. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2851. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2852. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2853. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2854. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2855. return this;
  2856. },
  2857. flattenToArray: function ( flat ) {
  2858. var te = this.elements;
  2859. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2860. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2861. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2862. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2863. return flat;
  2864. },
  2865. flattenToArrayOffset: function( flat, offset ) {
  2866. var te = this.elements;
  2867. flat[ offset ] = te[0];
  2868. flat[ offset + 1 ] = te[1];
  2869. flat[ offset + 2 ] = te[2];
  2870. flat[ offset + 3 ] = te[3];
  2871. flat[ offset + 4 ] = te[4];
  2872. flat[ offset + 5 ] = te[5];
  2873. flat[ offset + 6 ] = te[6];
  2874. flat[ offset + 7 ] = te[7];
  2875. flat[ offset + 8 ] = te[8];
  2876. flat[ offset + 9 ] = te[9];
  2877. flat[ offset + 10 ] = te[10];
  2878. flat[ offset + 11 ] = te[11];
  2879. flat[ offset + 12 ] = te[12];
  2880. flat[ offset + 13 ] = te[13];
  2881. flat[ offset + 14 ] = te[14];
  2882. flat[ offset + 15 ] = te[15];
  2883. return flat;
  2884. },
  2885. getPosition: function() {
  2886. var v1 = new THREE.Vector3();
  2887. return function () {
  2888. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.setFromMatrixPosition( matrix ) instead.' );
  2889. var te = this.elements;
  2890. return v1.set( te[12], te[13], te[14] );
  2891. };
  2892. }(),
  2893. setPosition: function ( v ) {
  2894. var te = this.elements;
  2895. te[12] = v.x;
  2896. te[13] = v.y;
  2897. te[14] = v.z;
  2898. return this;
  2899. },
  2900. getInverse: function ( m, throwOnInvertible ) {
  2901. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2902. var te = this.elements;
  2903. var me = m.elements;
  2904. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2905. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2906. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2907. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2908. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2909. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2910. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2911. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2912. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2913. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2914. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2915. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2916. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2917. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2918. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2919. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2920. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2921. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2922. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2923. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2924. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2925. if ( det == 0 ) {
  2926. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2927. if ( throwOnInvertible || false ) {
  2928. throw new Error( msg );
  2929. } else {
  2930. console.warn( msg );
  2931. }
  2932. this.identity();
  2933. return this;
  2934. }
  2935. this.multiplyScalar( 1 / det );
  2936. return this;
  2937. },
  2938. translate: function ( v ) {
  2939. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2940. },
  2941. rotateX: function ( angle ) {
  2942. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2943. },
  2944. rotateY: function ( angle ) {
  2945. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2946. },
  2947. rotateZ: function ( angle ) {
  2948. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2949. },
  2950. rotateByAxis: function ( axis, angle ) {
  2951. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2952. },
  2953. scale: function ( v ) {
  2954. var te = this.elements;
  2955. var x = v.x, y = v.y, z = v.z;
  2956. te[0] *= x; te[4] *= y; te[8] *= z;
  2957. te[1] *= x; te[5] *= y; te[9] *= z;
  2958. te[2] *= x; te[6] *= y; te[10] *= z;
  2959. te[3] *= x; te[7] *= y; te[11] *= z;
  2960. return this;
  2961. },
  2962. getMaxScaleOnAxis: function () {
  2963. var te = this.elements;
  2964. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2965. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2966. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2967. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2968. },
  2969. makeTranslation: function ( x, y, z ) {
  2970. this.set(
  2971. 1, 0, 0, x,
  2972. 0, 1, 0, y,
  2973. 0, 0, 1, z,
  2974. 0, 0, 0, 1
  2975. );
  2976. return this;
  2977. },
  2978. makeRotationX: function ( theta ) {
  2979. var c = Math.cos( theta ), s = Math.sin( theta );
  2980. this.set(
  2981. 1, 0, 0, 0,
  2982. 0, c, -s, 0,
  2983. 0, s, c, 0,
  2984. 0, 0, 0, 1
  2985. );
  2986. return this;
  2987. },
  2988. makeRotationY: function ( theta ) {
  2989. var c = Math.cos( theta ), s = Math.sin( theta );
  2990. this.set(
  2991. c, 0, s, 0,
  2992. 0, 1, 0, 0,
  2993. -s, 0, c, 0,
  2994. 0, 0, 0, 1
  2995. );
  2996. return this;
  2997. },
  2998. makeRotationZ: function ( theta ) {
  2999. var c = Math.cos( theta ), s = Math.sin( theta );
  3000. this.set(
  3001. c, -s, 0, 0,
  3002. s, c, 0, 0,
  3003. 0, 0, 1, 0,
  3004. 0, 0, 0, 1
  3005. );
  3006. return this;
  3007. },
  3008. makeRotationAxis: function ( axis, angle ) {
  3009. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  3010. var c = Math.cos( angle );
  3011. var s = Math.sin( angle );
  3012. var t = 1 - c;
  3013. var x = axis.x, y = axis.y, z = axis.z;
  3014. var tx = t * x, ty = t * y;
  3015. this.set(
  3016. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  3017. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  3018. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  3019. 0, 0, 0, 1
  3020. );
  3021. return this;
  3022. },
  3023. makeScale: function ( x, y, z ) {
  3024. this.set(
  3025. x, 0, 0, 0,
  3026. 0, y, 0, 0,
  3027. 0, 0, z, 0,
  3028. 0, 0, 0, 1
  3029. );
  3030. return this;
  3031. },
  3032. compose: function ( position, quaternion, scale ) {
  3033. this.makeRotationFromQuaternion( quaternion );
  3034. this.scale( scale );
  3035. this.setPosition( position );
  3036. return this;
  3037. },
  3038. decompose: function () {
  3039. var vector = new THREE.Vector3();
  3040. var matrix = new THREE.Matrix4();
  3041. return function ( position, quaternion, scale ) {
  3042. var te = this.elements;
  3043. var sx = vector.set( te[0], te[1], te[2] ).length();
  3044. var sy = vector.set( te[4], te[5], te[6] ).length();
  3045. var sz = vector.set( te[8], te[9], te[10] ).length();
  3046. // if determine is negative, we need to invert one scale
  3047. var det = this.determinant();
  3048. if( det < 0 ) {
  3049. sx = -sx;
  3050. }
  3051. position.x = te[12];
  3052. position.y = te[13];
  3053. position.z = te[14];
  3054. // scale the rotation part
  3055. matrix.elements.set( this.elements ); // at this point matrix is incomplete so we can't use .copy()
  3056. var invSX = 1 / sx;
  3057. var invSY = 1 / sy;
  3058. var invSZ = 1 / sz;
  3059. matrix.elements[0] *= invSX;
  3060. matrix.elements[1] *= invSX;
  3061. matrix.elements[2] *= invSX;
  3062. matrix.elements[4] *= invSY;
  3063. matrix.elements[5] *= invSY;
  3064. matrix.elements[6] *= invSY;
  3065. matrix.elements[8] *= invSZ;
  3066. matrix.elements[9] *= invSZ;
  3067. matrix.elements[10] *= invSZ;
  3068. quaternion.setFromRotationMatrix( matrix );
  3069. scale.x = sx;
  3070. scale.y = sy;
  3071. scale.z = sz;
  3072. return this;
  3073. };
  3074. }(),
  3075. makeFrustum: function ( left, right, bottom, top, near, far ) {
  3076. var te = this.elements;
  3077. var x = 2 * near / ( right - left );
  3078. var y = 2 * near / ( top - bottom );
  3079. var a = ( right + left ) / ( right - left );
  3080. var b = ( top + bottom ) / ( top - bottom );
  3081. var c = - ( far + near ) / ( far - near );
  3082. var d = - 2 * far * near / ( far - near );
  3083. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  3084. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  3085. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  3086. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  3087. return this;
  3088. },
  3089. makePerspective: function ( fov, aspect, near, far ) {
  3090. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  3091. var ymin = - ymax;
  3092. var xmin = ymin * aspect;
  3093. var xmax = ymax * aspect;
  3094. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  3095. },
  3096. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  3097. var te = this.elements;
  3098. var w = right - left;
  3099. var h = top - bottom;
  3100. var p = far - near;
  3101. var x = ( right + left ) / w;
  3102. var y = ( top + bottom ) / h;
  3103. var z = ( far + near ) / p;
  3104. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  3105. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  3106. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  3107. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  3108. return this;
  3109. },
  3110. fromArray: function ( array ) {
  3111. this.elements.set( array );
  3112. return this;
  3113. },
  3114. toArray: function () {
  3115. var te = this.elements;
  3116. return [
  3117. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  3118. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  3119. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  3120. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  3121. ];
  3122. },
  3123. clone: function () {
  3124. var te = this.elements;
  3125. return new THREE.Matrix4(
  3126. te[0], te[4], te[8], te[12],
  3127. te[1], te[5], te[9], te[13],
  3128. te[2], te[6], te[10], te[14],
  3129. te[3], te[7], te[11], te[15]
  3130. );
  3131. }
  3132. };
  3133. /**
  3134. * @author bhouston / http://exocortex.com
  3135. */
  3136. THREE.Ray = function ( origin, direction ) {
  3137. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  3138. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  3139. };
  3140. THREE.Ray.prototype = {
  3141. constructor: THREE.Ray,
  3142. set: function ( origin, direction ) {
  3143. this.origin.copy( origin );
  3144. this.direction.copy( direction );
  3145. return this;
  3146. },
  3147. copy: function ( ray ) {
  3148. this.origin.copy( ray.origin );
  3149. this.direction.copy( ray.direction );
  3150. return this;
  3151. },
  3152. at: function ( t, optionalTarget ) {
  3153. var result = optionalTarget || new THREE.Vector3();
  3154. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  3155. },
  3156. recast: function () {
  3157. var v1 = new THREE.Vector3();
  3158. return function ( t ) {
  3159. this.origin.copy( this.at( t, v1 ) );
  3160. return this;
  3161. };
  3162. }(),
  3163. closestPointToPoint: function ( point, optionalTarget ) {
  3164. var result = optionalTarget || new THREE.Vector3();
  3165. result.subVectors( point, this.origin );
  3166. var directionDistance = result.dot( this.direction );
  3167. if ( directionDistance < 0 ) {
  3168. return result.copy( this.origin );
  3169. }
  3170. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3171. },
  3172. distanceToPoint: function () {
  3173. var v1 = new THREE.Vector3();
  3174. return function ( point ) {
  3175. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3176. // point behind the ray
  3177. if ( directionDistance < 0 ) {
  3178. return this.origin.distanceTo( point );
  3179. }
  3180. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3181. return v1.distanceTo( point );
  3182. };
  3183. }(),
  3184. distanceSqToSegment: function( v0, v1, optionalPointOnRay, optionalPointOnSegment ) {
  3185. // from http://www.geometrictools.com/LibMathematics/Distance/Wm5DistRay3Segment3.cpp
  3186. // It returns the min distance between the ray and the segment
  3187. // defined by v0 and v1
  3188. // It can also set two optional targets :
  3189. // - The closest point on the ray
  3190. // - The closest point on the segment
  3191. var segCenter = v0.clone().add( v1 ).multiplyScalar( 0.5 );
  3192. var segDir = v1.clone().sub( v0 ).normalize();
  3193. var segExtent = v0.distanceTo( v1 ) * 0.5;
  3194. var diff = this.origin.clone().sub( segCenter );
  3195. var a01 = - this.direction.dot( segDir );
  3196. var b0 = diff.dot( this.direction );
  3197. var b1 = - diff.dot( segDir );
  3198. var c = diff.lengthSq();
  3199. var det = Math.abs( 1 - a01 * a01 );
  3200. var s0, s1, sqrDist, extDet;
  3201. if ( det >= 0 ) {
  3202. // The ray and segment are not parallel.
  3203. s0 = a01 * b1 - b0;
  3204. s1 = a01 * b0 - b1;
  3205. extDet = segExtent * det;
  3206. if ( s0 >= 0 ) {
  3207. if ( s1 >= - extDet ) {
  3208. if ( s1 <= extDet ) {
  3209. // region 0
  3210. // Minimum at interior points of ray and segment.
  3211. var invDet = 1 / det;
  3212. s0 *= invDet;
  3213. s1 *= invDet;
  3214. sqrDist = s0 * ( s0 + a01 * s1 + 2 * b0 ) + s1 * ( a01 * s0 + s1 + 2 * b1 ) + c;
  3215. } else {
  3216. // region 1
  3217. s1 = segExtent;
  3218. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3219. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3220. }
  3221. } else {
  3222. // region 5
  3223. s1 = - segExtent;
  3224. s0 = Math.max( 0, - ( a01 * s1 + b0) );
  3225. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3226. }
  3227. } else {
  3228. if ( s1 <= - extDet) {
  3229. // region 4
  3230. s0 = Math.max( 0, - ( - a01 * segExtent + b0 ) );
  3231. s1 = ( s0 > 0 ) ? - segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3232. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3233. } else if ( s1 <= extDet ) {
  3234. // region 3
  3235. s0 = 0;
  3236. s1 = Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3237. sqrDist = s1 * ( s1 + 2 * b1 ) + c;
  3238. } else {
  3239. // region 2
  3240. s0 = Math.max( 0, - ( a01 * segExtent + b0 ) );
  3241. s1 = ( s0 > 0 ) ? segExtent : Math.min( Math.max( - segExtent, - b1 ), segExtent );
  3242. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3243. }
  3244. }
  3245. } else {
  3246. // Ray and segment are parallel.
  3247. s1 = ( a01 > 0 ) ? - segExtent : segExtent;
  3248. s0 = Math.max( 0, - ( a01 * s1 + b0 ) );
  3249. sqrDist = - s0 * s0 + s1 * ( s1 + 2 * b1 ) + c;
  3250. }
  3251. if ( optionalPointOnRay ) {
  3252. optionalPointOnRay.copy( this.direction.clone().multiplyScalar( s0 ).add( this.origin ) );
  3253. }
  3254. if ( optionalPointOnSegment ) {
  3255. optionalPointOnSegment.copy( segDir.clone().multiplyScalar( s1 ).add( segCenter ) );
  3256. }
  3257. return sqrDist;
  3258. },
  3259. isIntersectionSphere: function ( sphere ) {
  3260. return this.distanceToPoint( sphere.center ) <= sphere.radius;
  3261. },
  3262. isIntersectionPlane: function ( plane ) {
  3263. // check if the ray lies on the plane first
  3264. var distToPoint = plane.distanceToPoint( this.origin );
  3265. if ( distToPoint === 0 ) {
  3266. return true;
  3267. }
  3268. var denominator = plane.normal.dot( this.direction );
  3269. if ( denominator * distToPoint < 0 ) {
  3270. return true
  3271. }
  3272. // ray origin is behind the plane (and is pointing behind it)
  3273. return false;
  3274. },
  3275. distanceToPlane: function ( plane ) {
  3276. var denominator = plane.normal.dot( this.direction );
  3277. if ( denominator == 0 ) {
  3278. // line is coplanar, return origin
  3279. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3280. return 0;
  3281. }
  3282. // Null is preferable to undefined since undefined means.... it is undefined
  3283. return null;
  3284. }
  3285. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3286. // Return if the ray never intersects the plane
  3287. return t >= 0 ? t : null;
  3288. },
  3289. intersectPlane: function ( plane, optionalTarget ) {
  3290. var t = this.distanceToPlane( plane );
  3291. if ( t === null ) {
  3292. return null;
  3293. }
  3294. return this.at( t, optionalTarget );
  3295. },
  3296. isIntersectionBox: function () {
  3297. var v = new THREE.Vector3();
  3298. return function ( box ) {
  3299. return this.intersectBox( box, v ) !== null;
  3300. }
  3301. }(),
  3302. intersectBox: function ( box , optionalTarget ) {
  3303. // http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
  3304. var tmin,tmax,tymin,tymax,tzmin,tzmax;
  3305. var invdirx = 1/this.direction.x,
  3306. invdiry = 1/this.direction.y,
  3307. invdirz = 1/this.direction.z;
  3308. var origin = this.origin;
  3309. if (invdirx >= 0) {
  3310. tmin = (box.min.x - origin.x) * invdirx;
  3311. tmax = (box.max.x - origin.x) * invdirx;
  3312. } else {
  3313. tmin = (box.max.x - origin.x) * invdirx;
  3314. tmax = (box.min.x - origin.x) * invdirx;
  3315. }
  3316. if (invdiry >= 0) {
  3317. tymin = (box.min.y - origin.y) * invdiry;
  3318. tymax = (box.max.y - origin.y) * invdiry;
  3319. } else {
  3320. tymin = (box.max.y - origin.y) * invdiry;
  3321. tymax = (box.min.y - origin.y) * invdiry;
  3322. }
  3323. if ((tmin > tymax) || (tymin > tmax)) return null;
  3324. // These lines also handle the case where tmin or tmax is NaN
  3325. // (result of 0 * Infinity). x !== x returns true if x is NaN
  3326. if (tymin > tmin || tmin !== tmin ) tmin = tymin;
  3327. if (tymax < tmax || tmax !== tmax ) tmax = tymax;
  3328. if (invdirz >= 0) {
  3329. tzmin = (box.min.z - origin.z) * invdirz;
  3330. tzmax = (box.max.z - origin.z) * invdirz;
  3331. } else {
  3332. tzmin = (box.max.z - origin.z) * invdirz;
  3333. tzmax = (box.min.z - origin.z) * invdirz;
  3334. }
  3335. if ((tmin > tzmax) || (tzmin > tmax)) return null;
  3336. if (tzmin > tmin || tmin !== tmin ) tmin = tzmin;
  3337. if (tzmax < tmax || tmax !== tmax ) tmax = tzmax;
  3338. //return point closest to the ray (positive side)
  3339. if ( tmax < 0 ) return null;
  3340. return this.at( tmin >= 0 ? tmin : tmax, optionalTarget );
  3341. },
  3342. intersectTriangle: function() {
  3343. // Compute the offset origin, edges, and normal.
  3344. var diff = new THREE.Vector3();
  3345. var edge1 = new THREE.Vector3();
  3346. var edge2 = new THREE.Vector3();
  3347. var normal = new THREE.Vector3();
  3348. return function ( a, b, c, backfaceCulling, optionalTarget ) {
  3349. // from http://www.geometrictools.com/LibMathematics/Intersection/Wm5IntrRay3Triangle3.cpp
  3350. edge1.subVectors( b, a );
  3351. edge2.subVectors( c, a );
  3352. normal.crossVectors( edge1, edge2 );
  3353. // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction,
  3354. // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by
  3355. // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2))
  3356. // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q))
  3357. // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N)
  3358. var DdN = this.direction.dot( normal );
  3359. var sign;
  3360. if ( DdN > 0 ) {
  3361. if ( backfaceCulling ) return null;
  3362. sign = 1;
  3363. } else if ( DdN < 0 ) {
  3364. sign = - 1;
  3365. DdN = - DdN;
  3366. } else {
  3367. return null;
  3368. }
  3369. diff.subVectors( this.origin, a );
  3370. var DdQxE2 = sign * this.direction.dot( edge2.crossVectors( diff, edge2 ) );
  3371. // b1 < 0, no intersection
  3372. if ( DdQxE2 < 0 ) {
  3373. return null;
  3374. }
  3375. var DdE1xQ = sign * this.direction.dot( edge1.cross( diff ) );
  3376. // b2 < 0, no intersection
  3377. if ( DdE1xQ < 0 ) {
  3378. return null;
  3379. }
  3380. // b1+b2 > 1, no intersection
  3381. if ( DdQxE2 + DdE1xQ > DdN ) {
  3382. return null;
  3383. }
  3384. // Line intersects triangle, check if ray does.
  3385. var QdN = - sign * diff.dot( normal );
  3386. // t < 0, no intersection
  3387. if ( QdN < 0 ) {
  3388. return null;
  3389. }
  3390. // Ray intersects triangle.
  3391. return this.at( QdN / DdN, optionalTarget );
  3392. }
  3393. }(),
  3394. applyMatrix4: function ( matrix4 ) {
  3395. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3396. this.origin.applyMatrix4( matrix4 );
  3397. this.direction.sub( this.origin );
  3398. this.direction.normalize();
  3399. return this;
  3400. },
  3401. equals: function ( ray ) {
  3402. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3403. },
  3404. clone: function () {
  3405. return new THREE.Ray().copy( this );
  3406. }
  3407. };
  3408. /**
  3409. * @author bhouston / http://exocortex.com
  3410. * @author mrdoob / http://mrdoob.com/
  3411. */
  3412. THREE.Sphere = function ( center, radius ) {
  3413. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3414. this.radius = ( radius !== undefined ) ? radius : 0;
  3415. };
  3416. THREE.Sphere.prototype = {
  3417. constructor: THREE.Sphere,
  3418. set: function ( center, radius ) {
  3419. this.center.copy( center );
  3420. this.radius = radius;
  3421. return this;
  3422. },
  3423. setFromPoints: function () {
  3424. var box = new THREE.Box3();
  3425. return function ( points, optionalCenter ) {
  3426. var center = this.center;
  3427. if ( optionalCenter !== undefined ) {
  3428. center.copy( optionalCenter );
  3429. } else {
  3430. box.setFromPoints( points ).center( center );
  3431. }
  3432. var maxRadiusSq = 0;
  3433. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3434. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( points[ i ] ) );
  3435. }
  3436. this.radius = Math.sqrt( maxRadiusSq );
  3437. return this;
  3438. };
  3439. }(),
  3440. copy: function ( sphere ) {
  3441. this.center.copy( sphere.center );
  3442. this.radius = sphere.radius;
  3443. return this;
  3444. },
  3445. empty: function () {
  3446. return ( this.radius <= 0 );
  3447. },
  3448. containsPoint: function ( point ) {
  3449. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3450. },
  3451. distanceToPoint: function ( point ) {
  3452. return ( point.distanceTo( this.center ) - this.radius );
  3453. },
  3454. intersectsSphere: function ( sphere ) {
  3455. var radiusSum = this.radius + sphere.radius;
  3456. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3457. },
  3458. clampPoint: function ( point, optionalTarget ) {
  3459. var deltaLengthSq = this.center.distanceToSquared( point );
  3460. var result = optionalTarget || new THREE.Vector3();
  3461. result.copy( point );
  3462. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3463. result.sub( this.center ).normalize();
  3464. result.multiplyScalar( this.radius ).add( this.center );
  3465. }
  3466. return result;
  3467. },
  3468. getBoundingBox: function ( optionalTarget ) {
  3469. var box = optionalTarget || new THREE.Box3();
  3470. box.set( this.center, this.center );
  3471. box.expandByScalar( this.radius );
  3472. return box;
  3473. },
  3474. applyMatrix4: function ( matrix ) {
  3475. this.center.applyMatrix4( matrix );
  3476. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3477. return this;
  3478. },
  3479. translate: function ( offset ) {
  3480. this.center.add( offset );
  3481. return this;
  3482. },
  3483. equals: function ( sphere ) {
  3484. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3485. },
  3486. clone: function () {
  3487. return new THREE.Sphere().copy( this );
  3488. }
  3489. };
  3490. /**
  3491. * @author mrdoob / http://mrdoob.com/
  3492. * @author alteredq / http://alteredqualia.com/
  3493. * @author bhouston / http://exocortex.com
  3494. */
  3495. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3496. this.planes = [
  3497. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3498. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3499. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3500. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3501. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3502. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3503. ];
  3504. };
  3505. THREE.Frustum.prototype = {
  3506. constructor: THREE.Frustum,
  3507. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3508. var planes = this.planes;
  3509. planes[0].copy( p0 );
  3510. planes[1].copy( p1 );
  3511. planes[2].copy( p2 );
  3512. planes[3].copy( p3 );
  3513. planes[4].copy( p4 );
  3514. planes[5].copy( p5 );
  3515. return this;
  3516. },
  3517. copy: function ( frustum ) {
  3518. var planes = this.planes;
  3519. for( var i = 0; i < 6; i ++ ) {
  3520. planes[i].copy( frustum.planes[i] );
  3521. }
  3522. return this;
  3523. },
  3524. setFromMatrix: function ( m ) {
  3525. var planes = this.planes;
  3526. var me = m.elements;
  3527. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3528. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3529. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3530. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3531. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3532. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3533. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3534. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3535. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3536. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3537. return this;
  3538. },
  3539. intersectsObject: function () {
  3540. var sphere = new THREE.Sphere();
  3541. return function ( object ) {
  3542. var geometry = object.geometry;
  3543. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  3544. sphere.copy( geometry.boundingSphere );
  3545. sphere.applyMatrix4( object.matrixWorld );
  3546. return this.intersectsSphere( sphere );
  3547. };
  3548. }(),
  3549. intersectsSphere: function ( sphere ) {
  3550. var planes = this.planes;
  3551. var center = sphere.center;
  3552. var negRadius = -sphere.radius;
  3553. for ( var i = 0; i < 6; i ++ ) {
  3554. var distance = planes[ i ].distanceToPoint( center );
  3555. if ( distance < negRadius ) {
  3556. return false;
  3557. }
  3558. }
  3559. return true;
  3560. },
  3561. intersectsBox : function() {
  3562. var p1 = new THREE.Vector3(),
  3563. p2 = new THREE.Vector3();
  3564. return function( box ) {
  3565. var planes = this.planes;
  3566. for ( var i = 0; i < 6 ; i ++ ) {
  3567. var plane = planes[i];
  3568. p1.x = plane.normal.x > 0 ? box.min.x : box.max.x;
  3569. p2.x = plane.normal.x > 0 ? box.max.x : box.min.x;
  3570. p1.y = plane.normal.y > 0 ? box.min.y : box.max.y;
  3571. p2.y = plane.normal.y > 0 ? box.max.y : box.min.y;
  3572. p1.z = plane.normal.z > 0 ? box.min.z : box.max.z;
  3573. p2.z = plane.normal.z > 0 ? box.max.z : box.min.z;
  3574. var d1 = plane.distanceToPoint( p1 );
  3575. var d2 = plane.distanceToPoint( p2 );
  3576. // if both outside plane, no intersection
  3577. if ( d1 < 0 && d2 < 0 ) {
  3578. return false;
  3579. }
  3580. }
  3581. return true;
  3582. };
  3583. }(),
  3584. containsPoint: function ( point ) {
  3585. var planes = this.planes;
  3586. for ( var i = 0; i < 6; i ++ ) {
  3587. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3588. return false;
  3589. }
  3590. }
  3591. return true;
  3592. },
  3593. clone: function () {
  3594. return new THREE.Frustum().copy( this );
  3595. }
  3596. };
  3597. /**
  3598. * @author bhouston / http://exocortex.com
  3599. */
  3600. THREE.Plane = function ( normal, constant ) {
  3601. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3602. this.constant = ( constant !== undefined ) ? constant : 0;
  3603. };
  3604. THREE.Plane.prototype = {
  3605. constructor: THREE.Plane,
  3606. set: function ( normal, constant ) {
  3607. this.normal.copy( normal );
  3608. this.constant = constant;
  3609. return this;
  3610. },
  3611. setComponents: function ( x, y, z, w ) {
  3612. this.normal.set( x, y, z );
  3613. this.constant = w;
  3614. return this;
  3615. },
  3616. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3617. this.normal.copy( normal );
  3618. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3619. return this;
  3620. },
  3621. setFromCoplanarPoints: function() {
  3622. var v1 = new THREE.Vector3();
  3623. var v2 = new THREE.Vector3();
  3624. return function ( a, b, c ) {
  3625. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3626. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3627. this.setFromNormalAndCoplanarPoint( normal, a );
  3628. return this;
  3629. };
  3630. }(),
  3631. copy: function ( plane ) {
  3632. this.normal.copy( plane.normal );
  3633. this.constant = plane.constant;
  3634. return this;
  3635. },
  3636. normalize: function () {
  3637. // Note: will lead to a divide by zero if the plane is invalid.
  3638. var inverseNormalLength = 1.0 / this.normal.length();
  3639. this.normal.multiplyScalar( inverseNormalLength );
  3640. this.constant *= inverseNormalLength;
  3641. return this;
  3642. },
  3643. negate: function () {
  3644. this.constant *= -1;
  3645. this.normal.negate();
  3646. return this;
  3647. },
  3648. distanceToPoint: function ( point ) {
  3649. return this.normal.dot( point ) + this.constant;
  3650. },
  3651. distanceToSphere: function ( sphere ) {
  3652. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3653. },
  3654. projectPoint: function ( point, optionalTarget ) {
  3655. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3656. },
  3657. orthoPoint: function ( point, optionalTarget ) {
  3658. var perpendicularMagnitude = this.distanceToPoint( point );
  3659. var result = optionalTarget || new THREE.Vector3();
  3660. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3661. },
  3662. isIntersectionLine: function ( line ) {
  3663. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3664. var startSign = this.distanceToPoint( line.start );
  3665. var endSign = this.distanceToPoint( line.end );
  3666. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3667. },
  3668. intersectLine: function() {
  3669. var v1 = new THREE.Vector3();
  3670. return function ( line, optionalTarget ) {
  3671. var result = optionalTarget || new THREE.Vector3();
  3672. var direction = line.delta( v1 );
  3673. var denominator = this.normal.dot( direction );
  3674. if ( denominator == 0 ) {
  3675. // line is coplanar, return origin
  3676. if( this.distanceToPoint( line.start ) == 0 ) {
  3677. return result.copy( line.start );
  3678. }
  3679. // Unsure if this is the correct method to handle this case.
  3680. return undefined;
  3681. }
  3682. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3683. if( t < 0 || t > 1 ) {
  3684. return undefined;
  3685. }
  3686. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3687. };
  3688. }(),
  3689. coplanarPoint: function ( optionalTarget ) {
  3690. var result = optionalTarget || new THREE.Vector3();
  3691. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3692. },
  3693. applyMatrix4: function() {
  3694. var v1 = new THREE.Vector3();
  3695. var v2 = new THREE.Vector3();
  3696. var m1 = new THREE.Matrix3();
  3697. return function ( matrix, optionalNormalMatrix ) {
  3698. // compute new normal based on theory here:
  3699. // http://www.songho.ca/opengl/gl_normaltransform.html
  3700. var normalMatrix = optionalNormalMatrix || m1.getNormalMatrix( matrix );
  3701. var newNormal = v1.copy( this.normal ).applyMatrix3( normalMatrix );
  3702. var newCoplanarPoint = this.coplanarPoint( v2 );
  3703. newCoplanarPoint.applyMatrix4( matrix );
  3704. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3705. return this;
  3706. };
  3707. }(),
  3708. translate: function ( offset ) {
  3709. this.constant = this.constant - offset.dot( this.normal );
  3710. return this;
  3711. },
  3712. equals: function ( plane ) {
  3713. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3714. },
  3715. clone: function () {
  3716. return new THREE.Plane().copy( this );
  3717. }
  3718. };
  3719. /**
  3720. * @author alteredq / http://alteredqualia.com/
  3721. * @author mrdoob / http://mrdoob.com/
  3722. */
  3723. THREE.Math = {
  3724. generateUUID: function () {
  3725. // http://www.broofa.com/Tools/Math.uuid.htm
  3726. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3727. var uuid = new Array(36);
  3728. var rnd = 0, r;
  3729. return function () {
  3730. for ( var i = 0; i < 36; i ++ ) {
  3731. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3732. uuid[ i ] = '-';
  3733. } else if ( i == 14 ) {
  3734. uuid[ i ] = '4';
  3735. } else {
  3736. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3737. r = rnd & 0xf;
  3738. rnd = rnd >> 4;
  3739. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3740. }
  3741. }
  3742. return uuid.join('');
  3743. };
  3744. }(),
  3745. // Clamp value to range <a, b>
  3746. clamp: function ( x, a, b ) {
  3747. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3748. },
  3749. // Clamp value to range <a, inf)
  3750. clampBottom: function ( x, a ) {
  3751. return x < a ? a : x;
  3752. },
  3753. // Linear mapping from range <a1, a2> to range <b1, b2>
  3754. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3755. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3756. },
  3757. // http://en.wikipedia.org/wiki/Smoothstep
  3758. smoothstep: function ( x, min, max ) {
  3759. if ( x <= min ) return 0;
  3760. if ( x >= max ) return 1;
  3761. x = ( x - min )/( max - min );
  3762. return x*x*(3 - 2*x);
  3763. },
  3764. smootherstep: function ( x, min, max ) {
  3765. if ( x <= min ) return 0;
  3766. if ( x >= max ) return 1;
  3767. x = ( x - min )/( max - min );
  3768. return x*x*x*(x*(x*6 - 15) + 10);
  3769. },
  3770. // Random float from <0, 1> with 16 bits of randomness
  3771. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3772. random16: function () {
  3773. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3774. },
  3775. // Random integer from <low, high> interval
  3776. randInt: function ( low, high ) {
  3777. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3778. },
  3779. // Random float from <low, high> interval
  3780. randFloat: function ( low, high ) {
  3781. return low + Math.random() * ( high - low );
  3782. },
  3783. // Random float from <-range/2, range/2> interval
  3784. randFloatSpread: function ( range ) {
  3785. return range * ( 0.5 - Math.random() );
  3786. },
  3787. sign: function ( x ) {
  3788. return ( x < 0 ) ? - 1 : ( x > 0 ) ? 1 : 0;
  3789. },
  3790. degToRad: function() {
  3791. var degreeToRadiansFactor = Math.PI / 180;
  3792. return function ( degrees ) {
  3793. return degrees * degreeToRadiansFactor;
  3794. };
  3795. }(),
  3796. radToDeg: function() {
  3797. var radianToDegreesFactor = 180 / Math.PI;
  3798. return function ( radians ) {
  3799. return radians * radianToDegreesFactor;
  3800. };
  3801. }(),
  3802. isPowerOfTwo: function ( value ) {
  3803. return ( value & ( value - 1 ) ) === 0 && value !== 0;
  3804. }
  3805. };
  3806. /**
  3807. * Spline from Tween.js, slightly optimized (and trashed)
  3808. * http://sole.github.com/tween.js/examples/05_spline.html
  3809. *
  3810. * @author mrdoob / http://mrdoob.com/
  3811. * @author alteredq / http://alteredqualia.com/
  3812. */
  3813. THREE.Spline = function ( points ) {
  3814. this.points = points;
  3815. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3816. point, intPoint, weight, w2, w3,
  3817. pa, pb, pc, pd;
  3818. this.initFromArray = function( a ) {
  3819. this.points = [];
  3820. for ( var i = 0; i < a.length; i++ ) {
  3821. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3822. }
  3823. };
  3824. this.getPoint = function ( k ) {
  3825. point = ( this.points.length - 1 ) * k;
  3826. intPoint = Math.floor( point );
  3827. weight = point - intPoint;
  3828. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3829. c[ 1 ] = intPoint;
  3830. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3831. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3832. pa = this.points[ c[ 0 ] ];
  3833. pb = this.points[ c[ 1 ] ];
  3834. pc = this.points[ c[ 2 ] ];
  3835. pd = this.points[ c[ 3 ] ];
  3836. w2 = weight * weight;
  3837. w3 = weight * w2;
  3838. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3839. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3840. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3841. return v3;
  3842. };
  3843. this.getControlPointsArray = function () {
  3844. var i, p, l = this.points.length,
  3845. coords = [];
  3846. for ( i = 0; i < l; i ++ ) {
  3847. p = this.points[ i ];
  3848. coords[ i ] = [ p.x, p.y, p.z ];
  3849. }
  3850. return coords;
  3851. };
  3852. // approximate length by summing linear segments
  3853. this.getLength = function ( nSubDivisions ) {
  3854. var i, index, nSamples, position,
  3855. point = 0, intPoint = 0, oldIntPoint = 0,
  3856. oldPosition = new THREE.Vector3(),
  3857. tmpVec = new THREE.Vector3(),
  3858. chunkLengths = [],
  3859. totalLength = 0;
  3860. // first point has 0 length
  3861. chunkLengths[ 0 ] = 0;
  3862. if ( !nSubDivisions ) nSubDivisions = 100;
  3863. nSamples = this.points.length * nSubDivisions;
  3864. oldPosition.copy( this.points[ 0 ] );
  3865. for ( i = 1; i < nSamples; i ++ ) {
  3866. index = i / nSamples;
  3867. position = this.getPoint( index );
  3868. tmpVec.copy( position );
  3869. totalLength += tmpVec.distanceTo( oldPosition );
  3870. oldPosition.copy( position );
  3871. point = ( this.points.length - 1 ) * index;
  3872. intPoint = Math.floor( point );
  3873. if ( intPoint != oldIntPoint ) {
  3874. chunkLengths[ intPoint ] = totalLength;
  3875. oldIntPoint = intPoint;
  3876. }
  3877. }
  3878. // last point ends with total length
  3879. chunkLengths[ chunkLengths.length ] = totalLength;
  3880. return { chunks: chunkLengths, total: totalLength };
  3881. };
  3882. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3883. var i, j,
  3884. index, indexCurrent, indexNext,
  3885. linearDistance, realDistance,
  3886. sampling, position,
  3887. newpoints = [],
  3888. tmpVec = new THREE.Vector3(),
  3889. sl = this.getLength();
  3890. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3891. for ( i = 1; i < this.points.length; i++ ) {
  3892. //tmpVec.copy( this.points[ i - 1 ] );
  3893. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3894. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3895. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3896. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3897. indexNext = i / ( this.points.length - 1 );
  3898. for ( j = 1; j < sampling - 1; j++ ) {
  3899. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3900. position = this.getPoint( index );
  3901. newpoints.push( tmpVec.copy( position ).clone() );
  3902. }
  3903. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3904. }
  3905. this.points = newpoints;
  3906. };
  3907. // Catmull-Rom
  3908. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3909. var v0 = ( p2 - p0 ) * 0.5,
  3910. v1 = ( p3 - p1 ) * 0.5;
  3911. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3912. };
  3913. };
  3914. /**
  3915. * @author bhouston / http://exocortex.com
  3916. * @author mrdoob / http://mrdoob.com/
  3917. */
  3918. THREE.Triangle = function ( a, b, c ) {
  3919. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3920. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3921. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3922. };
  3923. THREE.Triangle.normal = function() {
  3924. var v0 = new THREE.Vector3();
  3925. return function ( a, b, c, optionalTarget ) {
  3926. var result = optionalTarget || new THREE.Vector3();
  3927. result.subVectors( c, b );
  3928. v0.subVectors( a, b );
  3929. result.cross( v0 );
  3930. var resultLengthSq = result.lengthSq();
  3931. if( resultLengthSq > 0 ) {
  3932. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3933. }
  3934. return result.set( 0, 0, 0 );
  3935. };
  3936. }();
  3937. // static/instance method to calculate barycoordinates
  3938. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3939. THREE.Triangle.barycoordFromPoint = function() {
  3940. var v0 = new THREE.Vector3();
  3941. var v1 = new THREE.Vector3();
  3942. var v2 = new THREE.Vector3();
  3943. return function ( point, a, b, c, optionalTarget ) {
  3944. v0.subVectors( c, a );
  3945. v1.subVectors( b, a );
  3946. v2.subVectors( point, a );
  3947. var dot00 = v0.dot( v0 );
  3948. var dot01 = v0.dot( v1 );
  3949. var dot02 = v0.dot( v2 );
  3950. var dot11 = v1.dot( v1 );
  3951. var dot12 = v1.dot( v2 );
  3952. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3953. var result = optionalTarget || new THREE.Vector3();
  3954. // colinear or singular triangle
  3955. if( denom == 0 ) {
  3956. // arbitrary location outside of triangle?
  3957. // not sure if this is the best idea, maybe should be returning undefined
  3958. return result.set( -2, -1, -1 );
  3959. }
  3960. var invDenom = 1 / denom;
  3961. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3962. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3963. // barycoordinates must always sum to 1
  3964. return result.set( 1 - u - v, v, u );
  3965. };
  3966. }();
  3967. THREE.Triangle.containsPoint = function() {
  3968. var v1 = new THREE.Vector3();
  3969. return function ( point, a, b, c ) {
  3970. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3971. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3972. };
  3973. }();
  3974. THREE.Triangle.prototype = {
  3975. constructor: THREE.Triangle,
  3976. set: function ( a, b, c ) {
  3977. this.a.copy( a );
  3978. this.b.copy( b );
  3979. this.c.copy( c );
  3980. return this;
  3981. },
  3982. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3983. this.a.copy( points[i0] );
  3984. this.b.copy( points[i1] );
  3985. this.c.copy( points[i2] );
  3986. return this;
  3987. },
  3988. copy: function ( triangle ) {
  3989. this.a.copy( triangle.a );
  3990. this.b.copy( triangle.b );
  3991. this.c.copy( triangle.c );
  3992. return this;
  3993. },
  3994. area: function() {
  3995. var v0 = new THREE.Vector3();
  3996. var v1 = new THREE.Vector3();
  3997. return function () {
  3998. v0.subVectors( this.c, this.b );
  3999. v1.subVectors( this.a, this.b );
  4000. return v0.cross( v1 ).length() * 0.5;
  4001. };
  4002. }(),
  4003. midpoint: function ( optionalTarget ) {
  4004. var result = optionalTarget || new THREE.Vector3();
  4005. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  4006. },
  4007. normal: function ( optionalTarget ) {
  4008. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  4009. },
  4010. plane: function ( optionalTarget ) {
  4011. var result = optionalTarget || new THREE.Plane();
  4012. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  4013. },
  4014. barycoordFromPoint: function ( point, optionalTarget ) {
  4015. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  4016. },
  4017. containsPoint: function ( point ) {
  4018. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  4019. },
  4020. equals: function ( triangle ) {
  4021. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  4022. },
  4023. clone: function () {
  4024. return new THREE.Triangle().copy( this );
  4025. }
  4026. };
  4027. /**
  4028. * @author mrdoob / http://mrdoob.com/
  4029. */
  4030. THREE.Vertex = function ( v ) {
  4031. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  4032. return v;
  4033. };
  4034. /**
  4035. * @author mrdoob / http://mrdoob.com/
  4036. */
  4037. THREE.UV = function ( u, v ) {
  4038. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  4039. return new THREE.Vector2( u, v );
  4040. };
  4041. /**
  4042. * @author alteredq / http://alteredqualia.com/
  4043. */
  4044. THREE.Clock = function ( autoStart ) {
  4045. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  4046. this.startTime = 0;
  4047. this.oldTime = 0;
  4048. this.elapsedTime = 0;
  4049. this.running = false;
  4050. };
  4051. THREE.Clock.prototype = {
  4052. constructor: THREE.Clock,
  4053. start: function () {
  4054. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  4055. ? self.performance.now()
  4056. : Date.now();
  4057. this.oldTime = this.startTime;
  4058. this.running = true;
  4059. },
  4060. stop: function () {
  4061. this.getElapsedTime();
  4062. this.running = false;
  4063. },
  4064. getElapsedTime: function () {
  4065. this.getDelta();
  4066. return this.elapsedTime;
  4067. },
  4068. getDelta: function () {
  4069. var diff = 0;
  4070. if ( this.autoStart && ! this.running ) {
  4071. this.start();
  4072. }
  4073. if ( this.running ) {
  4074. var newTime = self.performance !== undefined && self.performance.now !== undefined
  4075. ? self.performance.now()
  4076. : Date.now();
  4077. diff = 0.001 * ( newTime - this.oldTime );
  4078. this.oldTime = newTime;
  4079. this.elapsedTime += diff;
  4080. }
  4081. return diff;
  4082. }
  4083. };
  4084. /**
  4085. * https://github.com/mrdoob/eventdispatcher.js/
  4086. */
  4087. THREE.EventDispatcher = function () {}
  4088. THREE.EventDispatcher.prototype = {
  4089. constructor: THREE.EventDispatcher,
  4090. apply: function ( object ) {
  4091. object.addEventListener = THREE.EventDispatcher.prototype.addEventListener;
  4092. object.hasEventListener = THREE.EventDispatcher.prototype.hasEventListener;
  4093. object.removeEventListener = THREE.EventDispatcher.prototype.removeEventListener;
  4094. object.dispatchEvent = THREE.EventDispatcher.prototype.dispatchEvent;
  4095. },
  4096. addEventListener: function ( type, listener ) {
  4097. if ( this._listeners === undefined ) this._listeners = {};
  4098. var listeners = this._listeners;
  4099. if ( listeners[ type ] === undefined ) {
  4100. listeners[ type ] = [];
  4101. }
  4102. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  4103. listeners[ type ].push( listener );
  4104. }
  4105. },
  4106. hasEventListener: function ( type, listener ) {
  4107. if ( this._listeners === undefined ) return false;
  4108. var listeners = this._listeners;
  4109. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  4110. return true;
  4111. }
  4112. return false;
  4113. },
  4114. removeEventListener: function ( type, listener ) {
  4115. if ( this._listeners === undefined ) return;
  4116. var listeners = this._listeners;
  4117. var listenerArray = listeners[ type ];
  4118. if ( listenerArray !== undefined ) {
  4119. var index = listenerArray.indexOf( listener );
  4120. if ( index !== - 1 ) {
  4121. listenerArray.splice( index, 1 );
  4122. }
  4123. }
  4124. },
  4125. dispatchEvent: function ( event ) {
  4126. if ( this._listeners === undefined ) return;
  4127. var listeners = this._listeners;
  4128. var listenerArray = listeners[ event.type ];
  4129. if ( listenerArray !== undefined ) {
  4130. event.target = this;
  4131. var array = [];
  4132. var length = listenerArray.length;
  4133. for ( var i = 0; i < length; i ++ ) {
  4134. array[ i ] = listenerArray[ i ];
  4135. }
  4136. for ( var i = 0; i < length; i ++ ) {
  4137. array[ i ].call( this, event );
  4138. }
  4139. }
  4140. }
  4141. };
  4142. /**
  4143. * @author mrdoob / http://mrdoob.com/
  4144. * @author bhouston / http://exocortex.com/
  4145. * @author stephomi / http://stephaneginier.com/
  4146. */
  4147. ( function ( THREE ) {
  4148. THREE.Raycaster = function ( origin, direction, near, far ) {
  4149. this.ray = new THREE.Ray( origin, direction );
  4150. // direction is assumed to be normalized (for accurate distance calculations)
  4151. this.near = near || 0;
  4152. this.far = far || Infinity;
  4153. };
  4154. var sphere = new THREE.Sphere();
  4155. var localRay = new THREE.Ray();
  4156. var facePlane = new THREE.Plane();
  4157. var intersectPoint = new THREE.Vector3();
  4158. var matrixPosition = new THREE.Vector3();
  4159. var inverseMatrix = new THREE.Matrix4();
  4160. var descSort = function ( a, b ) {
  4161. return a.distance - b.distance;
  4162. };
  4163. var vA = new THREE.Vector3();
  4164. var vB = new THREE.Vector3();
  4165. var vC = new THREE.Vector3();
  4166. var intersectObject = function ( object, raycaster, intersects ) {
  4167. if ( object instanceof THREE.Sprite ) {
  4168. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4169. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  4170. if ( distance > object.scale.x ) {
  4171. return intersects;
  4172. }
  4173. intersects.push( {
  4174. distance: distance,
  4175. point: object.position,
  4176. face: null,
  4177. object: object
  4178. } );
  4179. } else if ( object instanceof THREE.LOD ) {
  4180. matrixPosition.setFromMatrixPosition( object.matrixWorld );
  4181. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  4182. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  4183. } else if ( object instanceof THREE.Mesh ) {
  4184. var geometry = object.geometry;
  4185. // Checking boundingSphere distance to ray
  4186. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4187. sphere.copy( geometry.boundingSphere );
  4188. sphere.applyMatrix4( object.matrixWorld );
  4189. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4190. return intersects;
  4191. }
  4192. // Check boundingBox before continuing
  4193. inverseMatrix.getInverse( object.matrixWorld );
  4194. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4195. if ( geometry.boundingBox !== null ) {
  4196. if ( localRay.isIntersectionBox( geometry.boundingBox ) === false ) {
  4197. return intersects;
  4198. }
  4199. }
  4200. if ( geometry instanceof THREE.BufferGeometry ) {
  4201. var material = object.material;
  4202. if ( material === undefined ) return intersects;
  4203. var attributes = geometry.attributes;
  4204. var a, b, c;
  4205. var precision = raycaster.precision;
  4206. if ( attributes.index !== undefined ) {
  4207. var indices = attributes.index.array;
  4208. var positions = attributes.position.array;
  4209. var offsets = geometry.offsets;
  4210. if ( offsets.length === 0 ) {
  4211. offsets = [ { start: 0, count: positions.length, index: 0 } ];
  4212. }
  4213. for ( var oi = 0, ol = offsets.length; oi < ol; ++oi ) {
  4214. var start = offsets[ oi ].start;
  4215. var count = offsets[ oi ].count;
  4216. var index = offsets[ oi ].index;
  4217. for ( var i = start, il = start + count; i < il; i += 3 ) {
  4218. a = index + indices[ i ];
  4219. b = index + indices[ i + 1 ];
  4220. c = index + indices[ i + 2 ];
  4221. vA.set(
  4222. positions[ a * 3 ],
  4223. positions[ a * 3 + 1 ],
  4224. positions[ a * 3 + 2 ]
  4225. );
  4226. vB.set(
  4227. positions[ b * 3 ],
  4228. positions[ b * 3 + 1 ],
  4229. positions[ b * 3 + 2 ]
  4230. );
  4231. vC.set(
  4232. positions[ c * 3 ],
  4233. positions[ c * 3 + 1 ],
  4234. positions[ c * 3 + 2 ]
  4235. );
  4236. if ( material.side === THREE.BackSide ) {
  4237. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4238. } else {
  4239. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4240. }
  4241. if ( intersectionPoint === null ) continue;
  4242. intersectionPoint.applyMatrix4( object.matrixWorld );
  4243. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4244. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4245. intersects.push( {
  4246. distance: distance,
  4247. point: intersectionPoint,
  4248. indices: [a, b, c],
  4249. face: null,
  4250. faceIndex: null,
  4251. object: object
  4252. } );
  4253. }
  4254. }
  4255. } else {
  4256. var offsets = geometry.offsets;
  4257. var positions = attributes.position.array;
  4258. for ( var i = 0, il = attributes.position.array.length; i < il; i += 3 ) {
  4259. a = i;
  4260. b = i + 1;
  4261. c = i + 2;
  4262. vA.set(
  4263. positions[ a * 3 ],
  4264. positions[ a * 3 + 1 ],
  4265. positions[ a * 3 + 2 ]
  4266. );
  4267. vB.set(
  4268. positions[ b * 3 ],
  4269. positions[ b * 3 + 1 ],
  4270. positions[ b * 3 + 2 ]
  4271. );
  4272. vC.set(
  4273. positions[ c * 3 ],
  4274. positions[ c * 3 + 1 ],
  4275. positions[ c * 3 + 2 ]
  4276. );
  4277. if ( material.side === THREE.BackSide ) {
  4278. var intersectionPoint = localRay.intersectTriangle( vC, vB, vA, true );
  4279. } else {
  4280. var intersectionPoint = localRay.intersectTriangle( vA, vB, vC, material.side !== THREE.DoubleSide );
  4281. }
  4282. if ( intersectionPoint === null ) continue;
  4283. intersectionPoint.applyMatrix4( object.matrixWorld );
  4284. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4285. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4286. intersects.push( {
  4287. distance: distance,
  4288. point: intersectionPoint,
  4289. indices: [a, b, c],
  4290. face: null,
  4291. faceIndex: null,
  4292. object: object
  4293. } );
  4294. }
  4295. }
  4296. } else if ( geometry instanceof THREE.Geometry ) {
  4297. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4298. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  4299. var a, b, c, d;
  4300. var precision = raycaster.precision;
  4301. var vertices = geometry.vertices;
  4302. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  4303. var face = geometry.faces[ f ];
  4304. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  4305. if ( material === undefined ) continue;
  4306. a = vertices[ face.a ];
  4307. b = vertices[ face.b ];
  4308. c = vertices[ face.c ];
  4309. if ( material.morphTargets === true ) {
  4310. var morphTargets = geometry.morphTargets;
  4311. var morphInfluences = object.morphTargetInfluences;
  4312. vA.set( 0, 0, 0 );
  4313. vB.set( 0, 0, 0 );
  4314. vC.set( 0, 0, 0 );
  4315. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  4316. var influence = morphInfluences[ t ];
  4317. if ( influence === 0 ) continue;
  4318. var targets = morphTargets[ t ].vertices;
  4319. vA.x += ( targets[ face.a ].x - a.x ) * influence;
  4320. vA.y += ( targets[ face.a ].y - a.y ) * influence;
  4321. vA.z += ( targets[ face.a ].z - a.z ) * influence;
  4322. vB.x += ( targets[ face.b ].x - b.x ) * influence;
  4323. vB.y += ( targets[ face.b ].y - b.y ) * influence;
  4324. vB.z += ( targets[ face.b ].z - b.z ) * influence;
  4325. vC.x += ( targets[ face.c ].x - c.x ) * influence;
  4326. vC.y += ( targets[ face.c ].y - c.y ) * influence;
  4327. vC.z += ( targets[ face.c ].z - c.z ) * influence;
  4328. }
  4329. vA.add( a );
  4330. vB.add( b );
  4331. vC.add( c );
  4332. a = vA;
  4333. b = vB;
  4334. c = vC;
  4335. }
  4336. if ( material.side === THREE.BackSide ) {
  4337. var intersectionPoint = localRay.intersectTriangle( c, b, a, true );
  4338. } else {
  4339. var intersectionPoint = localRay.intersectTriangle( a, b, c, material.side !== THREE.DoubleSide );
  4340. }
  4341. if ( intersectionPoint === null ) continue;
  4342. intersectionPoint.applyMatrix4( object.matrixWorld );
  4343. var distance = raycaster.ray.origin.distanceTo( intersectionPoint );
  4344. if ( distance < precision || distance < raycaster.near || distance > raycaster.far ) continue;
  4345. intersects.push( {
  4346. distance: distance,
  4347. point: intersectionPoint,
  4348. face: face,
  4349. faceIndex: f,
  4350. object: object
  4351. } );
  4352. }
  4353. }
  4354. } else if ( object instanceof THREE.Line ) {
  4355. var precision = raycaster.linePrecision;
  4356. var precisionSq = precision * precision;
  4357. var geometry = object.geometry;
  4358. if ( geometry.boundingSphere === null ) geometry.computeBoundingSphere();
  4359. // Checking boundingSphere distance to ray
  4360. sphere.copy( geometry.boundingSphere );
  4361. sphere.applyMatrix4( object.matrixWorld );
  4362. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  4363. return intersects;
  4364. }
  4365. inverseMatrix.getInverse( object.matrixWorld );
  4366. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  4367. /* if ( geometry instanceof THREE.BufferGeometry ) {
  4368. } else */ if ( geometry instanceof THREE.Geometry ) {
  4369. var vertices = geometry.vertices;
  4370. var nbVertices = vertices.length;
  4371. var interSegment = new THREE.Vector3();
  4372. var interRay = new THREE.Vector3();
  4373. var step = object.type === THREE.LineStrip ? 1 : 2;
  4374. for ( var i = 0; i < nbVertices - 1; i = i + step ) {
  4375. var distSq = localRay.distanceSqToSegment( vertices[ i ], vertices[ i + 1 ], interRay, interSegment );
  4376. if ( distSq > precisionSq ) continue;
  4377. var distance = localRay.origin.distanceTo( interRay );
  4378. if ( distance < raycaster.near || distance > raycaster.far ) continue;
  4379. intersects.push( {
  4380. distance: distance,
  4381. // What do we want? intersection point on the ray or on the segment??
  4382. // point: raycaster.ray.at( distance ),
  4383. point: interSegment.clone().applyMatrix4( object.matrixWorld ),
  4384. face: null,
  4385. faceIndex: null,
  4386. object: object
  4387. } );
  4388. }
  4389. }
  4390. }
  4391. };
  4392. var intersectDescendants = function ( object, raycaster, intersects ) {
  4393. var descendants = object.getDescendants();
  4394. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  4395. intersectObject( descendants[ i ], raycaster, intersects );
  4396. }
  4397. };
  4398. //
  4399. THREE.Raycaster.prototype.precision = 0.0001;
  4400. THREE.Raycaster.prototype.linePrecision = 1;
  4401. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  4402. this.ray.set( origin, direction );
  4403. // direction is assumed to be normalized (for accurate distance calculations)
  4404. };
  4405. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  4406. var intersects = [];
  4407. if ( recursive === true ) {
  4408. intersectDescendants( object, this, intersects );
  4409. }
  4410. intersectObject( object, this, intersects );
  4411. intersects.sort( descSort );
  4412. return intersects;
  4413. };
  4414. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  4415. var intersects = [];
  4416. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  4417. intersectObject( objects[ i ], this, intersects );
  4418. if ( recursive === true ) {
  4419. intersectDescendants( objects[ i ], this, intersects );
  4420. }
  4421. }
  4422. intersects.sort( descSort );
  4423. return intersects;
  4424. };
  4425. }( THREE ) );
  4426. /**
  4427. * @author mrdoob / http://mrdoob.com/
  4428. * @author mikael emtinger / http://gomo.se/
  4429. * @author alteredq / http://alteredqualia.com/
  4430. * @author WestLangley / http://github.com/WestLangley
  4431. */
  4432. THREE.Object3D = function () {
  4433. this.id = THREE.Object3DIdCount ++;
  4434. this.uuid = THREE.Math.generateUUID();
  4435. this.name = '';
  4436. this.parent = undefined;
  4437. this.children = [];
  4438. this.up = new THREE.Vector3( 0, 1, 0 );
  4439. this.position = new THREE.Vector3();
  4440. this._rotation = new THREE.Euler();
  4441. this._quaternion = new THREE.Quaternion();
  4442. this.scale = new THREE.Vector3( 1, 1, 1 );
  4443. // keep rotation and quaternion in sync
  4444. this._rotation._quaternion = this.quaternion;
  4445. this._quaternion._euler = this.rotation;
  4446. this.renderDepth = null;
  4447. this.rotationAutoUpdate = true;
  4448. this.matrix = new THREE.Matrix4();
  4449. this.matrixWorld = new THREE.Matrix4();
  4450. this.matrixAutoUpdate = true;
  4451. this.matrixWorldNeedsUpdate = false;
  4452. this.visible = true;
  4453. this.castShadow = false;
  4454. this.receiveShadow = false;
  4455. this.frustumCulled = true;
  4456. this.userData = {};
  4457. };
  4458. THREE.Object3D.prototype = {
  4459. constructor: THREE.Object3D,
  4460. get rotation () {
  4461. return this._rotation;
  4462. },
  4463. set rotation ( value ) {
  4464. this._rotation = value;
  4465. this._rotation._quaternion = this._quaternion;
  4466. this._quaternion._euler = this._rotation;
  4467. this._rotation._updateQuaternion();
  4468. },
  4469. get quaternion () {
  4470. return this._quaternion;
  4471. },
  4472. set quaternion ( value ) {
  4473. this._quaternion = value;
  4474. this._quaternion._euler = this._rotation;
  4475. this._rotation._quaternion = this._quaternion;
  4476. this._quaternion._updateEuler();
  4477. },
  4478. get eulerOrder () {
  4479. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4480. return this.rotation.order;
  4481. },
  4482. set eulerOrder ( value ) {
  4483. console.warn( 'DEPRECATED: Object3D\'s .eulerOrder has been moved to Object3D\'s .rotation.order.' );
  4484. this.rotation.order = value;
  4485. },
  4486. get useQuaternion () {
  4487. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4488. },
  4489. set useQuaternion ( value ) {
  4490. console.warn( 'DEPRECATED: Object3D\'s .useQuaternion has been removed. The library now uses quaternions by default.' );
  4491. },
  4492. applyMatrix: function ( matrix ) {
  4493. this.matrix.multiplyMatrices( matrix, this.matrix );
  4494. this.matrix.decompose( this.position, this.quaternion, this.scale );
  4495. },
  4496. setRotationFromAxisAngle: function ( axis, angle ) {
  4497. // assumes axis is normalized
  4498. this.quaternion.setFromAxisAngle( axis, angle );
  4499. },
  4500. setRotationFromEuler: function ( euler ) {
  4501. this.quaternion.setFromEuler( euler, true );
  4502. },
  4503. setRotationFromMatrix: function ( m ) {
  4504. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  4505. this.quaternion.setFromRotationMatrix( m );
  4506. },
  4507. setRotationFromQuaternion: function ( q ) {
  4508. // assumes q is normalized
  4509. this.quaternion.copy( q );
  4510. },
  4511. rotateOnAxis: function() {
  4512. // rotate object on axis in object space
  4513. // axis is assumed to be normalized
  4514. var q1 = new THREE.Quaternion();
  4515. return function ( axis, angle ) {
  4516. q1.setFromAxisAngle( axis, angle );
  4517. this.quaternion.multiply( q1 );
  4518. return this;
  4519. }
  4520. }(),
  4521. rotateX: function () {
  4522. var v1 = new THREE.Vector3( 1, 0, 0 );
  4523. return function ( angle ) {
  4524. return this.rotateOnAxis( v1, angle );
  4525. };
  4526. }(),
  4527. rotateY: function () {
  4528. var v1 = new THREE.Vector3( 0, 1, 0 );
  4529. return function ( angle ) {
  4530. return this.rotateOnAxis( v1, angle );
  4531. };
  4532. }(),
  4533. rotateZ: function () {
  4534. var v1 = new THREE.Vector3( 0, 0, 1 );
  4535. return function ( angle ) {
  4536. return this.rotateOnAxis( v1, angle );
  4537. };
  4538. }(),
  4539. translateOnAxis: function () {
  4540. // translate object by distance along axis in object space
  4541. // axis is assumed to be normalized
  4542. var v1 = new THREE.Vector3();
  4543. return function ( axis, distance ) {
  4544. v1.copy( axis );
  4545. v1.applyQuaternion( this.quaternion );
  4546. this.position.add( v1.multiplyScalar( distance ) );
  4547. return this;
  4548. }
  4549. }(),
  4550. translate: function ( distance, axis ) {
  4551. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4552. return this.translateOnAxis( axis, distance );
  4553. },
  4554. translateX: function () {
  4555. var v1 = new THREE.Vector3( 1, 0, 0 );
  4556. return function ( distance ) {
  4557. return this.translateOnAxis( v1, distance );
  4558. };
  4559. }(),
  4560. translateY: function () {
  4561. var v1 = new THREE.Vector3( 0, 1, 0 );
  4562. return function ( distance ) {
  4563. return this.translateOnAxis( v1, distance );
  4564. };
  4565. }(),
  4566. translateZ: function () {
  4567. var v1 = new THREE.Vector3( 0, 0, 1 );
  4568. return function ( distance ) {
  4569. return this.translateOnAxis( v1, distance );
  4570. };
  4571. }(),
  4572. localToWorld: function ( vector ) {
  4573. return vector.applyMatrix4( this.matrixWorld );
  4574. },
  4575. worldToLocal: function () {
  4576. var m1 = new THREE.Matrix4();
  4577. return function ( vector ) {
  4578. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4579. };
  4580. }(),
  4581. lookAt: function () {
  4582. // This routine does not support objects with rotated and/or translated parent(s)
  4583. var m1 = new THREE.Matrix4();
  4584. return function ( vector ) {
  4585. m1.lookAt( vector, this.position, this.up );
  4586. this.quaternion.setFromRotationMatrix( m1 );
  4587. };
  4588. }(),
  4589. add: function ( object ) {
  4590. if ( object === this ) {
  4591. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4592. return;
  4593. }
  4594. if ( object instanceof THREE.Object3D ) {
  4595. if ( object.parent !== undefined ) {
  4596. object.parent.remove( object );
  4597. }
  4598. object.parent = this;
  4599. object.dispatchEvent( { type: 'added' } );
  4600. this.children.push( object );
  4601. // add to scene
  4602. var scene = this;
  4603. while ( scene.parent !== undefined ) {
  4604. scene = scene.parent;
  4605. }
  4606. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4607. scene.__addObject( object );
  4608. }
  4609. }
  4610. },
  4611. remove: function ( object ) {
  4612. var index = this.children.indexOf( object );
  4613. if ( index !== - 1 ) {
  4614. object.parent = undefined;
  4615. object.dispatchEvent( { type: 'removed' } );
  4616. this.children.splice( index, 1 );
  4617. // remove from scene
  4618. var scene = this;
  4619. while ( scene.parent !== undefined ) {
  4620. scene = scene.parent;
  4621. }
  4622. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4623. scene.__removeObject( object );
  4624. }
  4625. }
  4626. },
  4627. traverse: function ( callback ) {
  4628. callback( this );
  4629. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4630. this.children[ i ].traverse( callback );
  4631. }
  4632. },
  4633. getObjectById: function ( id, recursive ) {
  4634. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4635. var child = this.children[ i ];
  4636. if ( child.id === id ) {
  4637. return child;
  4638. }
  4639. if ( recursive === true ) {
  4640. child = child.getObjectById( id, recursive );
  4641. if ( child !== undefined ) {
  4642. return child;
  4643. }
  4644. }
  4645. }
  4646. return undefined;
  4647. },
  4648. getObjectByName: function ( name, recursive ) {
  4649. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4650. var child = this.children[ i ];
  4651. if ( child.name === name ) {
  4652. return child;
  4653. }
  4654. if ( recursive === true ) {
  4655. child = child.getObjectByName( name, recursive );
  4656. if ( child !== undefined ) {
  4657. return child;
  4658. }
  4659. }
  4660. }
  4661. return undefined;
  4662. },
  4663. getChildByName: function ( name, recursive ) {
  4664. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4665. return this.getObjectByName( name, recursive );
  4666. },
  4667. getDescendants: function ( array ) {
  4668. if ( array === undefined ) array = [];
  4669. Array.prototype.push.apply( array, this.children );
  4670. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4671. this.children[ i ].getDescendants( array );
  4672. }
  4673. return array;
  4674. },
  4675. updateMatrix: function () {
  4676. this.matrix.compose( this.position, this.quaternion, this.scale );
  4677. this.matrixWorldNeedsUpdate = true;
  4678. },
  4679. updateMatrixWorld: function ( force ) {
  4680. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4681. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4682. if ( this.parent === undefined ) {
  4683. this.matrixWorld.copy( this.matrix );
  4684. } else {
  4685. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4686. }
  4687. this.matrixWorldNeedsUpdate = false;
  4688. force = true;
  4689. }
  4690. // update children
  4691. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4692. this.children[ i ].updateMatrixWorld( force );
  4693. }
  4694. },
  4695. clone: function ( object, recursive ) {
  4696. if ( object === undefined ) object = new THREE.Object3D();
  4697. if ( recursive === undefined ) recursive = true;
  4698. object.name = this.name;
  4699. object.up.copy( this.up );
  4700. object.position.copy( this.position );
  4701. object.quaternion.copy( this.quaternion );
  4702. object.scale.copy( this.scale );
  4703. object.renderDepth = this.renderDepth;
  4704. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4705. object.matrix.copy( this.matrix );
  4706. object.matrixWorld.copy( this.matrixWorld );
  4707. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4708. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4709. object.visible = this.visible;
  4710. object.castShadow = this.castShadow;
  4711. object.receiveShadow = this.receiveShadow;
  4712. object.frustumCulled = this.frustumCulled;
  4713. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4714. if ( recursive === true ) {
  4715. for ( var i = 0; i < this.children.length; i ++ ) {
  4716. var child = this.children[ i ];
  4717. object.add( child.clone() );
  4718. }
  4719. }
  4720. return object;
  4721. }
  4722. };
  4723. THREE.EventDispatcher.prototype.apply( THREE.Object3D.prototype );
  4724. THREE.Object3DIdCount = 0;
  4725. /**
  4726. * @author mrdoob / http://mrdoob.com/
  4727. * @author supereggbert / http://www.paulbrunt.co.uk/
  4728. * @author julianwa / https://github.com/julianwa
  4729. */
  4730. THREE.Projector = function () {
  4731. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4732. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4733. _face, _faceCount, _facePool = [], _facePoolLength = 0,
  4734. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4735. _sprite, _spriteCount, _spritePool = [], _spritePoolLength = 0,
  4736. _renderData = { objects: [], lights: [], elements: [] },
  4737. _vA = new THREE.Vector3(),
  4738. _vB = new THREE.Vector3(),
  4739. _vC = new THREE.Vector3(),
  4740. _vector3 = new THREE.Vector3(),
  4741. _vector4 = new THREE.Vector4(),
  4742. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4743. _boundingBox = new THREE.Box3(),
  4744. _points3 = new Array( 3 ),
  4745. _points4 = new Array( 4 ),
  4746. _viewMatrix = new THREE.Matrix4(),
  4747. _viewProjectionMatrix = new THREE.Matrix4(),
  4748. _modelMatrix,
  4749. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4750. _normalMatrix = new THREE.Matrix3(),
  4751. _frustum = new THREE.Frustum(),
  4752. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4753. _clippedVertex2PositionScreen = new THREE.Vector4();
  4754. this.projectVector = function ( vector, camera ) {
  4755. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4756. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4757. return vector.applyProjection( _viewProjectionMatrix );
  4758. };
  4759. this.unprojectVector = function () {
  4760. var projectionMatrixInverse = new THREE.Matrix4();
  4761. return function ( vector, camera ) {
  4762. projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4763. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, projectionMatrixInverse );
  4764. return vector.applyProjection( _viewProjectionMatrix );
  4765. };
  4766. }();
  4767. this.pickingRay = function ( vector, camera ) {
  4768. // set two vectors with opposing z values
  4769. vector.z = -1.0;
  4770. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4771. this.unprojectVector( vector, camera );
  4772. this.unprojectVector( end, camera );
  4773. // find direction from vector to end
  4774. end.sub( vector ).normalize();
  4775. return new THREE.Raycaster( vector, end );
  4776. };
  4777. var projectObject = function ( object ) {
  4778. if ( object.visible === false ) return;
  4779. if ( object instanceof THREE.Light ) {
  4780. _renderData.lights.push( object );
  4781. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line || object instanceof THREE.Sprite ) {
  4782. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4783. _object = getNextObjectInPool();
  4784. _object.id = object.id;
  4785. _object.object = object;
  4786. if ( object.renderDepth !== null ) {
  4787. _object.z = object.renderDepth;
  4788. } else {
  4789. _vector3.setFromMatrixPosition( object.matrixWorld );
  4790. _vector3.applyProjection( _viewProjectionMatrix );
  4791. _object.z = _vector3.z;
  4792. }
  4793. _renderData.objects.push( _object );
  4794. }
  4795. }
  4796. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4797. projectObject( object.children[ i ] );
  4798. }
  4799. };
  4800. var projectGraph = function ( root, sortObjects ) {
  4801. _objectCount = 0;
  4802. _renderData.objects.length = 0;
  4803. _renderData.lights.length = 0;
  4804. projectObject( root );
  4805. if ( sortObjects === true ) {
  4806. _renderData.objects.sort( painterSort );
  4807. }
  4808. };
  4809. var RenderList = function () {
  4810. var normals = [];
  4811. var uvs = [];
  4812. var object = null;
  4813. var material = null;
  4814. var normalMatrix = new THREE.Matrix3();
  4815. var setObject = function ( value ) {
  4816. object = value;
  4817. material = object.material;
  4818. normalMatrix.getNormalMatrix( object.matrixWorld );
  4819. normals.length = 0;
  4820. uvs.length = 0;
  4821. };
  4822. var projectVertex = function ( vertex ) {
  4823. var position = vertex.position;
  4824. var positionWorld = vertex.positionWorld;
  4825. var positionScreen = vertex.positionScreen;
  4826. positionWorld.copy( position ).applyMatrix4( _modelMatrix );
  4827. positionScreen.copy( positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4828. var invW = 1 / positionScreen.w;
  4829. positionScreen.x *= invW;
  4830. positionScreen.y *= invW;
  4831. positionScreen.z *= invW;
  4832. vertex.visible = positionScreen.x >= -1 && positionScreen.x <= 1 &&
  4833. positionScreen.y >= -1 && positionScreen.y <= 1 &&
  4834. positionScreen.z >= -1 && positionScreen.z <= 1;
  4835. };
  4836. var pushVertex = function ( x, y, z ) {
  4837. _vertex = getNextVertexInPool();
  4838. _vertex.position.set( x, y, z );
  4839. projectVertex( _vertex );
  4840. };
  4841. var pushNormal = function ( x, y, z ) {
  4842. normals.push( x, y, z );
  4843. };
  4844. var pushUv = function ( x, y ) {
  4845. uvs.push( x, y );
  4846. };
  4847. var checkTriangleVisibility = function ( v1, v2, v3 ) {
  4848. if ( v1.visible === true || v2.visible === true || v3.visible === true ) return true;
  4849. _points3[ 0 ] = v1.positionScreen;
  4850. _points3[ 1 ] = v2.positionScreen;
  4851. _points3[ 2 ] = v3.positionScreen;
  4852. return _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) );
  4853. };
  4854. var checkBackfaceCulling = function ( v1, v2, v3 ) {
  4855. return ( ( v3.positionScreen.x - v1.positionScreen.x ) *
  4856. ( v2.positionScreen.y - v1.positionScreen.y ) -
  4857. ( v3.positionScreen.y - v1.positionScreen.y ) *
  4858. ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4859. };
  4860. var pushLine = function ( a, b ) {
  4861. var v1 = _vertexPool[ a ];
  4862. var v2 = _vertexPool[ b ];
  4863. _line = getNextLineInPool();
  4864. _line.id = object.id;
  4865. _line.v1.copy( v1 );
  4866. _line.v2.copy( v2 );
  4867. _line.z = ( v1.positionScreen.z + v2.positionScreen.z ) / 2;
  4868. _line.material = object.material;
  4869. _renderData.elements.push( _line );
  4870. };
  4871. var pushTriangle = function ( a, b, c ) {
  4872. var v1 = _vertexPool[ a ];
  4873. var v2 = _vertexPool[ b ];
  4874. var v3 = _vertexPool[ c ];
  4875. if ( checkTriangleVisibility( v1, v2, v3 ) === false ) return;
  4876. if ( material.side === THREE.DoubleSide || checkBackfaceCulling( v1, v2, v3 ) === true ) {
  4877. _face = getNextFaceInPool();
  4878. _face.id = object.id;
  4879. _face.v1.copy( v1 );
  4880. _face.v2.copy( v2 );
  4881. _face.v3.copy( v3 );
  4882. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  4883. for ( var i = 0; i < 3; i ++ ) {
  4884. var offset = arguments[ i ] * 3;
  4885. var normal = _face.vertexNormalsModel[ i ];
  4886. normal.set( normals[ offset ], normals[ offset + 1 ], normals[ offset + 2 ] );
  4887. normal.applyMatrix3( normalMatrix ).normalize();
  4888. var offset2 = arguments[ i ] * 2;
  4889. var uv = _face.uvs[ i ];
  4890. uv.set( uvs[ offset2 ], uvs[ offset2 + 1 ] );
  4891. }
  4892. _face.vertexNormalsLength = 3;
  4893. _face.material = object.material;
  4894. _renderData.elements.push( _face );
  4895. }
  4896. };
  4897. return {
  4898. setObject: setObject,
  4899. projectVertex: projectVertex,
  4900. checkTriangleVisibility: checkTriangleVisibility,
  4901. checkBackfaceCulling: checkBackfaceCulling,
  4902. pushVertex: pushVertex,
  4903. pushNormal: pushNormal,
  4904. pushUv: pushUv,
  4905. pushLine: pushLine,
  4906. pushTriangle: pushTriangle
  4907. }
  4908. };
  4909. var renderList = new RenderList();
  4910. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4911. var object, geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs,
  4912. isFaceMaterial, objectMaterials;
  4913. _faceCount = 0;
  4914. _lineCount = 0;
  4915. _spriteCount = 0;
  4916. _renderData.elements.length = 0;
  4917. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4918. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4919. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4920. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4921. _frustum.setFromMatrix( _viewProjectionMatrix );
  4922. projectGraph( scene, sortObjects );
  4923. for ( var o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4924. object = _renderData.objects[ o ].object;
  4925. geometry = object.geometry;
  4926. renderList.setObject( object );
  4927. _modelMatrix = object.matrixWorld;
  4928. _vertexCount = 0;
  4929. if ( object instanceof THREE.Mesh ) {
  4930. if ( geometry instanceof THREE.BufferGeometry ) {
  4931. var attributes = geometry.attributes;
  4932. var offsets = geometry.offsets;
  4933. if ( attributes.position === undefined ) continue;
  4934. var positions = attributes.position.array;
  4935. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  4936. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  4937. }
  4938. if ( attributes.normal !== undefined ) {
  4939. var normals = attributes.normal.array;
  4940. for ( var i = 0, l = normals.length; i < l; i += 3 ) {
  4941. renderList.pushNormal( normals[ i ], normals[ i + 1 ], normals[ i + 2 ] );
  4942. }
  4943. }
  4944. if ( attributes.uv !== undefined ) {
  4945. var uvs = attributes.uv.array;
  4946. for ( var i = 0, l = uvs.length; i < l; i += 2 ) {
  4947. renderList.pushUv( uvs[ i ], uvs[ i + 1 ] );
  4948. }
  4949. }
  4950. if ( attributes.index !== undefined ) {
  4951. var indices = attributes.index.array;
  4952. if ( offsets.length > 0 ) {
  4953. for ( var o = 0; o < offsets.length; o ++ ) {
  4954. var offset = offsets[ o ];
  4955. var index = offset.index;
  4956. for ( var i = offset.start, l = offset.start + offset.count; i < l; i += 3 ) {
  4957. renderList.pushTriangle( indices[ i ] + index, indices[ i + 1 ] + index, indices[ i + 2 ] + index );
  4958. }
  4959. }
  4960. } else {
  4961. for ( var i = 0, l = indices.length; i < l; i += 3 ) {
  4962. renderList.pushTriangle( indices[ i ], indices[ i + 1 ], indices[ i + 2 ] );
  4963. }
  4964. }
  4965. } else {
  4966. for ( var i = 0, l = positions.length / 3; i < l; i += 3 ) {
  4967. renderList.pushTriangle( i, i + 1, i + 2 );
  4968. }
  4969. }
  4970. } else if ( geometry instanceof THREE.Geometry ) {
  4971. vertices = geometry.vertices;
  4972. faces = geometry.faces;
  4973. faceVertexUvs = geometry.faceVertexUvs[ 0 ];
  4974. _normalMatrix.getNormalMatrix( _modelMatrix );
  4975. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4976. objectMaterials = isFaceMaterial === true ? object.material : null;
  4977. for ( var v = 0, vl = vertices.length; v < vl; v ++ ) {
  4978. var vertex = vertices[ v ];
  4979. renderList.pushVertex( vertex.x, vertex.y, vertex.z );
  4980. }
  4981. for ( var f = 0, fl = faces.length; f < fl; f ++ ) {
  4982. face = faces[ f ];
  4983. var material = isFaceMaterial === true
  4984. ? objectMaterials.materials[ face.materialIndex ]
  4985. : object.material;
  4986. if ( material === undefined ) continue;
  4987. var side = material.side;
  4988. var v1 = _vertexPool[ face.a ];
  4989. var v2 = _vertexPool[ face.b ];
  4990. var v3 = _vertexPool[ face.c ];
  4991. if ( material.morphTargets === true ) {
  4992. var morphTargets = geometry.morphTargets;
  4993. var morphInfluences = object.morphTargetInfluences;
  4994. var v1p = v1.position;
  4995. var v2p = v2.position;
  4996. var v3p = v3.position;
  4997. _vA.set( 0, 0, 0 );
  4998. _vB.set( 0, 0, 0 );
  4999. _vC.set( 0, 0, 0 );
  5000. for ( var t = 0, tl = morphTargets.length; t < tl; t ++ ) {
  5001. var influence = morphInfluences[ t ];
  5002. if ( influence === 0 ) continue;
  5003. var targets = morphTargets[ t ].vertices;
  5004. _vA.x += ( targets[ face.a ].x - v1p.x ) * influence;
  5005. _vA.y += ( targets[ face.a ].y - v1p.y ) * influence;
  5006. _vA.z += ( targets[ face.a ].z - v1p.z ) * influence;
  5007. _vB.x += ( targets[ face.b ].x - v2p.x ) * influence;
  5008. _vB.y += ( targets[ face.b ].y - v2p.y ) * influence;
  5009. _vB.z += ( targets[ face.b ].z - v2p.z ) * influence;
  5010. _vC.x += ( targets[ face.c ].x - v3p.x ) * influence;
  5011. _vC.y += ( targets[ face.c ].y - v3p.y ) * influence;
  5012. _vC.z += ( targets[ face.c ].z - v3p.z ) * influence;
  5013. }
  5014. v1.position.add( _vA );
  5015. v2.position.add( _vB );
  5016. v3.position.add( _vC );
  5017. renderList.projectVertex( v1 );
  5018. renderList.projectVertex( v2 );
  5019. renderList.projectVertex( v3 );
  5020. }
  5021. if ( renderList.checkTriangleVisibility( v1, v2, v3 ) === false ) continue;
  5022. var visible = renderList.checkBackfaceCulling( v1, v2, v3 );
  5023. if ( side !== THREE.DoubleSide ) {
  5024. if ( side === THREE.FrontSide && visible === false ) continue;
  5025. if ( side === THREE.BackSide && visible === true ) continue;
  5026. }
  5027. _face = getNextFaceInPool();
  5028. _face.id = object.id;
  5029. _face.v1.copy( v1 );
  5030. _face.v2.copy( v2 );
  5031. _face.v3.copy( v3 );
  5032. _face.normalModel.copy( face.normal );
  5033. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5034. _face.normalModel.negate();
  5035. }
  5036. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  5037. faceVertexNormals = face.vertexNormals;
  5038. for ( var n = 0, nl = Math.min( faceVertexNormals.length, 3 ); n < nl; n ++ ) {
  5039. var normalModel = _face.vertexNormalsModel[ n ];
  5040. normalModel.copy( faceVertexNormals[ n ] );
  5041. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  5042. normalModel.negate();
  5043. }
  5044. normalModel.applyMatrix3( _normalMatrix ).normalize();
  5045. }
  5046. _face.vertexNormalsLength = faceVertexNormals.length;
  5047. var vertexUvs = faceVertexUvs[ f ];
  5048. if ( vertexUvs !== undefined ) {
  5049. for ( var u = 0; u < 3; u ++ ) {
  5050. _face.uvs[ u ].copy( vertexUvs[ u ] );
  5051. }
  5052. }
  5053. _face.color = face.color;
  5054. _face.material = material;
  5055. _face.z = ( v1.positionScreen.z + v2.positionScreen.z + v3.positionScreen.z ) / 3;
  5056. _renderData.elements.push( _face );
  5057. }
  5058. }
  5059. } else if ( object instanceof THREE.Line ) {
  5060. if ( geometry instanceof THREE.BufferGeometry ) {
  5061. var attributes = geometry.attributes;
  5062. if ( attributes.position !== undefined ) {
  5063. var positions = attributes.position.array;
  5064. for ( var i = 0, l = positions.length; i < l; i += 3 ) {
  5065. renderList.pushVertex( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5066. }
  5067. if ( attributes.index !== undefined ) {
  5068. var indices = attributes.index.array;
  5069. for ( var i = 0, l = indices.length; i < l; i += 2 ) {
  5070. renderList.pushLine( indices[ i ], indices[ i + 1 ] );
  5071. }
  5072. } else {
  5073. for ( var i = 0, l = ( positions.length / 3 ) - 1; i < l; i ++ ) {
  5074. renderList.pushLine( i, i + 1 );
  5075. }
  5076. }
  5077. }
  5078. } else if ( geometry instanceof THREE.Geometry ) {
  5079. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  5080. vertices = object.geometry.vertices;
  5081. if ( vertices.length === 0 ) continue;
  5082. v1 = getNextVertexInPool();
  5083. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  5084. // Handle LineStrip and LinePieces
  5085. var step = object.type === THREE.LinePieces ? 2 : 1;
  5086. for ( var v = 1, vl = vertices.length; v < vl; v ++ ) {
  5087. v1 = getNextVertexInPool();
  5088. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  5089. if ( ( v + 1 ) % step > 0 ) continue;
  5090. v2 = _vertexPool[ _vertexCount - 2 ];
  5091. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  5092. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  5093. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  5094. // Perform the perspective divide
  5095. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  5096. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  5097. _line = getNextLineInPool();
  5098. _line.id = object.id;
  5099. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  5100. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  5101. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  5102. _line.material = object.material;
  5103. if ( object.material.vertexColors === THREE.VertexColors ) {
  5104. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  5105. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  5106. }
  5107. _renderData.elements.push( _line );
  5108. }
  5109. }
  5110. }
  5111. } else if ( object instanceof THREE.Sprite ) {
  5112. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  5113. _vector4.applyMatrix4( _viewProjectionMatrix );
  5114. var invW = 1 / _vector4.w;
  5115. _vector4.z *= invW;
  5116. if ( _vector4.z >= -1 && _vector4.z <= 1 ) {
  5117. _sprite = getNextSpriteInPool();
  5118. _sprite.id = object.id;
  5119. _sprite.x = _vector4.x * invW;
  5120. _sprite.y = _vector4.y * invW;
  5121. _sprite.z = _vector4.z;
  5122. _sprite.object = object;
  5123. _sprite.rotation = object.rotation;
  5124. _sprite.scale.x = object.scale.x * Math.abs( _sprite.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  5125. _sprite.scale.y = object.scale.y * Math.abs( _sprite.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  5126. _sprite.material = object.material;
  5127. _renderData.elements.push( _sprite );
  5128. }
  5129. }
  5130. }
  5131. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  5132. return _renderData;
  5133. };
  5134. // Pools
  5135. function getNextObjectInPool() {
  5136. if ( _objectCount === _objectPoolLength ) {
  5137. var object = new THREE.RenderableObject();
  5138. _objectPool.push( object );
  5139. _objectPoolLength ++;
  5140. _objectCount ++;
  5141. return object;
  5142. }
  5143. return _objectPool[ _objectCount ++ ];
  5144. }
  5145. function getNextVertexInPool() {
  5146. if ( _vertexCount === _vertexPoolLength ) {
  5147. var vertex = new THREE.RenderableVertex();
  5148. _vertexPool.push( vertex );
  5149. _vertexPoolLength ++;
  5150. _vertexCount ++;
  5151. return vertex;
  5152. }
  5153. return _vertexPool[ _vertexCount ++ ];
  5154. }
  5155. function getNextFaceInPool() {
  5156. if ( _faceCount === _facePoolLength ) {
  5157. var face = new THREE.RenderableFace();
  5158. _facePool.push( face );
  5159. _facePoolLength ++;
  5160. _faceCount ++;
  5161. return face;
  5162. }
  5163. return _facePool[ _faceCount ++ ];
  5164. }
  5165. function getNextLineInPool() {
  5166. if ( _lineCount === _linePoolLength ) {
  5167. var line = new THREE.RenderableLine();
  5168. _linePool.push( line );
  5169. _linePoolLength ++;
  5170. _lineCount ++
  5171. return line;
  5172. }
  5173. return _linePool[ _lineCount ++ ];
  5174. }
  5175. function getNextSpriteInPool() {
  5176. if ( _spriteCount === _spritePoolLength ) {
  5177. var sprite = new THREE.RenderableSprite();
  5178. _spritePool.push( sprite );
  5179. _spritePoolLength ++;
  5180. _spriteCount ++
  5181. return sprite;
  5182. }
  5183. return _spritePool[ _spriteCount ++ ];
  5184. }
  5185. //
  5186. function painterSort( a, b ) {
  5187. if ( a.z !== b.z ) {
  5188. return b.z - a.z;
  5189. } else if ( a.id !== b.id ) {
  5190. return a.id - b.id;
  5191. } else {
  5192. return 0;
  5193. }
  5194. }
  5195. function clipLine( s1, s2 ) {
  5196. var alpha1 = 0, alpha2 = 1,
  5197. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  5198. // Z = -1 and Z = +1, respectively.
  5199. bc1near = s1.z + s1.w,
  5200. bc2near = s2.z + s2.w,
  5201. bc1far = - s1.z + s1.w,
  5202. bc2far = - s2.z + s2.w;
  5203. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  5204. // Both vertices lie entirely within all clip planes.
  5205. return true;
  5206. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  5207. // Both vertices lie entirely outside one of the clip planes.
  5208. return false;
  5209. } else {
  5210. // The line segment spans at least one clip plane.
  5211. if ( bc1near < 0 ) {
  5212. // v1 lies outside the near plane, v2 inside
  5213. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  5214. } else if ( bc2near < 0 ) {
  5215. // v2 lies outside the near plane, v1 inside
  5216. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  5217. }
  5218. if ( bc1far < 0 ) {
  5219. // v1 lies outside the far plane, v2 inside
  5220. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  5221. } else if ( bc2far < 0 ) {
  5222. // v2 lies outside the far plane, v2 inside
  5223. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  5224. }
  5225. if ( alpha2 < alpha1 ) {
  5226. // The line segment spans two boundaries, but is outside both of them.
  5227. // (This can't happen when we're only clipping against just near/far but good
  5228. // to leave the check here for future usage if other clip planes are added.)
  5229. return false;
  5230. } else {
  5231. // Update the s1 and s2 vertices to match the clipped line segment.
  5232. s1.lerp( s2, alpha1 );
  5233. s2.lerp( s1, 1 - alpha2 );
  5234. return true;
  5235. }
  5236. }
  5237. }
  5238. };
  5239. /**
  5240. * @author mrdoob / http://mrdoob.com/
  5241. * @author alteredq / http://alteredqualia.com/
  5242. */
  5243. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  5244. this.a = a;
  5245. this.b = b;
  5246. this.c = c;
  5247. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  5248. this.vertexNormals = normal instanceof Array ? normal : [ ];
  5249. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  5250. this.vertexColors = color instanceof Array ? color : [];
  5251. this.vertexTangents = [];
  5252. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  5253. };
  5254. THREE.Face3.prototype = {
  5255. constructor: THREE.Face3,
  5256. clone: function () {
  5257. var face = new THREE.Face3( this.a, this.b, this.c );
  5258. face.normal.copy( this.normal );
  5259. face.color.copy( this.color );
  5260. face.materialIndex = this.materialIndex;
  5261. var i, il;
  5262. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  5263. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  5264. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  5265. return face;
  5266. }
  5267. };
  5268. /**
  5269. * @author mrdoob / http://mrdoob.com/
  5270. */
  5271. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  5272. console.warn( 'THREE.Face4 has been removed. A THREE.Face3 will be created instead.')
  5273. return new THREE.Face3( a, b, c, normal, color, materialIndex );
  5274. };
  5275. /**
  5276. * @author mrdoob / http://mrdoob.com/
  5277. */
  5278. THREE.BufferAttribute = function () {};
  5279. THREE.BufferAttribute.prototype = {
  5280. constructor: THREE.BufferAttribute,
  5281. get length () {
  5282. return this.array.length;
  5283. },
  5284. set: function ( value ) {
  5285. this.array.set( value );
  5286. },
  5287. setX: function ( index, x ) {
  5288. this.array[ index * this.itemSize ] = x;
  5289. },
  5290. setY: function ( index, y ) {
  5291. this.array[ index * this.itemSize + 1 ] = y;
  5292. },
  5293. setZ: function ( index, z ) {
  5294. this.array[ index * this.itemSize + 2 ] = z;
  5295. },
  5296. setXY: function ( index, x, y ) {
  5297. index *= this.itemSize;
  5298. this.array[ index ] = x;
  5299. this.array[ index + 1 ] = y;
  5300. },
  5301. setXYZ: function ( index, x, y, z ) {
  5302. index *= this.itemSize;
  5303. this.array[ index ] = x;
  5304. this.array[ index + 1 ] = y;
  5305. this.array[ index + 2 ] = z;
  5306. },
  5307. setXYZW: function ( index, x, y, z, w ) {
  5308. index *= this.itemSize;
  5309. this.array[ index ] = x;
  5310. this.array[ index + 1 ] = y;
  5311. this.array[ index + 2 ] = z;
  5312. this.array[ index + 3 ] = w;
  5313. }
  5314. };
  5315. //
  5316. THREE.Int8Attribute = function ( size, itemSize ) {
  5317. this.array = new Int8Array( size * itemSize );
  5318. this.itemSize = itemSize;
  5319. };
  5320. THREE.Int8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5321. THREE.Uint8Attribute = function ( size, itemSize ) {
  5322. this.array = new Uint8Array( size * itemSize );
  5323. this.itemSize = itemSize;
  5324. };
  5325. THREE.Uint8Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5326. THREE.Uint8ClampedAttribute = function ( size, itemSize ) {
  5327. this.array = new Uint8ClampedArray( size * itemSize );
  5328. this.itemSize = itemSize;
  5329. };
  5330. THREE.Uint8ClampedAttribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5331. THREE.Int16Attribute = function ( size, itemSize ) {
  5332. this.array = new Int16Array( size * itemSize );
  5333. this.itemSize = itemSize;
  5334. };
  5335. THREE.Int16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5336. THREE.Uint16Attribute = function ( size, itemSize ) {
  5337. this.array = new Uint16Array( size * itemSize );
  5338. this.itemSize = itemSize;
  5339. };
  5340. THREE.Uint16Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5341. THREE.Int32Attribute = function ( size, itemSize ) {
  5342. this.array = new Int32Array( size * itemSize );
  5343. this.itemSize = itemSize;
  5344. };
  5345. THREE.Int32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5346. THREE.Uint32Attribute = function ( size, itemSize ) {
  5347. this.array = new Uint32Array( size * itemSize );
  5348. this.itemSize = itemSize;
  5349. };
  5350. THREE.Uint32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5351. THREE.Float32Attribute = function ( size, itemSize ) {
  5352. this.array = new Float32Array( size * itemSize );
  5353. this.itemSize = itemSize;
  5354. };
  5355. THREE.Float32Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5356. THREE.Float64Attribute = function ( size, itemSize ) {
  5357. this.array = new Float64Array( size * itemSize );
  5358. this.itemSize = itemSize;
  5359. };
  5360. THREE.Float64Attribute.prototype = Object.create( THREE.BufferAttribute.prototype );
  5361. /**
  5362. * @author alteredq / http://alteredqualia.com/
  5363. */
  5364. THREE.BufferGeometry = function () {
  5365. this.id = THREE.GeometryIdCount ++;
  5366. this.uuid = THREE.Math.generateUUID();
  5367. this.name = '';
  5368. this.attributes = {};
  5369. this.drawcalls = [];
  5370. this.offsets = this.drawcalls; // backwards compatibility
  5371. this.boundingBox = null;
  5372. this.boundingSphere = null;
  5373. };
  5374. THREE.BufferGeometry.prototype = {
  5375. constructor: THREE.BufferGeometry,
  5376. addAttribute: function ( name, attribute ) {
  5377. if ( attribute instanceof THREE.BufferAttribute === false ) {
  5378. console.warn( 'DEPRECATED: BufferGeometry\'s addAttribute() now expects ( name, attribute ).' );
  5379. this.attributes[ name ] = { array: arguments[ 1 ], itemSize: arguments[ 2 ] };
  5380. return;
  5381. }
  5382. this.attributes[ name ] = attribute;
  5383. },
  5384. getAttribute: function ( name ) {
  5385. return this.attributes[ name ];
  5386. },
  5387. addDrawCall: function ( start, count, indexOffset ) {
  5388. this.drawcalls.push( {
  5389. start: start,
  5390. count: count,
  5391. index: indexOffset !== undefined ? indexOffset : 0
  5392. } );
  5393. },
  5394. applyMatrix: function ( matrix ) {
  5395. var position = this.attributes.position;
  5396. if ( position !== undefined ) {
  5397. matrix.applyToVector3Array( position.array );
  5398. position.needsUpdate = true;
  5399. }
  5400. var normal = this.attributes.normal;
  5401. if ( normal !== undefined ) {
  5402. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5403. normalMatrix.applyToVector3Array( normal.array );
  5404. normal.needsUpdate = true;
  5405. }
  5406. },
  5407. computeBoundingBox: function () {
  5408. if ( this.boundingBox === null ) {
  5409. this.boundingBox = new THREE.Box3();
  5410. }
  5411. var positions = this.attributes[ "position" ].array;
  5412. if ( positions ) {
  5413. var bb = this.boundingBox;
  5414. if( positions.length >= 3 ) {
  5415. bb.min.x = bb.max.x = positions[ 0 ];
  5416. bb.min.y = bb.max.y = positions[ 1 ];
  5417. bb.min.z = bb.max.z = positions[ 2 ];
  5418. }
  5419. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5420. var x = positions[ i ];
  5421. var y = positions[ i + 1 ];
  5422. var z = positions[ i + 2 ];
  5423. // bounding box
  5424. if ( x < bb.min.x ) {
  5425. bb.min.x = x;
  5426. } else if ( x > bb.max.x ) {
  5427. bb.max.x = x;
  5428. }
  5429. if ( y < bb.min.y ) {
  5430. bb.min.y = y;
  5431. } else if ( y > bb.max.y ) {
  5432. bb.max.y = y;
  5433. }
  5434. if ( z < bb.min.z ) {
  5435. bb.min.z = z;
  5436. } else if ( z > bb.max.z ) {
  5437. bb.max.z = z;
  5438. }
  5439. }
  5440. }
  5441. if ( positions === undefined || positions.length === 0 ) {
  5442. this.boundingBox.min.set( 0, 0, 0 );
  5443. this.boundingBox.max.set( 0, 0, 0 );
  5444. }
  5445. },
  5446. computeBoundingSphere: function () {
  5447. var box = new THREE.Box3();
  5448. var vector = new THREE.Vector3();
  5449. return function () {
  5450. if ( this.boundingSphere === null ) {
  5451. this.boundingSphere = new THREE.Sphere();
  5452. }
  5453. var positions = this.attributes[ "position" ].array;
  5454. if ( positions ) {
  5455. box.makeEmpty();
  5456. var center = this.boundingSphere.center;
  5457. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5458. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5459. box.addPoint( vector );
  5460. }
  5461. box.center( center );
  5462. var maxRadiusSq = 0;
  5463. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5464. vector.set( positions[ i ], positions[ i + 1 ], positions[ i + 2 ] );
  5465. maxRadiusSq = Math.max( maxRadiusSq, center.distanceToSquared( vector ) );
  5466. }
  5467. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5468. }
  5469. }
  5470. }(),
  5471. computeFaceNormals: function () {
  5472. // backwards compatibility
  5473. },
  5474. computeVertexNormals: function () {
  5475. if ( this.attributes[ "position" ] ) {
  5476. var i, il;
  5477. var j, jl;
  5478. var nVertexElements = this.attributes[ "position" ].array.length;
  5479. if ( this.attributes[ "normal" ] === undefined ) {
  5480. this.attributes[ "normal" ] = {
  5481. itemSize: 3,
  5482. array: new Float32Array( nVertexElements )
  5483. };
  5484. } else {
  5485. // reset existing normals to zero
  5486. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5487. this.attributes[ "normal" ].array[ i ] = 0;
  5488. }
  5489. }
  5490. var positions = this.attributes[ "position" ].array;
  5491. var normals = this.attributes[ "normal" ].array;
  5492. var vA, vB, vC, x, y, z,
  5493. pA = new THREE.Vector3(),
  5494. pB = new THREE.Vector3(),
  5495. pC = new THREE.Vector3(),
  5496. cb = new THREE.Vector3(),
  5497. ab = new THREE.Vector3();
  5498. // indexed elements
  5499. if ( this.attributes[ "index" ] ) {
  5500. var indices = this.attributes[ "index" ].array;
  5501. var offsets = this.offsets;
  5502. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5503. var start = offsets[ j ].start;
  5504. var count = offsets[ j ].count;
  5505. var index = offsets[ j ].index;
  5506. for ( i = start, il = start + count; i < il; i += 3 ) {
  5507. vA = index + indices[ i ];
  5508. vB = index + indices[ i + 1 ];
  5509. vC = index + indices[ i + 2 ];
  5510. x = positions[ vA * 3 ];
  5511. y = positions[ vA * 3 + 1 ];
  5512. z = positions[ vA * 3 + 2 ];
  5513. pA.set( x, y, z );
  5514. x = positions[ vB * 3 ];
  5515. y = positions[ vB * 3 + 1 ];
  5516. z = positions[ vB * 3 + 2 ];
  5517. pB.set( x, y, z );
  5518. x = positions[ vC * 3 ];
  5519. y = positions[ vC * 3 + 1 ];
  5520. z = positions[ vC * 3 + 2 ];
  5521. pC.set( x, y, z );
  5522. cb.subVectors( pC, pB );
  5523. ab.subVectors( pA, pB );
  5524. cb.cross( ab );
  5525. normals[ vA * 3 ] += cb.x;
  5526. normals[ vA * 3 + 1 ] += cb.y;
  5527. normals[ vA * 3 + 2 ] += cb.z;
  5528. normals[ vB * 3 ] += cb.x;
  5529. normals[ vB * 3 + 1 ] += cb.y;
  5530. normals[ vB * 3 + 2 ] += cb.z;
  5531. normals[ vC * 3 ] += cb.x;
  5532. normals[ vC * 3 + 1 ] += cb.y;
  5533. normals[ vC * 3 + 2 ] += cb.z;
  5534. }
  5535. }
  5536. // non-indexed elements (unconnected triangle soup)
  5537. } else {
  5538. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5539. x = positions[ i ];
  5540. y = positions[ i + 1 ];
  5541. z = positions[ i + 2 ];
  5542. pA.set( x, y, z );
  5543. x = positions[ i + 3 ];
  5544. y = positions[ i + 4 ];
  5545. z = positions[ i + 5 ];
  5546. pB.set( x, y, z );
  5547. x = positions[ i + 6 ];
  5548. y = positions[ i + 7 ];
  5549. z = positions[ i + 8 ];
  5550. pC.set( x, y, z );
  5551. cb.subVectors( pC, pB );
  5552. ab.subVectors( pA, pB );
  5553. cb.cross( ab );
  5554. normals[ i ] = cb.x;
  5555. normals[ i + 1 ] = cb.y;
  5556. normals[ i + 2 ] = cb.z;
  5557. normals[ i + 3 ] = cb.x;
  5558. normals[ i + 4 ] = cb.y;
  5559. normals[ i + 5 ] = cb.z;
  5560. normals[ i + 6 ] = cb.x;
  5561. normals[ i + 7 ] = cb.y;
  5562. normals[ i + 8 ] = cb.z;
  5563. }
  5564. }
  5565. this.normalizeNormals();
  5566. this.normalsNeedUpdate = true;
  5567. }
  5568. },
  5569. normalizeNormals: function () {
  5570. var normals = this.attributes[ "normal" ].array;
  5571. var x, y, z, n;
  5572. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5573. x = normals[ i ];
  5574. y = normals[ i + 1 ];
  5575. z = normals[ i + 2 ];
  5576. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5577. normals[ i ] *= n;
  5578. normals[ i + 1 ] *= n;
  5579. normals[ i + 2 ] *= n;
  5580. }
  5581. },
  5582. computeTangents: function () {
  5583. // based on http://www.terathon.com/code/tangent.html
  5584. // (per vertex tangents)
  5585. if ( this.attributes[ "index" ] === undefined ||
  5586. this.attributes[ "position" ] === undefined ||
  5587. this.attributes[ "normal" ] === undefined ||
  5588. this.attributes[ "uv" ] === undefined ) {
  5589. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5590. return;
  5591. }
  5592. var indices = this.attributes[ "index" ].array;
  5593. var positions = this.attributes[ "position" ].array;
  5594. var normals = this.attributes[ "normal" ].array;
  5595. var uvs = this.attributes[ "uv" ].array;
  5596. var nVertices = positions.length / 3;
  5597. if ( this.attributes[ "tangent" ] === undefined ) {
  5598. var nTangentElements = 4 * nVertices;
  5599. this.attributes[ "tangent" ] = {
  5600. itemSize: 4,
  5601. array: new Float32Array( nTangentElements )
  5602. };
  5603. }
  5604. var tangents = this.attributes[ "tangent" ].array;
  5605. var tan1 = [], tan2 = [];
  5606. for ( var k = 0; k < nVertices; k ++ ) {
  5607. tan1[ k ] = new THREE.Vector3();
  5608. tan2[ k ] = new THREE.Vector3();
  5609. }
  5610. var xA, yA, zA,
  5611. xB, yB, zB,
  5612. xC, yC, zC,
  5613. uA, vA,
  5614. uB, vB,
  5615. uC, vC,
  5616. x1, x2, y1, y2, z1, z2,
  5617. s1, s2, t1, t2, r;
  5618. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5619. function handleTriangle( a, b, c ) {
  5620. xA = positions[ a * 3 ];
  5621. yA = positions[ a * 3 + 1 ];
  5622. zA = positions[ a * 3 + 2 ];
  5623. xB = positions[ b * 3 ];
  5624. yB = positions[ b * 3 + 1 ];
  5625. zB = positions[ b * 3 + 2 ];
  5626. xC = positions[ c * 3 ];
  5627. yC = positions[ c * 3 + 1 ];
  5628. zC = positions[ c * 3 + 2 ];
  5629. uA = uvs[ a * 2 ];
  5630. vA = uvs[ a * 2 + 1 ];
  5631. uB = uvs[ b * 2 ];
  5632. vB = uvs[ b * 2 + 1 ];
  5633. uC = uvs[ c * 2 ];
  5634. vC = uvs[ c * 2 + 1 ];
  5635. x1 = xB - xA;
  5636. x2 = xC - xA;
  5637. y1 = yB - yA;
  5638. y2 = yC - yA;
  5639. z1 = zB - zA;
  5640. z2 = zC - zA;
  5641. s1 = uB - uA;
  5642. s2 = uC - uA;
  5643. t1 = vB - vA;
  5644. t2 = vC - vA;
  5645. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5646. sdir.set(
  5647. ( t2 * x1 - t1 * x2 ) * r,
  5648. ( t2 * y1 - t1 * y2 ) * r,
  5649. ( t2 * z1 - t1 * z2 ) * r
  5650. );
  5651. tdir.set(
  5652. ( s1 * x2 - s2 * x1 ) * r,
  5653. ( s1 * y2 - s2 * y1 ) * r,
  5654. ( s1 * z2 - s2 * z1 ) * r
  5655. );
  5656. tan1[ a ].add( sdir );
  5657. tan1[ b ].add( sdir );
  5658. tan1[ c ].add( sdir );
  5659. tan2[ a ].add( tdir );
  5660. tan2[ b ].add( tdir );
  5661. tan2[ c ].add( tdir );
  5662. }
  5663. var i, il;
  5664. var j, jl;
  5665. var iA, iB, iC;
  5666. var offsets = this.offsets;
  5667. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5668. var start = offsets[ j ].start;
  5669. var count = offsets[ j ].count;
  5670. var index = offsets[ j ].index;
  5671. for ( i = start, il = start + count; i < il; i += 3 ) {
  5672. iA = index + indices[ i ];
  5673. iB = index + indices[ i + 1 ];
  5674. iC = index + indices[ i + 2 ];
  5675. handleTriangle( iA, iB, iC );
  5676. }
  5677. }
  5678. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5679. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5680. var w, t, test;
  5681. function handleVertex( v ) {
  5682. n.x = normals[ v * 3 ];
  5683. n.y = normals[ v * 3 + 1 ];
  5684. n.z = normals[ v * 3 + 2 ];
  5685. n2.copy( n );
  5686. t = tan1[ v ];
  5687. // Gram-Schmidt orthogonalize
  5688. tmp.copy( t );
  5689. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5690. // Calculate handedness
  5691. tmp2.crossVectors( n2, t );
  5692. test = tmp2.dot( tan2[ v ] );
  5693. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5694. tangents[ v * 4 ] = tmp.x;
  5695. tangents[ v * 4 + 1 ] = tmp.y;
  5696. tangents[ v * 4 + 2 ] = tmp.z;
  5697. tangents[ v * 4 + 3 ] = w;
  5698. }
  5699. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5700. var start = offsets[ j ].start;
  5701. var count = offsets[ j ].count;
  5702. var index = offsets[ j ].index;
  5703. for ( i = start, il = start + count; i < il; i += 3 ) {
  5704. iA = index + indices[ i ];
  5705. iB = index + indices[ i + 1 ];
  5706. iC = index + indices[ i + 2 ];
  5707. handleVertex( iA );
  5708. handleVertex( iB );
  5709. handleVertex( iC );
  5710. }
  5711. }
  5712. },
  5713. /*
  5714. computeOffsets
  5715. Compute the draw offset for large models by chunking the index buffer into chunks of 65k addressable vertices.
  5716. This method will effectively rewrite the index buffer and remap all attributes to match the new indices.
  5717. WARNING: This method will also expand the vertex count to prevent sprawled triangles across draw offsets.
  5718. indexBufferSize - Defaults to 65535, but allows for larger or smaller chunks.
  5719. */
  5720. computeOffsets: function(indexBufferSize) {
  5721. var size = indexBufferSize;
  5722. if(indexBufferSize === undefined)
  5723. size = 65535; //WebGL limits type of index buffer values to 16-bit.
  5724. var s = Date.now();
  5725. var indices = this.attributes['index'].array;
  5726. var vertices = this.attributes['position'].array;
  5727. var verticesCount = (vertices.length/3);
  5728. var facesCount = (indices.length/3);
  5729. /*
  5730. console.log("Computing buffers in offsets of "+size+" -> indices:"+indices.length+" vertices:"+vertices.length);
  5731. console.log("Faces to process: "+(indices.length/3));
  5732. console.log("Reordering "+verticesCount+" vertices.");
  5733. */
  5734. var sortedIndices = new Uint16Array( indices.length ); //16-bit buffers
  5735. var indexPtr = 0;
  5736. var vertexPtr = 0;
  5737. var offsets = [ { start:0, count:0, index:0 } ];
  5738. var offset = offsets[0];
  5739. var duplicatedVertices = 0;
  5740. var newVerticeMaps = 0;
  5741. var faceVertices = new Int32Array(6);
  5742. var vertexMap = new Int32Array( vertices.length );
  5743. var revVertexMap = new Int32Array( vertices.length );
  5744. for(var j = 0; j < vertices.length; j++) { vertexMap[j] = -1; revVertexMap[j] = -1; }
  5745. /*
  5746. Traverse every face and reorder vertices in the proper offsets of 65k.
  5747. We can have more than 65k entries in the index buffer per offset, but only reference 65k values.
  5748. */
  5749. for(var findex = 0; findex < facesCount; findex++) {
  5750. newVerticeMaps = 0;
  5751. for(var vo = 0; vo < 3; vo++) {
  5752. var vid = indices[ findex*3 + vo ];
  5753. if(vertexMap[vid] == -1) {
  5754. //Unmapped vertice
  5755. faceVertices[vo*2] = vid;
  5756. faceVertices[vo*2+1] = -1;
  5757. newVerticeMaps++;
  5758. } else if(vertexMap[vid] < offset.index) {
  5759. //Reused vertices from previous block (duplicate)
  5760. faceVertices[vo*2] = vid;
  5761. faceVertices[vo*2+1] = -1;
  5762. duplicatedVertices++;
  5763. } else {
  5764. //Reused vertice in the current block
  5765. faceVertices[vo*2] = vid;
  5766. faceVertices[vo*2+1] = vertexMap[vid];
  5767. }
  5768. }
  5769. var faceMax = vertexPtr + newVerticeMaps;
  5770. if(faceMax > (offset.index + size)) {
  5771. var new_offset = { start:indexPtr, count:0, index:vertexPtr };
  5772. offsets.push(new_offset);
  5773. offset = new_offset;
  5774. //Re-evaluate reused vertices in light of new offset.
  5775. for(var v = 0; v < 6; v+=2) {
  5776. var new_vid = faceVertices[v+1];
  5777. if(new_vid > -1 && new_vid < offset.index)
  5778. faceVertices[v+1] = -1;
  5779. }
  5780. }
  5781. //Reindex the face.
  5782. for(var v = 0; v < 6; v+=2) {
  5783. var vid = faceVertices[v];
  5784. var new_vid = faceVertices[v+1];
  5785. if(new_vid === -1)
  5786. new_vid = vertexPtr++;
  5787. vertexMap[vid] = new_vid;
  5788. revVertexMap[new_vid] = vid;
  5789. sortedIndices[indexPtr++] = new_vid - offset.index; //XXX overflows at 16bit
  5790. offset.count++;
  5791. }
  5792. }
  5793. /* Move all attribute values to map to the new computed indices , also expand the vertice stack to match our new vertexPtr. */
  5794. this.reorderBuffers(sortedIndices, revVertexMap, vertexPtr);
  5795. this.offsets = offsets;
  5796. /*
  5797. var orderTime = Date.now();
  5798. console.log("Reorder time: "+(orderTime-s)+"ms");
  5799. console.log("Duplicated "+duplicatedVertices+" vertices.");
  5800. console.log("Compute Buffers time: "+(Date.now()-s)+"ms");
  5801. console.log("Draw offsets: "+offsets.length);
  5802. */
  5803. return offsets;
  5804. },
  5805. /*
  5806. reoderBuffers:
  5807. Reorder attributes based on a new indexBuffer and indexMap.
  5808. indexBuffer - Uint16Array of the new ordered indices.
  5809. indexMap - Int32Array where the position is the new vertex ID and the value the old vertex ID for each vertex.
  5810. vertexCount - Amount of total vertices considered in this reordering (in case you want to grow the vertice stack).
  5811. */
  5812. reorderBuffers: function(indexBuffer, indexMap, vertexCount) {
  5813. /* Create a copy of all attributes for reordering. */
  5814. var sortedAttributes = {};
  5815. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5816. for( var attr in this.attributes ) {
  5817. if(attr == 'index')
  5818. continue;
  5819. var sourceArray = this.attributes[attr].array;
  5820. for ( var i = 0, il = types.length; i < il; i++ ) {
  5821. var type = types[i];
  5822. if (sourceArray instanceof type) {
  5823. sortedAttributes[attr] = new type( this.attributes[attr].itemSize * vertexCount );
  5824. break;
  5825. }
  5826. }
  5827. }
  5828. /* Move attribute positions based on the new index map */
  5829. for(var new_vid = 0; new_vid < vertexCount; new_vid++) {
  5830. var vid = indexMap[new_vid];
  5831. for ( var attr in this.attributes ) {
  5832. if(attr == 'index')
  5833. continue;
  5834. var attrArray = this.attributes[attr].array;
  5835. var attrSize = this.attributes[attr].itemSize;
  5836. var sortedAttr = sortedAttributes[attr];
  5837. for(var k = 0; k < attrSize; k++)
  5838. sortedAttr[ new_vid * attrSize + k ] = attrArray[ vid * attrSize + k ];
  5839. }
  5840. }
  5841. /* Carry the new sorted buffers locally */
  5842. this.attributes['index'].array = indexBuffer;
  5843. for ( var attr in this.attributes ) {
  5844. if(attr == 'index')
  5845. continue;
  5846. this.attributes[attr].array = sortedAttributes[attr];
  5847. this.attributes[attr].numItems = this.attributes[attr].itemSize * vertexCount;
  5848. }
  5849. },
  5850. clone: function () {
  5851. var geometry = new THREE.BufferGeometry();
  5852. var types = [ Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array, Int32Array, Uint32Array, Float32Array, Float64Array ];
  5853. for ( var attr in this.attributes ) {
  5854. var sourceAttr = this.attributes[ attr ];
  5855. var sourceArray = sourceAttr.array;
  5856. var attribute = {
  5857. itemSize: sourceAttr.itemSize,
  5858. array: null
  5859. };
  5860. for ( var i = 0, il = types.length; i < il; i ++ ) {
  5861. var type = types[ i ];
  5862. if ( sourceArray instanceof type ) {
  5863. attribute.array = new type( sourceArray );
  5864. break;
  5865. }
  5866. }
  5867. geometry.attributes[ attr ] = attribute;
  5868. }
  5869. for ( var i = 0, il = this.offsets.length; i < il; i ++ ) {
  5870. var offset = this.offsets[ i ];
  5871. geometry.offsets.push( {
  5872. start: offset.start,
  5873. index: offset.index,
  5874. count: offset.count
  5875. } );
  5876. }
  5877. return geometry;
  5878. },
  5879. dispose: function () {
  5880. this.dispatchEvent( { type: 'dispose' } );
  5881. }
  5882. };
  5883. THREE.EventDispatcher.prototype.apply( THREE.BufferGeometry.prototype );
  5884. /**
  5885. * @author mrdoob / http://mrdoob.com/
  5886. */
  5887. THREE.BufferGeometryManipulator = function ( bufferGeometry ) {
  5888. this.vertices = [];
  5889. this.normals = [];
  5890. this.uvs = [];
  5891. var attributes = bufferGeometry.attributes;
  5892. var length = attributes.position.array.length / 3;
  5893. for ( var i = 0; i < length; i ++ ) {
  5894. this.vertices.push( new THREE.ProxyVector3( attributes.position.array, i * 3 ) );
  5895. this.normals.push( new THREE.ProxyVector3( attributes.normal.array, i * 3 ) );
  5896. this.uvs.push( new THREE.ProxyVector2( attributes.uv.array, i * 2 ) );
  5897. }
  5898. };
  5899. /**
  5900. * @author mrdoob / http://mrdoob.com/
  5901. * @author kile / http://kile.stravaganza.org/
  5902. * @author alteredq / http://alteredqualia.com/
  5903. * @author mikael emtinger / http://gomo.se/
  5904. * @author zz85 / http://www.lab4games.net/zz85/blog
  5905. * @author bhouston / http://exocortex.com
  5906. */
  5907. THREE.Geometry = function () {
  5908. this.id = THREE.GeometryIdCount ++;
  5909. this.uuid = THREE.Math.generateUUID();
  5910. this.name = '';
  5911. this.vertices = [];
  5912. this.colors = []; // one-to-one vertex colors, used in ParticleSystem and Line
  5913. this.faces = [];
  5914. this.faceVertexUvs = [[]];
  5915. this.morphTargets = [];
  5916. this.morphColors = [];
  5917. this.morphNormals = [];
  5918. this.skinWeights = [];
  5919. this.skinIndices = [];
  5920. this.lineDistances = [];
  5921. this.boundingBox = null;
  5922. this.boundingSphere = null;
  5923. this.hasTangents = false;
  5924. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  5925. // update flags
  5926. this.verticesNeedUpdate = false;
  5927. this.elementsNeedUpdate = false;
  5928. this.uvsNeedUpdate = false;
  5929. this.normalsNeedUpdate = false;
  5930. this.tangentsNeedUpdate = false;
  5931. this.colorsNeedUpdate = false;
  5932. this.lineDistancesNeedUpdate = false;
  5933. this.buffersNeedUpdate = false;
  5934. };
  5935. THREE.Geometry.prototype = {
  5936. constructor: THREE.Geometry,
  5937. applyMatrix: function ( matrix ) {
  5938. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5939. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  5940. var vertex = this.vertices[ i ];
  5941. vertex.applyMatrix4( matrix );
  5942. }
  5943. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  5944. var face = this.faces[ i ];
  5945. face.normal.applyMatrix3( normalMatrix ).normalize();
  5946. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  5947. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  5948. }
  5949. }
  5950. if ( this.boundingBox instanceof THREE.Box3 ) {
  5951. this.computeBoundingBox();
  5952. }
  5953. if ( this.boundingSphere instanceof THREE.Sphere ) {
  5954. this.computeBoundingSphere();
  5955. }
  5956. },
  5957. computeFaceNormals: function () {
  5958. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  5959. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5960. var face = this.faces[ f ];
  5961. var vA = this.vertices[ face.a ];
  5962. var vB = this.vertices[ face.b ];
  5963. var vC = this.vertices[ face.c ];
  5964. cb.subVectors( vC, vB );
  5965. ab.subVectors( vA, vB );
  5966. cb.cross( ab );
  5967. cb.normalize();
  5968. face.normal.copy( cb );
  5969. }
  5970. },
  5971. computeVertexNormals: function ( areaWeighted ) {
  5972. var v, vl, f, fl, face, vertices;
  5973. vertices = new Array( this.vertices.length );
  5974. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  5975. vertices[ v ] = new THREE.Vector3();
  5976. }
  5977. if ( areaWeighted ) {
  5978. // vertex normals weighted by triangle areas
  5979. // http://www.iquilezles.org/www/articles/normals/normals.htm
  5980. var vA, vB, vC, vD;
  5981. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  5982. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  5983. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5984. face = this.faces[ f ];
  5985. vA = this.vertices[ face.a ];
  5986. vB = this.vertices[ face.b ];
  5987. vC = this.vertices[ face.c ];
  5988. cb.subVectors( vC, vB );
  5989. ab.subVectors( vA, vB );
  5990. cb.cross( ab );
  5991. vertices[ face.a ].add( cb );
  5992. vertices[ face.b ].add( cb );
  5993. vertices[ face.c ].add( cb );
  5994. }
  5995. } else {
  5996. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  5997. face = this.faces[ f ];
  5998. vertices[ face.a ].add( face.normal );
  5999. vertices[ face.b ].add( face.normal );
  6000. vertices[ face.c ].add( face.normal );
  6001. }
  6002. }
  6003. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6004. vertices[ v ].normalize();
  6005. }
  6006. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6007. face = this.faces[ f ];
  6008. face.vertexNormals[ 0 ] = vertices[ face.a ].clone();
  6009. face.vertexNormals[ 1 ] = vertices[ face.b ].clone();
  6010. face.vertexNormals[ 2 ] = vertices[ face.c ].clone();
  6011. }
  6012. },
  6013. computeMorphNormals: function () {
  6014. var i, il, f, fl, face;
  6015. // save original normals
  6016. // - create temp variables on first access
  6017. // otherwise just copy (for faster repeated calls)
  6018. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6019. face = this.faces[ f ];
  6020. if ( ! face.__originalFaceNormal ) {
  6021. face.__originalFaceNormal = face.normal.clone();
  6022. } else {
  6023. face.__originalFaceNormal.copy( face.normal );
  6024. }
  6025. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  6026. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  6027. if ( ! face.__originalVertexNormals[ i ] ) {
  6028. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  6029. } else {
  6030. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  6031. }
  6032. }
  6033. }
  6034. // use temp geometry to compute face and vertex normals for each morph
  6035. var tmpGeo = new THREE.Geometry();
  6036. tmpGeo.faces = this.faces;
  6037. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  6038. // create on first access
  6039. if ( ! this.morphNormals[ i ] ) {
  6040. this.morphNormals[ i ] = {};
  6041. this.morphNormals[ i ].faceNormals = [];
  6042. this.morphNormals[ i ].vertexNormals = [];
  6043. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  6044. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  6045. var faceNormal, vertexNormals;
  6046. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6047. face = this.faces[ f ];
  6048. faceNormal = new THREE.Vector3();
  6049. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  6050. dstNormalsFace.push( faceNormal );
  6051. dstNormalsVertex.push( vertexNormals );
  6052. }
  6053. }
  6054. var morphNormals = this.morphNormals[ i ];
  6055. // set vertices to morph target
  6056. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  6057. // compute morph normals
  6058. tmpGeo.computeFaceNormals();
  6059. tmpGeo.computeVertexNormals();
  6060. // store morph normals
  6061. var faceNormal, vertexNormals;
  6062. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6063. face = this.faces[ f ];
  6064. faceNormal = morphNormals.faceNormals[ f ];
  6065. vertexNormals = morphNormals.vertexNormals[ f ];
  6066. faceNormal.copy( face.normal );
  6067. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  6068. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  6069. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  6070. }
  6071. }
  6072. // restore original normals
  6073. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6074. face = this.faces[ f ];
  6075. face.normal = face.__originalFaceNormal;
  6076. face.vertexNormals = face.__originalVertexNormals;
  6077. }
  6078. },
  6079. computeTangents: function () {
  6080. // based on http://www.terathon.com/code/tangent.html
  6081. // tangents go to vertices
  6082. var f, fl, v, vl, i, il, vertexIndex,
  6083. face, uv, vA, vB, vC, uvA, uvB, uvC,
  6084. x1, x2, y1, y2, z1, z2,
  6085. s1, s2, t1, t2, r, t, test,
  6086. tan1 = [], tan2 = [],
  6087. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  6088. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  6089. n = new THREE.Vector3(), w;
  6090. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  6091. tan1[ v ] = new THREE.Vector3();
  6092. tan2[ v ] = new THREE.Vector3();
  6093. }
  6094. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  6095. vA = context.vertices[ a ];
  6096. vB = context.vertices[ b ];
  6097. vC = context.vertices[ c ];
  6098. uvA = uv[ ua ];
  6099. uvB = uv[ ub ];
  6100. uvC = uv[ uc ];
  6101. x1 = vB.x - vA.x;
  6102. x2 = vC.x - vA.x;
  6103. y1 = vB.y - vA.y;
  6104. y2 = vC.y - vA.y;
  6105. z1 = vB.z - vA.z;
  6106. z2 = vC.z - vA.z;
  6107. s1 = uvB.x - uvA.x;
  6108. s2 = uvC.x - uvA.x;
  6109. t1 = uvB.y - uvA.y;
  6110. t2 = uvC.y - uvA.y;
  6111. r = 1.0 / ( s1 * t2 - s2 * t1 );
  6112. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  6113. ( t2 * y1 - t1 * y2 ) * r,
  6114. ( t2 * z1 - t1 * z2 ) * r );
  6115. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  6116. ( s1 * y2 - s2 * y1 ) * r,
  6117. ( s1 * z2 - s2 * z1 ) * r );
  6118. tan1[ a ].add( sdir );
  6119. tan1[ b ].add( sdir );
  6120. tan1[ c ].add( sdir );
  6121. tan2[ a ].add( tdir );
  6122. tan2[ b ].add( tdir );
  6123. tan2[ c ].add( tdir );
  6124. }
  6125. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6126. face = this.faces[ f ];
  6127. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  6128. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  6129. }
  6130. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  6131. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6132. face = this.faces[ f ];
  6133. for ( i = 0; i < Math.min( face.vertexNormals.length, 3 ); i++ ) {
  6134. n.copy( face.vertexNormals[ i ] );
  6135. vertexIndex = face[ faceIndex[ i ] ];
  6136. t = tan1[ vertexIndex ];
  6137. // Gram-Schmidt orthogonalize
  6138. tmp.copy( t );
  6139. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  6140. // Calculate handedness
  6141. tmp2.crossVectors( face.vertexNormals[ i ], t );
  6142. test = tmp2.dot( tan2[ vertexIndex ] );
  6143. w = (test < 0.0) ? -1.0 : 1.0;
  6144. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  6145. }
  6146. }
  6147. this.hasTangents = true;
  6148. },
  6149. computeLineDistances: function ( ) {
  6150. var d = 0;
  6151. var vertices = this.vertices;
  6152. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6153. if ( i > 0 ) {
  6154. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  6155. }
  6156. this.lineDistances[ i ] = d;
  6157. }
  6158. },
  6159. computeBoundingBox: function () {
  6160. if ( this.boundingBox === null ) {
  6161. this.boundingBox = new THREE.Box3();
  6162. }
  6163. this.boundingBox.setFromPoints( this.vertices );
  6164. },
  6165. computeBoundingSphere: function () {
  6166. if ( this.boundingSphere === null ) {
  6167. this.boundingSphere = new THREE.Sphere();
  6168. }
  6169. this.boundingSphere.setFromPoints( this.vertices );
  6170. },
  6171. /*
  6172. * Checks for duplicate vertices with hashmap.
  6173. * Duplicated vertices are removed
  6174. * and faces' vertices are updated.
  6175. */
  6176. mergeVertices: function () {
  6177. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  6178. var unique = [], changes = [];
  6179. var v, key;
  6180. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  6181. var precision = Math.pow( 10, precisionPoints );
  6182. var i,il, face;
  6183. var indices, k, j, jl, u;
  6184. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  6185. v = this.vertices[ i ];
  6186. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  6187. if ( verticesMap[ key ] === undefined ) {
  6188. verticesMap[ key ] = i;
  6189. unique.push( this.vertices[ i ] );
  6190. changes[ i ] = unique.length - 1;
  6191. } else {
  6192. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  6193. changes[ i ] = changes[ verticesMap[ key ] ];
  6194. }
  6195. };
  6196. // if faces are completely degenerate after merging vertices, we
  6197. // have to remove them from the geometry.
  6198. var faceIndicesToRemove = [];
  6199. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  6200. face = this.faces[ i ];
  6201. face.a = changes[ face.a ];
  6202. face.b = changes[ face.b ];
  6203. face.c = changes[ face.c ];
  6204. indices = [ face.a, face.b, face.c ];
  6205. var dupIndex = -1;
  6206. // if any duplicate vertices are found in a Face3
  6207. // we have to remove the face as nothing can be saved
  6208. for ( var n = 0; n < 3; n ++ ) {
  6209. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  6210. dupIndex = n;
  6211. faceIndicesToRemove.push( i );
  6212. break;
  6213. }
  6214. }
  6215. }
  6216. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  6217. var idx = faceIndicesToRemove[ i ];
  6218. this.faces.splice( idx, 1 );
  6219. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  6220. this.faceVertexUvs[ j ].splice( idx, 1 );
  6221. }
  6222. }
  6223. // Use unique set of vertices
  6224. var diff = this.vertices.length - unique.length;
  6225. this.vertices = unique;
  6226. return diff;
  6227. },
  6228. // Geometry splitting
  6229. makeGroups: ( function () {
  6230. var geometryGroupCounter = 0;
  6231. return function ( usesFaceMaterial, maxVerticesInGroup ) {
  6232. var f, fl, face, materialIndex,
  6233. groupHash, hash_map = {};
  6234. var numMorphTargets = this.morphTargets.length;
  6235. var numMorphNormals = this.morphNormals.length;
  6236. this.geometryGroups = {};
  6237. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  6238. face = this.faces[ f ];
  6239. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  6240. if ( ! ( materialIndex in hash_map ) ) {
  6241. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  6242. }
  6243. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6244. if ( ! ( groupHash in this.geometryGroups ) ) {
  6245. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6246. }
  6247. if ( this.geometryGroups[ groupHash ].vertices + 3 > maxVerticesInGroup ) {
  6248. hash_map[ materialIndex ].counter += 1;
  6249. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  6250. if ( ! ( groupHash in this.geometryGroups ) ) {
  6251. this.geometryGroups[ groupHash ] = { 'faces3': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  6252. }
  6253. }
  6254. this.geometryGroups[ groupHash ].faces3.push( f );
  6255. this.geometryGroups[ groupHash ].vertices += 3;
  6256. }
  6257. this.geometryGroupsList = [];
  6258. for ( var g in this.geometryGroups ) {
  6259. this.geometryGroups[ g ].id = geometryGroupCounter ++;
  6260. this.geometryGroupsList.push( this.geometryGroups[ g ] );
  6261. }
  6262. };
  6263. } )(),
  6264. clone: function () {
  6265. var geometry = new THREE.Geometry();
  6266. var vertices = this.vertices;
  6267. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  6268. geometry.vertices.push( vertices[ i ].clone() );
  6269. }
  6270. var faces = this.faces;
  6271. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  6272. geometry.faces.push( faces[ i ].clone() );
  6273. }
  6274. var uvs = this.faceVertexUvs[ 0 ];
  6275. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  6276. var uv = uvs[ i ], uvCopy = [];
  6277. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  6278. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  6279. }
  6280. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  6281. }
  6282. return geometry;
  6283. },
  6284. dispose: function () {
  6285. this.dispatchEvent( { type: 'dispose' } );
  6286. }
  6287. };
  6288. THREE.EventDispatcher.prototype.apply( THREE.Geometry.prototype );
  6289. THREE.GeometryIdCount = 0;
  6290. /**
  6291. * @author mrdoob / http://mrdoob.com/
  6292. */
  6293. THREE.Geometry2 = function ( vertices, normals, uvs ) {
  6294. THREE.BufferGeometry.call( this );
  6295. this.attributes[ 'position' ] = { array: vertices, itemSize: 3 };
  6296. this.attributes[ 'normal' ] = { array: normals, itemSize: 3 };
  6297. this.attributes[ 'uv' ] = { array: uvs, itemSize: 2 };
  6298. };
  6299. THREE.Geometry2.prototype = Object.create( THREE.BufferGeometry.prototype );
  6300. THREE.Geometry99 = function ( ) {
  6301. THREE.BufferGeometry.call( this );
  6302. };
  6303. THREE.Geometry99.prototype = Object.create( THREE.BufferGeometry.prototype );
  6304. Object.defineProperties( THREE.Geometry99.prototype, {
  6305. vertices: {
  6306. enumerable: true,
  6307. get: function() { return this.createVertexProxies(); }
  6308. },
  6309. faces: {
  6310. enumerable: true,
  6311. get: function() { return this.createFaceProxies() }
  6312. },
  6313. faceVertexUvs: {
  6314. enumerable: true,
  6315. get: function() { return this.createUvProxies() }
  6316. }
  6317. // TODO - fill in additional proxies:
  6318. // - colors
  6319. // - morphColors
  6320. // - morphNormals
  6321. // - morphTargets
  6322. // - skinIndex
  6323. // - skinWeights
  6324. } );
  6325. THREE.Geometry99.prototype.createVertexProxies = function() {
  6326. // Replace the prototype getter with a local array property
  6327. Object.defineProperty( this, "vertices", { value: [] } );
  6328. // If the attribute buffer has already been populated, set up proxy objects
  6329. this.populateProxyFromBuffer( this.vertices, "position", THREE.ProxyVector3, 3 );
  6330. // Return a reference to the newly-created array
  6331. return this.vertices;
  6332. };
  6333. THREE.Geometry99.prototype.createFaceProxies = function () {
  6334. // Replace the prototype getter with a local array property
  6335. Object.defineProperty( this, "faces", { value: [] } );
  6336. // If the attribute buffer has already been populated, set up proxy objects
  6337. if ( this.attributes.index ) {
  6338. var indexarray = this.attributes[ 'index' ].array;
  6339. var size = 3;
  6340. var attr = this.faces;
  6341. var normalarray = false;
  6342. if (this.attributes[ 'normal' ]) {
  6343. normalarray = this.attributes[ 'normal' ].array;
  6344. }
  6345. for ( var i = 0, l = indexarray.length / size; i < l; i ++ ) {
  6346. var o = i * size;
  6347. // Generate faceVertexNormals
  6348. var vertexNormals;
  6349. if (normalarray) {
  6350. vertexNormals = [
  6351. new THREE.ProxyVector3( normalarray, indexarray[ o ] * 3 ),
  6352. new THREE.ProxyVector3( normalarray, indexarray[ o + 1 ] * 3 ),
  6353. new THREE.ProxyVector3( normalarray, indexarray[ o + 2 ] * 3 )
  6354. ]
  6355. }
  6356. // TODO - do BufferGeometries support face normals?
  6357. var face = new THREE.ProxyFace3( indexarray, i * size, vertexNormals );
  6358. attr.push( face );
  6359. }
  6360. } else {
  6361. // TODO - should be able to generate Face data even for non-indexed geometries
  6362. }
  6363. // Return a reference to the newly-created array
  6364. return this.faces;
  6365. };
  6366. THREE.Geometry99.prototype.createUvProxies = function () {
  6367. // Replace the prototype getter with a local array property
  6368. Object.defineProperty( this, "faceVertexUvs", { value: [[]] } );
  6369. // If the attribute buffer has already been populated, set up proxy objects
  6370. if ( this.attributes.uv ) {
  6371. var faces = this.faces;
  6372. var uvarray = this.attributes.uv.array;
  6373. for (var i = 0, l = faces.length; i < l; i++) {
  6374. var f = faces[i];
  6375. this.faceVertexUvs[0][i] = [];
  6376. this.faceVertexUvs[0][i][0] = new THREE.ProxyVector2(uvarray, f.a * 2);
  6377. this.faceVertexUvs[0][i][1] = new THREE.ProxyVector2(uvarray, f.b * 2);
  6378. this.faceVertexUvs[0][i][2] = new THREE.ProxyVector2(uvarray, f.c * 2);
  6379. }
  6380. }
  6381. // Return a reference to the newly-created array
  6382. return this.faceVertexUvs;
  6383. };
  6384. THREE.Geometry99.prototype.populateProxyFromBuffer = function ( attr, buffername, proxytype, itemsize, offset, count ) {
  6385. if ( this.attributes[ buffername ] ) {
  6386. var array = this.attributes[ buffername ].array;
  6387. var size = itemsize || this.attributes[ buffername ].itemSize;
  6388. var start = offset || 0;
  6389. count = count || ( array.length / size - start );
  6390. for ( var i = start, l = start + count; i < l; i ++ ) {
  6391. attr.push( new proxytype( array, i * size ) );
  6392. }
  6393. }
  6394. };
  6395. /**
  6396. * @author mrdoob / http://mrdoob.com/
  6397. */
  6398. THREE.IndexedGeometry2 = function ( indices, vertices, normals, uvs ) {
  6399. THREE.BufferGeometry.call( this );
  6400. this.attributes[ 'index' ] = { array: indices, itemSize: 1 };
  6401. this.attributes[ 'position' ] = { array: vertices, itemSize: 3 };
  6402. this.attributes[ 'normal' ] = { array: normals, itemSize: 3 };
  6403. this.attributes[ 'uv' ] = { array: uvs, itemSize: 2 };
  6404. };
  6405. THREE.IndexedGeometry2.prototype = Object.create( THREE.Geometry99.prototype );
  6406. /**
  6407. * @author mrdoob / http://mrdoob.com/
  6408. */
  6409. THREE.ProxyVector2 = function ( array, offset ) {
  6410. this.array = array;
  6411. this.offset = offset;
  6412. };
  6413. THREE.ProxyVector2.prototype = Object.create( THREE.Vector2.prototype );
  6414. Object.defineProperties( THREE.ProxyVector2.prototype, {
  6415. 'x': {
  6416. get: function () { return this.array[ this.offset ]; },
  6417. set: function ( v ) { this.array[ this.offset ] = v; }
  6418. },
  6419. 'y': {
  6420. get: function () { return this.array[ this.offset + 1 ]; },
  6421. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6422. }
  6423. } );
  6424. /**
  6425. * @author mrdoob / http://mrdoob.com/
  6426. */
  6427. THREE.ProxyVector3 = function ( array, offset ) {
  6428. this.array = array;
  6429. this.offset = offset;
  6430. };
  6431. THREE.ProxyVector3.prototype = Object.create( THREE.Vector3.prototype );
  6432. Object.defineProperties( THREE.ProxyVector3.prototype, {
  6433. 'x': {
  6434. get: function () { return this.array[ this.offset ]; },
  6435. set: function ( v ) { this.array[ this.offset ] = v; }
  6436. },
  6437. 'y': {
  6438. get: function () { return this.array[ this.offset + 1 ]; },
  6439. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6440. },
  6441. 'z': {
  6442. get: function () { return this.array[ this.offset + 2 ]; },
  6443. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  6444. }
  6445. } );
  6446. /**
  6447. * @author mrdoob / http://mrdoob.com/
  6448. */
  6449. THREE.ProxyFace3 = function ( array, offset, vertexNormals ) {
  6450. this.array = array;
  6451. this.offset = offset;
  6452. this.vertexNormals = vertexNormals;
  6453. //THREE.Face3.call( this, array[offset], array[offset+1], array[offset+2] /*, normal, color, materialIndex */);
  6454. }
  6455. THREE.ProxyFace3.prototype = Object.create( THREE.Face3.prototype );
  6456. Object.defineProperties( THREE.ProxyFace3.prototype, {
  6457. 'a': {
  6458. enumerable: true,
  6459. get: function () { return this.array[ this.offset ]; },
  6460. set: function ( v ) { this.array[ this.offset ] = v; }
  6461. },
  6462. 'b': {
  6463. enumerable: true,
  6464. get: function () { return this.array[ this.offset + 1 ]; },
  6465. set: function ( v ) { this.array[ this.offset + 1 ] = v; }
  6466. },
  6467. 'c': {
  6468. enumerable: true,
  6469. get: function () { return this.array[ this.offset + 2 ]; },
  6470. set: function ( v ) { this.array[ this.offset + 2 ] = v; }
  6471. },
  6472. } );
  6473. /**
  6474. * @author mrdoob / http://mrdoob.com/
  6475. * @author mikael emtinger / http://gomo.se/
  6476. * @author WestLangley / http://github.com/WestLangley
  6477. */
  6478. THREE.Camera = function () {
  6479. THREE.Object3D.call( this );
  6480. this.matrixWorldInverse = new THREE.Matrix4();
  6481. this.projectionMatrix = new THREE.Matrix4();
  6482. };
  6483. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  6484. THREE.Camera.prototype.lookAt = function () {
  6485. // This routine does not support cameras with rotated and/or translated parent(s)
  6486. var m1 = new THREE.Matrix4();
  6487. return function ( vector ) {
  6488. m1.lookAt( this.position, vector, this.up );
  6489. this.quaternion.setFromRotationMatrix( m1 );
  6490. };
  6491. }();
  6492. THREE.Camera.prototype.clone = function (camera) {
  6493. if ( camera === undefined ) camera = new THREE.Camera();
  6494. THREE.Object3D.prototype.clone.call( this, camera );
  6495. camera.matrixWorldInverse.copy( this.matrixWorldInverse );
  6496. camera.projectionMatrix.copy( this.projectionMatrix );
  6497. return camera;
  6498. };
  6499. /**
  6500. * @author alteredq / http://alteredqualia.com/
  6501. */
  6502. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  6503. THREE.Camera.call( this );
  6504. this.left = left;
  6505. this.right = right;
  6506. this.top = top;
  6507. this.bottom = bottom;
  6508. this.near = ( near !== undefined ) ? near : 0.1;
  6509. this.far = ( far !== undefined ) ? far : 2000;
  6510. this.updateProjectionMatrix();
  6511. };
  6512. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  6513. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  6514. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  6515. };
  6516. THREE.OrthographicCamera.prototype.clone = function () {
  6517. var camera = new THREE.OrthographicCamera();
  6518. THREE.Camera.prototype.clone.call( this, camera );
  6519. camera.left = this.left;
  6520. camera.right = this.right;
  6521. camera.top = this.top;
  6522. camera.bottom = this.bottom;
  6523. camera.near = this.near;
  6524. camera.far = this.far;
  6525. return camera;
  6526. };
  6527. /**
  6528. * @author mrdoob / http://mrdoob.com/
  6529. * @author greggman / http://games.greggman.com/
  6530. * @author zz85 / http://www.lab4games.net/zz85/blog
  6531. */
  6532. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  6533. THREE.Camera.call( this );
  6534. this.fov = fov !== undefined ? fov : 50;
  6535. this.aspect = aspect !== undefined ? aspect : 1;
  6536. this.near = near !== undefined ? near : 0.1;
  6537. this.far = far !== undefined ? far : 2000;
  6538. this.updateProjectionMatrix();
  6539. };
  6540. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  6541. /**
  6542. * Uses Focal Length (in mm) to estimate and set FOV
  6543. * 35mm (fullframe) camera is used if frame size is not specified;
  6544. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  6545. */
  6546. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  6547. if ( frameHeight === undefined ) frameHeight = 24;
  6548. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  6549. this.updateProjectionMatrix();
  6550. }
  6551. /**
  6552. * Sets an offset in a larger frustum. This is useful for multi-window or
  6553. * multi-monitor/multi-machine setups.
  6554. *
  6555. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  6556. * the monitors are in grid like this
  6557. *
  6558. * +---+---+---+
  6559. * | A | B | C |
  6560. * +---+---+---+
  6561. * | D | E | F |
  6562. * +---+---+---+
  6563. *
  6564. * then for each monitor you would call it like this
  6565. *
  6566. * var w = 1920;
  6567. * var h = 1080;
  6568. * var fullWidth = w * 3;
  6569. * var fullHeight = h * 2;
  6570. *
  6571. * --A--
  6572. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  6573. * --B--
  6574. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  6575. * --C--
  6576. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  6577. * --D--
  6578. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  6579. * --E--
  6580. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  6581. * --F--
  6582. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  6583. *
  6584. * Note there is no reason monitors have to be the same size or in a grid.
  6585. */
  6586. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  6587. this.fullWidth = fullWidth;
  6588. this.fullHeight = fullHeight;
  6589. this.x = x;
  6590. this.y = y;
  6591. this.width = width;
  6592. this.height = height;
  6593. this.updateProjectionMatrix();
  6594. };
  6595. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  6596. if ( this.fullWidth ) {
  6597. var aspect = this.fullWidth / this.fullHeight;
  6598. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  6599. var bottom = -top;
  6600. var left = aspect * bottom;
  6601. var right = aspect * top;
  6602. var width = Math.abs( right - left );
  6603. var height = Math.abs( top - bottom );
  6604. this.projectionMatrix.makeFrustum(
  6605. left + this.x * width / this.fullWidth,
  6606. left + ( this.x + this.width ) * width / this.fullWidth,
  6607. top - ( this.y + this.height ) * height / this.fullHeight,
  6608. top - this.y * height / this.fullHeight,
  6609. this.near,
  6610. this.far
  6611. );
  6612. } else {
  6613. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  6614. }
  6615. };
  6616. THREE.PerspectiveCamera.prototype.clone = function () {
  6617. var camera = new THREE.PerspectiveCamera();
  6618. THREE.Camera.prototype.clone.call( this, camera );
  6619. camera.fov = this.fov;
  6620. camera.aspect = this.aspect;
  6621. camera.near = this.near;
  6622. camera.far = this.far;
  6623. return camera;
  6624. };
  6625. /**
  6626. * @author mrdoob / http://mrdoob.com/
  6627. * @author alteredq / http://alteredqualia.com/
  6628. */
  6629. THREE.Light = function ( color ) {
  6630. THREE.Object3D.call( this );
  6631. this.color = new THREE.Color( color );
  6632. };
  6633. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  6634. THREE.Light.prototype.clone = function ( light ) {
  6635. if ( light === undefined ) light = new THREE.Light();
  6636. THREE.Object3D.prototype.clone.call( this, light );
  6637. light.color.copy( this.color );
  6638. return light;
  6639. };
  6640. /**
  6641. * @author mrdoob / http://mrdoob.com/
  6642. */
  6643. THREE.AmbientLight = function ( color ) {
  6644. THREE.Light.call( this, color );
  6645. };
  6646. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  6647. THREE.AmbientLight.prototype.clone = function () {
  6648. var light = new THREE.AmbientLight();
  6649. THREE.Light.prototype.clone.call( this, light );
  6650. return light;
  6651. };
  6652. /**
  6653. * @author MPanknin / http://www.redplant.de/
  6654. * @author alteredq / http://alteredqualia.com/
  6655. */
  6656. THREE.AreaLight = function ( color, intensity ) {
  6657. THREE.Light.call( this, color );
  6658. this.normal = new THREE.Vector3( 0, -1, 0 );
  6659. this.right = new THREE.Vector3( 1, 0, 0 );
  6660. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6661. this.width = 1.0;
  6662. this.height = 1.0;
  6663. this.constantAttenuation = 1.5;
  6664. this.linearAttenuation = 0.5;
  6665. this.quadraticAttenuation = 0.1;
  6666. };
  6667. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  6668. /**
  6669. * @author mrdoob / http://mrdoob.com/
  6670. * @author alteredq / http://alteredqualia.com/
  6671. */
  6672. THREE.DirectionalLight = function ( color, intensity ) {
  6673. THREE.Light.call( this, color );
  6674. this.position.set( 0, 1, 0 );
  6675. this.target = new THREE.Object3D();
  6676. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6677. this.castShadow = false;
  6678. this.onlyShadow = false;
  6679. //
  6680. this.shadowCameraNear = 50;
  6681. this.shadowCameraFar = 5000;
  6682. this.shadowCameraLeft = -500;
  6683. this.shadowCameraRight = 500;
  6684. this.shadowCameraTop = 500;
  6685. this.shadowCameraBottom = -500;
  6686. this.shadowCameraVisible = false;
  6687. this.shadowBias = 0;
  6688. this.shadowDarkness = 0.5;
  6689. this.shadowMapWidth = 512;
  6690. this.shadowMapHeight = 512;
  6691. //
  6692. this.shadowCascade = false;
  6693. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  6694. this.shadowCascadeCount = 2;
  6695. this.shadowCascadeBias = [ 0, 0, 0 ];
  6696. this.shadowCascadeWidth = [ 512, 512, 512 ];
  6697. this.shadowCascadeHeight = [ 512, 512, 512 ];
  6698. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  6699. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  6700. this.shadowCascadeArray = [];
  6701. //
  6702. this.shadowMap = null;
  6703. this.shadowMapSize = null;
  6704. this.shadowCamera = null;
  6705. this.shadowMatrix = null;
  6706. };
  6707. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  6708. THREE.DirectionalLight.prototype.clone = function () {
  6709. var light = new THREE.DirectionalLight();
  6710. THREE.Light.prototype.clone.call( this, light );
  6711. light.target = this.target.clone();
  6712. light.intensity = this.intensity;
  6713. light.castShadow = this.castShadow;
  6714. light.onlyShadow = this.onlyShadow;
  6715. //
  6716. light.shadowCameraNear = this.shadowCameraNear;
  6717. light.shadowCameraFar = this.shadowCameraFar;
  6718. light.shadowCameraLeft = this.shadowCameraLeft;
  6719. light.shadowCameraRight = this.shadowCameraRight;
  6720. light.shadowCameraTop = this.shadowCameraTop;
  6721. light.shadowCameraBottom = this.shadowCameraBottom;
  6722. light.shadowCameraVisible = this.shadowCameraVisible;
  6723. light.shadowBias = this.shadowBias;
  6724. light.shadowDarkness = this.shadowDarkness;
  6725. light.shadowMapWidth = this.shadowMapWidth;
  6726. light.shadowMapHeight = this.shadowMapHeight;
  6727. //
  6728. light.shadowCascade = this.shadowCascade;
  6729. light.shadowCascadeOffset.copy( this.shadowCascadeOffset );
  6730. light.shadowCascadeCount = this.shadowCascadeCount;
  6731. light.shadowCascadeBias = this.shadowCascadeBias.slice( 0 );
  6732. light.shadowCascadeWidth = this.shadowCascadeWidth.slice( 0 );
  6733. light.shadowCascadeHeight = this.shadowCascadeHeight.slice( 0 );
  6734. light.shadowCascadeNearZ = this.shadowCascadeNearZ.slice( 0 );
  6735. light.shadowCascadeFarZ = this.shadowCascadeFarZ.slice( 0 );
  6736. return light;
  6737. };
  6738. /**
  6739. * @author alteredq / http://alteredqualia.com/
  6740. */
  6741. THREE.HemisphereLight = function ( skyColor, groundColor, intensity ) {
  6742. THREE.Light.call( this, skyColor );
  6743. this.position.set( 0, 100, 0 );
  6744. this.groundColor = new THREE.Color( groundColor );
  6745. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6746. };
  6747. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  6748. THREE.HemisphereLight.prototype.clone = function () {
  6749. var light = new THREE.HemisphereLight();
  6750. THREE.Light.prototype.clone.call( this, light );
  6751. light.groundColor.copy( this.groundColor );
  6752. light.intensity = this.intensity;
  6753. return light;
  6754. };
  6755. /**
  6756. * @author mrdoob / http://mrdoob.com/
  6757. */
  6758. THREE.PointLight = function ( color, intensity, distance ) {
  6759. THREE.Light.call( this, color );
  6760. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6761. this.distance = ( distance !== undefined ) ? distance : 0;
  6762. };
  6763. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  6764. THREE.PointLight.prototype.clone = function () {
  6765. var light = new THREE.PointLight();
  6766. THREE.Light.prototype.clone.call( this, light );
  6767. light.intensity = this.intensity;
  6768. light.distance = this.distance;
  6769. return light;
  6770. };
  6771. /**
  6772. * @author alteredq / http://alteredqualia.com/
  6773. */
  6774. THREE.SpotLight = function ( color, intensity, distance, angle, exponent ) {
  6775. THREE.Light.call( this, color );
  6776. this.position.set( 0, 1, 0 );
  6777. this.target = new THREE.Object3D();
  6778. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  6779. this.distance = ( distance !== undefined ) ? distance : 0;
  6780. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  6781. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  6782. this.castShadow = false;
  6783. this.onlyShadow = false;
  6784. //
  6785. this.shadowCameraNear = 50;
  6786. this.shadowCameraFar = 5000;
  6787. this.shadowCameraFov = 50;
  6788. this.shadowCameraVisible = false;
  6789. this.shadowBias = 0;
  6790. this.shadowDarkness = 0.5;
  6791. this.shadowMapWidth = 512;
  6792. this.shadowMapHeight = 512;
  6793. //
  6794. this.shadowMap = null;
  6795. this.shadowMapSize = null;
  6796. this.shadowCamera = null;
  6797. this.shadowMatrix = null;
  6798. };
  6799. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  6800. THREE.SpotLight.prototype.clone = function () {
  6801. var light = new THREE.SpotLight();
  6802. THREE.Light.prototype.clone.call( this, light );
  6803. light.target = this.target.clone();
  6804. light.intensity = this.intensity;
  6805. light.distance = this.distance;
  6806. light.angle = this.angle;
  6807. light.exponent = this.exponent;
  6808. light.castShadow = this.castShadow;
  6809. light.onlyShadow = this.onlyShadow;
  6810. //
  6811. light.shadowCameraNear = this.shadowCameraNear;
  6812. light.shadowCameraFar = this.shadowCameraFar;
  6813. light.shadowCameraFov = this.shadowCameraFov;
  6814. light.shadowCameraVisible = this.shadowCameraVisible;
  6815. light.shadowBias = this.shadowBias;
  6816. light.shadowDarkness = this.shadowDarkness;
  6817. light.shadowMapWidth = this.shadowMapWidth;
  6818. light.shadowMapHeight = this.shadowMapHeight;
  6819. return light;
  6820. };
  6821. /**
  6822. * @author mrdoob / http://mrdoob.com/
  6823. */
  6824. THREE.Cache = function () {
  6825. this.files = {};
  6826. };
  6827. THREE.Cache.prototype = {
  6828. constructor: THREE.Cache,
  6829. add: function ( key, file ) {
  6830. // console.log( 'THREE.Cache', 'Adding key:', key );
  6831. this.files[ key ] = file;
  6832. },
  6833. get: function ( key ) {
  6834. // console.log( 'THREE.Cache', 'Checking key:', key );
  6835. return this.files[ key ];
  6836. },
  6837. remove: function ( key ) {
  6838. delete this.files[ key ];
  6839. },
  6840. clear: function () {
  6841. this.files = {}
  6842. }
  6843. };
  6844. /**
  6845. * @author alteredq / http://alteredqualia.com/
  6846. */
  6847. THREE.Loader = function ( showStatus ) {
  6848. this.showStatus = showStatus;
  6849. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6850. this.imageLoader = new THREE.ImageLoader();
  6851. this.onLoadStart = function () {};
  6852. this.onLoadProgress = function () {};
  6853. this.onLoadComplete = function () {};
  6854. };
  6855. THREE.Loader.prototype = {
  6856. constructor: THREE.Loader,
  6857. crossOrigin: undefined,
  6858. addStatusElement: function () {
  6859. var e = document.createElement( "div" );
  6860. e.style.position = "absolute";
  6861. e.style.right = "0px";
  6862. e.style.top = "0px";
  6863. e.style.fontSize = "0.8em";
  6864. e.style.textAlign = "left";
  6865. e.style.background = "rgba(0,0,0,0.25)";
  6866. e.style.color = "#fff";
  6867. e.style.width = "120px";
  6868. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6869. e.style.zIndex = 1000;
  6870. e.innerHTML = "Loading ...";
  6871. return e;
  6872. },
  6873. updateProgress: function ( progress ) {
  6874. var message = "Loaded ";
  6875. if ( progress.total ) {
  6876. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6877. } else {
  6878. message += ( progress.loaded / 1024 ).toFixed(2) + " KB";
  6879. }
  6880. this.statusDomElement.innerHTML = message;
  6881. },
  6882. extractUrlBase: function ( url ) {
  6883. var parts = url.split( '/' );
  6884. if ( parts.length === 1 ) return './';
  6885. parts.pop();
  6886. return parts.join( '/' ) + '/';
  6887. },
  6888. initMaterials: function ( materials, texturePath ) {
  6889. var array = [];
  6890. for ( var i = 0; i < materials.length; ++ i ) {
  6891. array[ i ] = this.createMaterial( materials[ i ], texturePath );
  6892. }
  6893. return array;
  6894. },
  6895. needsTangents: function ( materials ) {
  6896. for( var i = 0, il = materials.length; i < il; i ++ ) {
  6897. var m = materials[ i ];
  6898. if ( m instanceof THREE.ShaderMaterial ) return true;
  6899. }
  6900. return false;
  6901. },
  6902. createMaterial: function ( m, texturePath ) {
  6903. var scope = this;
  6904. function nearest_pow2( n ) {
  6905. var l = Math.log( n ) / Math.LN2;
  6906. return Math.pow( 2, Math.round( l ) );
  6907. }
  6908. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  6909. var isCompressed = /\.dds$/i.test( sourceFile );
  6910. var fullPath = texturePath + sourceFile;
  6911. if ( isCompressed ) {
  6912. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  6913. where[ name ] = texture;
  6914. } else {
  6915. var texture = document.createElement( 'canvas' );
  6916. where[ name ] = new THREE.Texture( texture );
  6917. }
  6918. where[ name ].sourceFile = sourceFile;
  6919. if( repeat ) {
  6920. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6921. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6922. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6923. }
  6924. if ( offset ) {
  6925. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6926. }
  6927. if ( wrap ) {
  6928. var wrapMap = {
  6929. "repeat": THREE.RepeatWrapping,
  6930. "mirror": THREE.MirroredRepeatWrapping
  6931. }
  6932. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6933. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6934. }
  6935. if ( anisotropy ) {
  6936. where[ name ].anisotropy = anisotropy;
  6937. }
  6938. if ( ! isCompressed ) {
  6939. var texture = where[ name ];
  6940. scope.imageLoader.crossOrigin = scope.crossOrigin;
  6941. scope.imageLoader.load( fullPath, function ( image ) {
  6942. if ( THREE.Math.isPowerOfTwo( image.width ) === false ||
  6943. THREE.Math.isPowerOfTwo( image.height ) === false ) {
  6944. var width = nearest_pow2( image.width );
  6945. var height = nearest_pow2( image.height );
  6946. texture.image.width = width;
  6947. texture.image.height = height;
  6948. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  6949. } else {
  6950. texture.image = image;
  6951. }
  6952. texture.needsUpdate = true;
  6953. } );
  6954. }
  6955. }
  6956. function rgb2hex( rgb ) {
  6957. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6958. }
  6959. // defaults
  6960. var mtype = "MeshLambertMaterial";
  6961. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  6962. // parameters from model file
  6963. if ( m.shading ) {
  6964. var shading = m.shading.toLowerCase();
  6965. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6966. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6967. }
  6968. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6969. mpars.blending = THREE[ m.blending ];
  6970. }
  6971. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6972. mpars.transparent = m.transparent;
  6973. }
  6974. if ( m.depthTest !== undefined ) {
  6975. mpars.depthTest = m.depthTest;
  6976. }
  6977. if ( m.depthWrite !== undefined ) {
  6978. mpars.depthWrite = m.depthWrite;
  6979. }
  6980. if ( m.visible !== undefined ) {
  6981. mpars.visible = m.visible;
  6982. }
  6983. if ( m.flipSided !== undefined ) {
  6984. mpars.side = THREE.BackSide;
  6985. }
  6986. if ( m.doubleSided !== undefined ) {
  6987. mpars.side = THREE.DoubleSide;
  6988. }
  6989. if ( m.wireframe !== undefined ) {
  6990. mpars.wireframe = m.wireframe;
  6991. }
  6992. if ( m.vertexColors !== undefined ) {
  6993. if ( m.vertexColors === "face" ) {
  6994. mpars.vertexColors = THREE.FaceColors;
  6995. } else if ( m.vertexColors ) {
  6996. mpars.vertexColors = THREE.VertexColors;
  6997. }
  6998. }
  6999. // colors
  7000. if ( m.colorDiffuse ) {
  7001. mpars.color = rgb2hex( m.colorDiffuse );
  7002. } else if ( m.DbgColor ) {
  7003. mpars.color = m.DbgColor;
  7004. }
  7005. if ( m.colorSpecular ) {
  7006. mpars.specular = rgb2hex( m.colorSpecular );
  7007. }
  7008. if ( m.colorAmbient ) {
  7009. mpars.ambient = rgb2hex( m.colorAmbient );
  7010. }
  7011. // modifiers
  7012. if ( m.transparency ) {
  7013. mpars.opacity = m.transparency;
  7014. }
  7015. if ( m.specularCoef ) {
  7016. mpars.shininess = m.specularCoef;
  7017. }
  7018. // textures
  7019. if ( m.mapDiffuse && texturePath ) {
  7020. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  7021. }
  7022. if ( m.mapLight && texturePath ) {
  7023. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  7024. }
  7025. if ( m.mapBump && texturePath ) {
  7026. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  7027. }
  7028. if ( m.mapNormal && texturePath ) {
  7029. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  7030. }
  7031. if ( m.mapSpecular && texturePath ) {
  7032. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  7033. }
  7034. //
  7035. if ( m.mapBumpScale ) {
  7036. mpars.bumpScale = m.mapBumpScale;
  7037. }
  7038. // special case for normal mapped material
  7039. if ( m.mapNormal ) {
  7040. var shader = THREE.ShaderLib[ "normalmap" ];
  7041. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7042. uniforms[ "tNormal" ].value = mpars.normalMap;
  7043. if ( m.mapNormalFactor ) {
  7044. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  7045. }
  7046. if ( mpars.map ) {
  7047. uniforms[ "tDiffuse" ].value = mpars.map;
  7048. uniforms[ "enableDiffuse" ].value = true;
  7049. }
  7050. if ( mpars.specularMap ) {
  7051. uniforms[ "tSpecular" ].value = mpars.specularMap;
  7052. uniforms[ "enableSpecular" ].value = true;
  7053. }
  7054. if ( mpars.lightMap ) {
  7055. uniforms[ "tAO" ].value = mpars.lightMap;
  7056. uniforms[ "enableAO" ].value = true;
  7057. }
  7058. // for the moment don't handle displacement texture
  7059. uniforms[ "diffuse" ].value.setHex( mpars.color );
  7060. uniforms[ "specular" ].value.setHex( mpars.specular );
  7061. uniforms[ "ambient" ].value.setHex( mpars.ambient );
  7062. uniforms[ "shininess" ].value = mpars.shininess;
  7063. if ( mpars.opacity !== undefined ) {
  7064. uniforms[ "opacity" ].value = mpars.opacity;
  7065. }
  7066. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7067. var material = new THREE.ShaderMaterial( parameters );
  7068. if ( mpars.transparent ) {
  7069. material.transparent = true;
  7070. }
  7071. } else {
  7072. var material = new THREE[ mtype ]( mpars );
  7073. }
  7074. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  7075. return material;
  7076. }
  7077. };
  7078. /**
  7079. * @author mrdoob / http://mrdoob.com/
  7080. */
  7081. THREE.XHRLoader = function ( manager ) {
  7082. this.cache = new THREE.Cache();
  7083. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7084. };
  7085. THREE.XHRLoader.prototype = {
  7086. constructor: THREE.XHRLoader,
  7087. load: function ( url, onLoad, onProgress, onError ) {
  7088. var scope = this;
  7089. var cached = scope.cache.get( url );
  7090. if ( cached !== undefined ) {
  7091. onLoad( cached );
  7092. return;
  7093. }
  7094. var request = new XMLHttpRequest();
  7095. if ( onLoad !== undefined ) {
  7096. request.addEventListener( 'load', function ( event ) {
  7097. scope.cache.add( url, event.target.responseText );
  7098. onLoad( event.target.responseText );
  7099. scope.manager.itemEnd( url );
  7100. }, false );
  7101. }
  7102. if ( onProgress !== undefined ) {
  7103. request.addEventListener( 'progress', function ( event ) {
  7104. onProgress( event );
  7105. }, false );
  7106. }
  7107. if ( onError !== undefined ) {
  7108. request.addEventListener( 'error', function ( event ) {
  7109. onError( event );
  7110. }, false );
  7111. }
  7112. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  7113. request.open( 'GET', url, true );
  7114. request.send( null );
  7115. scope.manager.itemStart( url );
  7116. },
  7117. setCrossOrigin: function ( value ) {
  7118. this.crossOrigin = value;
  7119. }
  7120. };
  7121. /**
  7122. * @author mrdoob / http://mrdoob.com/
  7123. */
  7124. THREE.ImageLoader = function ( manager ) {
  7125. this.cache = new THREE.Cache();
  7126. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7127. };
  7128. THREE.ImageLoader.prototype = {
  7129. constructor: THREE.ImageLoader,
  7130. load: function ( url, onLoad, onProgress, onError ) {
  7131. var scope = this;
  7132. var cached = scope.cache.get( url );
  7133. if ( cached !== undefined ) {
  7134. onLoad( cached );
  7135. return;
  7136. }
  7137. var image = document.createElement( 'img' );
  7138. if ( onLoad !== undefined ) {
  7139. image.addEventListener( 'load', function ( event ) {
  7140. scope.cache.add( url, this );
  7141. onLoad( this );
  7142. scope.manager.itemEnd( url );
  7143. }, false );
  7144. }
  7145. if ( onProgress !== undefined ) {
  7146. image.addEventListener( 'progress', function ( event ) {
  7147. onProgress( event );
  7148. }, false );
  7149. }
  7150. if ( onError !== undefined ) {
  7151. image.addEventListener( 'error', function ( event ) {
  7152. onError( event );
  7153. }, false );
  7154. }
  7155. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  7156. image.src = url;
  7157. scope.manager.itemStart( url );
  7158. return image;
  7159. },
  7160. setCrossOrigin: function ( value ) {
  7161. this.crossOrigin = value;
  7162. }
  7163. }
  7164. /**
  7165. * @author mrdoob / http://mrdoob.com/
  7166. * @author alteredq / http://alteredqualia.com/
  7167. */
  7168. THREE.JSONLoader = function ( showStatus ) {
  7169. THREE.Loader.call( this, showStatus );
  7170. this.withCredentials = false;
  7171. };
  7172. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  7173. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  7174. var scope = this;
  7175. // todo: unify load API to for easier SceneLoader use
  7176. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  7177. this.onLoadStart();
  7178. this.loadAjaxJSON( this, url, callback, texturePath );
  7179. };
  7180. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  7181. var xhr = new XMLHttpRequest();
  7182. var length = 0;
  7183. xhr.onreadystatechange = function () {
  7184. if ( xhr.readyState === xhr.DONE ) {
  7185. if ( xhr.status === 200 || xhr.status === 0 ) {
  7186. if ( xhr.responseText ) {
  7187. var json = JSON.parse( xhr.responseText );
  7188. if ( json.metadata !== undefined && json.metadata.type === 'scene' ) {
  7189. console.error( 'THREE.JSONLoader: "' + url + '" seems to be a Scene. Use THREE.SceneLoader instead.' );
  7190. return;
  7191. }
  7192. var result = context.parse( json, texturePath );
  7193. callback( result.geometry, result.materials );
  7194. } else {
  7195. console.error( 'THREE.JSONLoader: "' + url + '" seems to be unreachable or the file is empty.' );
  7196. }
  7197. // in context of more complex asset initialization
  7198. // do not block on single failed file
  7199. // maybe should go even one more level up
  7200. context.onLoadComplete();
  7201. } else {
  7202. console.error( 'THREE.JSONLoader: Couldn\'t load "' + url + '" (' + xhr.status + ')' );
  7203. }
  7204. } else if ( xhr.readyState === xhr.LOADING ) {
  7205. if ( callbackProgress ) {
  7206. if ( length === 0 ) {
  7207. length = xhr.getResponseHeader( 'Content-Length' );
  7208. }
  7209. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  7210. }
  7211. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  7212. if ( callbackProgress !== undefined ) {
  7213. length = xhr.getResponseHeader( "Content-Length" );
  7214. }
  7215. }
  7216. };
  7217. xhr.open( "GET", url, true );
  7218. xhr.withCredentials = this.withCredentials;
  7219. xhr.send( null );
  7220. };
  7221. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  7222. var scope = this,
  7223. geometry = new THREE.Geometry(),
  7224. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  7225. parseModel( scale );
  7226. parseSkin();
  7227. parseMorphing( scale );
  7228. geometry.computeFaceNormals();
  7229. geometry.computeBoundingSphere();
  7230. function parseModel( scale ) {
  7231. function isBitSet( value, position ) {
  7232. return value & ( 1 << position );
  7233. }
  7234. var i, j, fi,
  7235. offset, zLength,
  7236. colorIndex, normalIndex, uvIndex, materialIndex,
  7237. type,
  7238. isQuad,
  7239. hasMaterial,
  7240. hasFaceVertexUv,
  7241. hasFaceNormal, hasFaceVertexNormal,
  7242. hasFaceColor, hasFaceVertexColor,
  7243. vertex, face, faceA, faceB, color, hex, normal,
  7244. uvLayer, uv, u, v,
  7245. faces = json.faces,
  7246. vertices = json.vertices,
  7247. normals = json.normals,
  7248. colors = json.colors,
  7249. nUvLayers = 0;
  7250. if ( json.uvs !== undefined ) {
  7251. // disregard empty arrays
  7252. for ( i = 0; i < json.uvs.length; i++ ) {
  7253. if ( json.uvs[ i ].length ) nUvLayers ++;
  7254. }
  7255. for ( i = 0; i < nUvLayers; i++ ) {
  7256. geometry.faceVertexUvs[ i ] = [];
  7257. }
  7258. }
  7259. offset = 0;
  7260. zLength = vertices.length;
  7261. while ( offset < zLength ) {
  7262. vertex = new THREE.Vector3();
  7263. vertex.x = vertices[ offset ++ ] * scale;
  7264. vertex.y = vertices[ offset ++ ] * scale;
  7265. vertex.z = vertices[ offset ++ ] * scale;
  7266. geometry.vertices.push( vertex );
  7267. }
  7268. offset = 0;
  7269. zLength = faces.length;
  7270. while ( offset < zLength ) {
  7271. type = faces[ offset ++ ];
  7272. isQuad = isBitSet( type, 0 );
  7273. hasMaterial = isBitSet( type, 1 );
  7274. hasFaceVertexUv = isBitSet( type, 3 );
  7275. hasFaceNormal = isBitSet( type, 4 );
  7276. hasFaceVertexNormal = isBitSet( type, 5 );
  7277. hasFaceColor = isBitSet( type, 6 );
  7278. hasFaceVertexColor = isBitSet( type, 7 );
  7279. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  7280. if ( isQuad ) {
  7281. faceA = new THREE.Face3();
  7282. faceA.a = faces[ offset ];
  7283. faceA.b = faces[ offset + 1 ];
  7284. faceA.c = faces[ offset + 3 ];
  7285. faceB = new THREE.Face3();
  7286. faceB.a = faces[ offset + 1 ];
  7287. faceB.b = faces[ offset + 2 ];
  7288. faceB.c = faces[ offset + 3 ];
  7289. offset += 4;
  7290. if ( hasMaterial ) {
  7291. materialIndex = faces[ offset ++ ];
  7292. faceA.materialIndex = materialIndex;
  7293. faceB.materialIndex = materialIndex;
  7294. }
  7295. // to get face <=> uv index correspondence
  7296. fi = geometry.faces.length;
  7297. if ( hasFaceVertexUv ) {
  7298. for ( i = 0; i < nUvLayers; i++ ) {
  7299. uvLayer = json.uvs[ i ];
  7300. geometry.faceVertexUvs[ i ][ fi ] = [];
  7301. geometry.faceVertexUvs[ i ][ fi + 1 ] = []
  7302. for ( j = 0; j < 4; j ++ ) {
  7303. uvIndex = faces[ offset ++ ];
  7304. u = uvLayer[ uvIndex * 2 ];
  7305. v = uvLayer[ uvIndex * 2 + 1 ];
  7306. uv = new THREE.Vector2( u, v );
  7307. if ( j !== 2 ) geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7308. if ( j !== 0 ) geometry.faceVertexUvs[ i ][ fi + 1 ].push( uv );
  7309. }
  7310. }
  7311. }
  7312. if ( hasFaceNormal ) {
  7313. normalIndex = faces[ offset ++ ] * 3;
  7314. faceA.normal.set(
  7315. normals[ normalIndex ++ ],
  7316. normals[ normalIndex ++ ],
  7317. normals[ normalIndex ]
  7318. );
  7319. faceB.normal.copy( faceA.normal );
  7320. }
  7321. if ( hasFaceVertexNormal ) {
  7322. for ( i = 0; i < 4; i++ ) {
  7323. normalIndex = faces[ offset ++ ] * 3;
  7324. normal = new THREE.Vector3(
  7325. normals[ normalIndex ++ ],
  7326. normals[ normalIndex ++ ],
  7327. normals[ normalIndex ]
  7328. );
  7329. if ( i !== 2 ) faceA.vertexNormals.push( normal );
  7330. if ( i !== 0 ) faceB.vertexNormals.push( normal );
  7331. }
  7332. }
  7333. if ( hasFaceColor ) {
  7334. colorIndex = faces[ offset ++ ];
  7335. hex = colors[ colorIndex ];
  7336. faceA.color.setHex( hex );
  7337. faceB.color.setHex( hex );
  7338. }
  7339. if ( hasFaceVertexColor ) {
  7340. for ( i = 0; i < 4; i++ ) {
  7341. colorIndex = faces[ offset ++ ];
  7342. hex = colors[ colorIndex ];
  7343. if ( i !== 2 ) faceA.vertexColors.push( new THREE.Color( hex ) );
  7344. if ( i !== 0 ) faceB.vertexColors.push( new THREE.Color( hex ) );
  7345. }
  7346. }
  7347. geometry.faces.push( faceA );
  7348. geometry.faces.push( faceB );
  7349. } else {
  7350. face = new THREE.Face3();
  7351. face.a = faces[ offset ++ ];
  7352. face.b = faces[ offset ++ ];
  7353. face.c = faces[ offset ++ ];
  7354. if ( hasMaterial ) {
  7355. materialIndex = faces[ offset ++ ];
  7356. face.materialIndex = materialIndex;
  7357. }
  7358. // to get face <=> uv index correspondence
  7359. fi = geometry.faces.length;
  7360. if ( hasFaceVertexUv ) {
  7361. for ( i = 0; i < nUvLayers; i++ ) {
  7362. uvLayer = json.uvs[ i ];
  7363. geometry.faceVertexUvs[ i ][ fi ] = [];
  7364. for ( j = 0; j < 3; j ++ ) {
  7365. uvIndex = faces[ offset ++ ];
  7366. u = uvLayer[ uvIndex * 2 ];
  7367. v = uvLayer[ uvIndex * 2 + 1 ];
  7368. uv = new THREE.Vector2( u, v );
  7369. geometry.faceVertexUvs[ i ][ fi ].push( uv );
  7370. }
  7371. }
  7372. }
  7373. if ( hasFaceNormal ) {
  7374. normalIndex = faces[ offset ++ ] * 3;
  7375. face.normal.set(
  7376. normals[ normalIndex ++ ],
  7377. normals[ normalIndex ++ ],
  7378. normals[ normalIndex ]
  7379. );
  7380. }
  7381. if ( hasFaceVertexNormal ) {
  7382. for ( i = 0; i < 3; i++ ) {
  7383. normalIndex = faces[ offset ++ ] * 3;
  7384. normal = new THREE.Vector3(
  7385. normals[ normalIndex ++ ],
  7386. normals[ normalIndex ++ ],
  7387. normals[ normalIndex ]
  7388. );
  7389. face.vertexNormals.push( normal );
  7390. }
  7391. }
  7392. if ( hasFaceColor ) {
  7393. colorIndex = faces[ offset ++ ];
  7394. face.color.setHex( colors[ colorIndex ] );
  7395. }
  7396. if ( hasFaceVertexColor ) {
  7397. for ( i = 0; i < 3; i++ ) {
  7398. colorIndex = faces[ offset ++ ];
  7399. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  7400. }
  7401. }
  7402. geometry.faces.push( face );
  7403. }
  7404. }
  7405. };
  7406. function parseSkin() {
  7407. var influencesPerVertex = ( json.influencesPerVertex !== undefined ) ? json.influencesPerVertex : 2;
  7408. if ( json.skinWeights ) {
  7409. for ( var i = 0, l = json.skinWeights.length; i < l; i += influencesPerVertex ) {
  7410. var x = json.skinWeights[ i ];
  7411. var y = ( influencesPerVertex > 1 ) ? json.skinWeights[ i + 1 ] : 0;
  7412. var z = ( influencesPerVertex > 2 ) ? json.skinWeights[ i + 2 ] : 0;
  7413. var w = ( influencesPerVertex > 3 ) ? json.skinWeights[ i + 3 ] : 0;
  7414. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  7415. }
  7416. }
  7417. if ( json.skinIndices ) {
  7418. for ( var i = 0, l = json.skinIndices.length; i < l; i += influencesPerVertex ) {
  7419. var a = json.skinIndices[ i ];
  7420. var b = ( influencesPerVertex > 1 ) ? json.skinIndices[ i + 1 ] : 0;
  7421. var c = ( influencesPerVertex > 2 ) ? json.skinIndices[ i + 2 ] : 0;
  7422. var d = ( influencesPerVertex > 3 ) ? json.skinIndices[ i + 3 ] : 0;
  7423. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  7424. }
  7425. }
  7426. geometry.bones = json.bones;
  7427. if ( geometry.bones && geometry.bones.length > 0 && ( geometry.skinWeights.length !== geometry.skinIndices.length || geometry.skinIndices.length !== geometry.vertices.length ) ) {
  7428. console.warn( 'When skinning, number of vertices (' + geometry.vertices.length + '), skinIndices (' +
  7429. geometry.skinIndices.length + '), and skinWeights (' + geometry.skinWeights.length + ') should match.' );
  7430. }
  7431. // could change this to json.animations[0] or remove completely
  7432. geometry.animation = json.animation;
  7433. geometry.animations = json.animations;
  7434. };
  7435. function parseMorphing( scale ) {
  7436. if ( json.morphTargets !== undefined ) {
  7437. var i, l, v, vl, dstVertices, srcVertices;
  7438. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  7439. geometry.morphTargets[ i ] = {};
  7440. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  7441. geometry.morphTargets[ i ].vertices = [];
  7442. dstVertices = geometry.morphTargets[ i ].vertices;
  7443. srcVertices = json.morphTargets [ i ].vertices;
  7444. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  7445. var vertex = new THREE.Vector3();
  7446. vertex.x = srcVertices[ v ] * scale;
  7447. vertex.y = srcVertices[ v + 1 ] * scale;
  7448. vertex.z = srcVertices[ v + 2 ] * scale;
  7449. dstVertices.push( vertex );
  7450. }
  7451. }
  7452. }
  7453. if ( json.morphColors !== undefined ) {
  7454. var i, l, c, cl, dstColors, srcColors, color;
  7455. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  7456. geometry.morphColors[ i ] = {};
  7457. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  7458. geometry.morphColors[ i ].colors = [];
  7459. dstColors = geometry.morphColors[ i ].colors;
  7460. srcColors = json.morphColors [ i ].colors;
  7461. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  7462. color = new THREE.Color( 0xffaa00 );
  7463. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  7464. dstColors.push( color );
  7465. }
  7466. }
  7467. }
  7468. };
  7469. if ( json.materials === undefined || json.materials.length === 0 ) {
  7470. return { geometry: geometry };
  7471. } else {
  7472. var materials = this.initMaterials( json.materials, texturePath );
  7473. if ( this.needsTangents( materials ) ) {
  7474. geometry.computeTangents();
  7475. }
  7476. return { geometry: geometry, materials: materials };
  7477. }
  7478. };
  7479. /**
  7480. * @author mrdoob / http://mrdoob.com/
  7481. */
  7482. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  7483. var scope = this;
  7484. var loaded = 0, total = 0;
  7485. this.onLoad = onLoad;
  7486. this.onProgress = onProgress;
  7487. this.onError = onError;
  7488. this.itemStart = function ( url ) {
  7489. total ++;
  7490. };
  7491. this.itemEnd = function ( url ) {
  7492. loaded ++;
  7493. if ( scope.onProgress !== undefined ) {
  7494. scope.onProgress( url, loaded, total );
  7495. }
  7496. if ( loaded === total && scope.onLoad !== undefined ) {
  7497. scope.onLoad();
  7498. }
  7499. };
  7500. };
  7501. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  7502. /**
  7503. * @author mrdoob / http://mrdoob.com/
  7504. */
  7505. THREE.BufferGeometryLoader = function ( manager ) {
  7506. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7507. };
  7508. THREE.BufferGeometryLoader.prototype = {
  7509. constructor: THREE.BufferGeometryLoader,
  7510. load: function ( url, onLoad, onProgress, onError ) {
  7511. var scope = this;
  7512. var loader = new THREE.XHRLoader();
  7513. loader.setCrossOrigin( this.crossOrigin );
  7514. loader.load( url, function ( text ) {
  7515. onLoad( scope.parse( JSON.parse( text ) ) );
  7516. } );
  7517. },
  7518. setCrossOrigin: function ( value ) {
  7519. this.crossOrigin = value;
  7520. },
  7521. parse: function ( json ) {
  7522. var geometry = new THREE.BufferGeometry();
  7523. var attributes = json.attributes;
  7524. var offsets = json.offsets;
  7525. var boundingSphere = json.boundingSphere;
  7526. for ( var key in attributes ) {
  7527. var attribute = attributes[ key ];
  7528. geometry.attributes[ key ] = {
  7529. itemSize: attribute.itemSize,
  7530. array: new self[ attribute.type ]( attribute.array )
  7531. }
  7532. }
  7533. if ( offsets !== undefined ) {
  7534. geometry.offsets = JSON.parse( JSON.stringify( offsets ) );
  7535. }
  7536. if ( boundingSphere !== undefined ) {
  7537. geometry.boundingSphere = new THREE.Sphere(
  7538. new THREE.Vector3().fromArray( boundingSphere.center !== undefined ? boundingSphere.center : [ 0, 0, 0 ] ),
  7539. boundingSphere.radius
  7540. );
  7541. }
  7542. return geometry;
  7543. }
  7544. };
  7545. /**
  7546. * @author mrdoob / http://mrdoob.com/
  7547. */
  7548. THREE.MaterialLoader = function ( manager ) {
  7549. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7550. };
  7551. THREE.MaterialLoader.prototype = {
  7552. constructor: THREE.MaterialLoader,
  7553. load: function ( url, onLoad, onProgress, onError ) {
  7554. var scope = this;
  7555. var loader = new THREE.XHRLoader();
  7556. loader.setCrossOrigin( this.crossOrigin );
  7557. loader.load( url, function ( text ) {
  7558. onLoad( scope.parse( JSON.parse( text ) ) );
  7559. } );
  7560. },
  7561. setCrossOrigin: function ( value ) {
  7562. this.crossOrigin = value;
  7563. },
  7564. parse: function ( json ) {
  7565. var material = new THREE[ json.type ];
  7566. if ( json.color !== undefined ) material.color.setHex( json.color );
  7567. if ( json.ambient !== undefined ) material.ambient.setHex( json.ambient );
  7568. if ( json.emissive !== undefined ) material.emissive.setHex( json.emissive );
  7569. if ( json.specular !== undefined ) material.specular.setHex( json.specular );
  7570. if ( json.shininess !== undefined ) material.shininess = json.shininess;
  7571. if ( json.vertexColors !== undefined ) material.vertexColors = json.vertexColors;
  7572. if ( json.blending !== undefined ) material.blending = json.blending;
  7573. if ( json.side !== undefined ) material.side = json.side;
  7574. if ( json.opacity !== undefined ) material.opacity = json.opacity;
  7575. if ( json.transparent !== undefined ) material.transparent = json.transparent;
  7576. if ( json.wireframe !== undefined ) material.wireframe = json.wireframe;
  7577. if ( json.materials !== undefined ) {
  7578. for ( var i = 0, l = json.materials.length; i < l; i ++ ) {
  7579. material.materials.push( this.parse( json.materials[ i ] ) );
  7580. }
  7581. }
  7582. return material;
  7583. }
  7584. };
  7585. /**
  7586. * @author mrdoob / http://mrdoob.com/
  7587. */
  7588. THREE.ObjectLoader = function ( manager ) {
  7589. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7590. };
  7591. THREE.ObjectLoader.prototype = {
  7592. constructor: THREE.ObjectLoader,
  7593. load: function ( url, onLoad, onProgress, onError ) {
  7594. var scope = this;
  7595. var loader = new THREE.XHRLoader( scope.manager );
  7596. loader.setCrossOrigin( this.crossOrigin );
  7597. loader.load( url, function ( text ) {
  7598. onLoad( scope.parse( JSON.parse( text ) ) );
  7599. } );
  7600. },
  7601. setCrossOrigin: function ( value ) {
  7602. this.crossOrigin = value;
  7603. },
  7604. parse: function ( json ) {
  7605. var geometries = this.parseGeometries( json.geometries );
  7606. var materials = this.parseMaterials( json.materials );
  7607. var object = this.parseObject( json.object, geometries, materials );
  7608. return object;
  7609. },
  7610. parseGeometries: function ( json ) {
  7611. var geometries = {};
  7612. if ( json !== undefined ) {
  7613. var geometryLoader = new THREE.JSONLoader();
  7614. var bufferGeometryLoader = new THREE.BufferGeometryLoader();
  7615. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7616. var geometry;
  7617. var data = json[ i ];
  7618. switch ( data.type ) {
  7619. case 'PlaneGeometry':
  7620. geometry = new THREE.PlaneGeometry(
  7621. data.width,
  7622. data.height,
  7623. data.widthSegments,
  7624. data.heightSegments
  7625. );
  7626. break;
  7627. case 'BoxGeometry':
  7628. case 'CubeGeometry': // DEPRECATED
  7629. geometry = new THREE.BoxGeometry(
  7630. data.width,
  7631. data.height,
  7632. data.depth,
  7633. data.widthSegments,
  7634. data.heightSegments,
  7635. data.depthSegments
  7636. );
  7637. break;
  7638. case 'CircleGeometry':
  7639. geometry = new THREE.CircleGeometry(
  7640. data.radius,
  7641. data.segments
  7642. );
  7643. break;
  7644. case 'CylinderGeometry':
  7645. geometry = new THREE.CylinderGeometry(
  7646. data.radiusTop,
  7647. data.radiusBottom,
  7648. data.height,
  7649. data.radialSegments,
  7650. data.heightSegments,
  7651. data.openEnded
  7652. );
  7653. break;
  7654. case 'SphereGeometry':
  7655. geometry = new THREE.SphereGeometry(
  7656. data.radius,
  7657. data.widthSegments,
  7658. data.heightSegments,
  7659. data.phiStart,
  7660. data.phiLength,
  7661. data.thetaStart,
  7662. data.thetaLength
  7663. );
  7664. break;
  7665. case 'IcosahedronGeometry':
  7666. geometry = new THREE.IcosahedronGeometry(
  7667. data.radius,
  7668. data.detail
  7669. );
  7670. break;
  7671. case 'TorusGeometry':
  7672. geometry = new THREE.TorusGeometry(
  7673. data.radius,
  7674. data.tube,
  7675. data.radialSegments,
  7676. data.tubularSegments,
  7677. data.arc
  7678. );
  7679. break;
  7680. case 'TorusKnotGeometry':
  7681. geometry = new THREE.TorusKnotGeometry(
  7682. data.radius,
  7683. data.tube,
  7684. data.radialSegments,
  7685. data.tubularSegments,
  7686. data.p,
  7687. data.q,
  7688. data.heightScale
  7689. );
  7690. break;
  7691. case 'BufferGeometry':
  7692. geometry = bufferGeometryLoader.parse( data.data );
  7693. break;
  7694. case 'Geometry':
  7695. geometry = geometryLoader.parse( data.data ).geometry;
  7696. break;
  7697. }
  7698. geometry.uuid = data.uuid;
  7699. if ( data.name !== undefined ) geometry.name = data.name;
  7700. geometries[ data.uuid ] = geometry;
  7701. }
  7702. }
  7703. return geometries;
  7704. },
  7705. parseMaterials: function ( json ) {
  7706. var materials = {};
  7707. if ( json !== undefined ) {
  7708. var loader = new THREE.MaterialLoader();
  7709. for ( var i = 0, l = json.length; i < l; i ++ ) {
  7710. var data = json[ i ];
  7711. var material = loader.parse( data );
  7712. material.uuid = data.uuid;
  7713. if ( data.name !== undefined ) material.name = data.name;
  7714. materials[ data.uuid ] = material;
  7715. }
  7716. }
  7717. return materials;
  7718. },
  7719. parseObject: function () {
  7720. var matrix = new THREE.Matrix4();
  7721. return function ( data, geometries, materials ) {
  7722. var object;
  7723. switch ( data.type ) {
  7724. case 'Scene':
  7725. object = new THREE.Scene();
  7726. break;
  7727. case 'PerspectiveCamera':
  7728. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  7729. break;
  7730. case 'OrthographicCamera':
  7731. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  7732. break;
  7733. case 'AmbientLight':
  7734. object = new THREE.AmbientLight( data.color );
  7735. break;
  7736. case 'DirectionalLight':
  7737. object = new THREE.DirectionalLight( data.color, data.intensity );
  7738. break;
  7739. case 'PointLight':
  7740. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  7741. break;
  7742. case 'SpotLight':
  7743. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  7744. break;
  7745. case 'HemisphereLight':
  7746. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  7747. break;
  7748. case 'Mesh':
  7749. var geometry = geometries[ data.geometry ];
  7750. var material = materials[ data.material ];
  7751. if ( geometry === undefined ) {
  7752. console.error( 'THREE.ObjectLoader: Undefined geometry ' + data.geometry );
  7753. }
  7754. if ( material === undefined ) {
  7755. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7756. }
  7757. object = new THREE.Mesh( geometry, material );
  7758. break;
  7759. case 'Sprite':
  7760. var material = materials[ data.material ];
  7761. if ( material === undefined ) {
  7762. console.error( 'THREE.ObjectLoader: Undefined material ' + data.material );
  7763. }
  7764. object = new THREE.Sprite( material );
  7765. break;
  7766. default:
  7767. object = new THREE.Object3D();
  7768. }
  7769. object.uuid = data.uuid;
  7770. if ( data.name !== undefined ) object.name = data.name;
  7771. if ( data.matrix !== undefined ) {
  7772. matrix.fromArray( data.matrix );
  7773. matrix.decompose( object.position, object.quaternion, object.scale );
  7774. } else {
  7775. if ( data.position !== undefined ) object.position.fromArray( data.position );
  7776. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  7777. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  7778. }
  7779. if ( data.visible !== undefined ) object.visible = data.visible;
  7780. if ( data.userData !== undefined ) object.userData = data.userData;
  7781. if ( data.children !== undefined ) {
  7782. for ( var child in data.children ) {
  7783. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  7784. }
  7785. }
  7786. return object;
  7787. }
  7788. }()
  7789. };
  7790. /**
  7791. * @author alteredq / http://alteredqualia.com/
  7792. */
  7793. THREE.SceneLoader = function () {
  7794. this.onLoadStart = function () {};
  7795. this.onLoadProgress = function() {};
  7796. this.onLoadComplete = function () {};
  7797. this.callbackSync = function () {};
  7798. this.callbackProgress = function () {};
  7799. this.geometryHandlers = {};
  7800. this.hierarchyHandlers = {};
  7801. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  7802. };
  7803. THREE.SceneLoader.prototype = {
  7804. constructor: THREE.SceneLoader,
  7805. load: function ( url, onLoad, onProgress, onError ) {
  7806. var scope = this;
  7807. var loader = new THREE.XHRLoader( scope.manager );
  7808. loader.setCrossOrigin( this.crossOrigin );
  7809. loader.load( url, function ( text ) {
  7810. scope.parse( JSON.parse( text ), onLoad, url );
  7811. } );
  7812. },
  7813. setCrossOrigin: function ( value ) {
  7814. this.crossOrigin = value;
  7815. },
  7816. addGeometryHandler: function ( typeID, loaderClass ) {
  7817. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  7818. },
  7819. addHierarchyHandler: function ( typeID, loaderClass ) {
  7820. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  7821. },
  7822. parse: function ( json, callbackFinished, url ) {
  7823. var scope = this;
  7824. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  7825. var geometry, material, camera, fog,
  7826. texture, images, color,
  7827. light, hex, intensity,
  7828. counter_models, counter_textures,
  7829. total_models, total_textures,
  7830. result;
  7831. var target_array = [];
  7832. var data = json;
  7833. // async geometry loaders
  7834. for ( var typeID in this.geometryHandlers ) {
  7835. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  7836. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7837. }
  7838. // async hierachy loaders
  7839. for ( var typeID in this.hierarchyHandlers ) {
  7840. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  7841. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  7842. }
  7843. counter_models = 0;
  7844. counter_textures = 0;
  7845. result = {
  7846. scene: new THREE.Scene(),
  7847. geometries: {},
  7848. face_materials: {},
  7849. materials: {},
  7850. textures: {},
  7851. objects: {},
  7852. cameras: {},
  7853. lights: {},
  7854. fogs: {},
  7855. empties: {},
  7856. groups: {}
  7857. };
  7858. if ( data.transform ) {
  7859. var position = data.transform.position,
  7860. rotation = data.transform.rotation,
  7861. scale = data.transform.scale;
  7862. if ( position ) {
  7863. result.scene.position.fromArray( position );
  7864. }
  7865. if ( rotation ) {
  7866. result.scene.rotation.fromArray( rotation );
  7867. }
  7868. if ( scale ) {
  7869. result.scene.scale.fromArray( scale );
  7870. }
  7871. if ( position || rotation || scale ) {
  7872. result.scene.updateMatrix();
  7873. result.scene.updateMatrixWorld();
  7874. }
  7875. }
  7876. function get_url( source_url, url_type ) {
  7877. if ( url_type == "relativeToHTML" ) {
  7878. return source_url;
  7879. } else {
  7880. return urlBase + source_url;
  7881. }
  7882. };
  7883. // toplevel loader function, delegates to handle_children
  7884. function handle_objects() {
  7885. handle_children( result.scene, data.objects );
  7886. }
  7887. // handle all the children from the loaded json and attach them to given parent
  7888. function handle_children( parent, children ) {
  7889. var mat, dst, pos, rot, scl, quat;
  7890. for ( var objID in children ) {
  7891. // check by id if child has already been handled,
  7892. // if not, create new object
  7893. var object = result.objects[ objID ];
  7894. var objJSON = children[ objID ];
  7895. if ( object === undefined ) {
  7896. // meshes
  7897. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7898. if ( objJSON.loading === undefined ) {
  7899. var reservedTypes = {
  7900. "type": 1, "url": 1, "material": 1,
  7901. "position": 1, "rotation": 1, "scale" : 1,
  7902. "visible": 1, "children": 1, "userData": 1,
  7903. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  7904. };
  7905. var loaderParameters = {};
  7906. for ( var parType in objJSON ) {
  7907. if ( ! ( parType in reservedTypes ) ) {
  7908. loaderParameters[ parType ] = objJSON[ parType ];
  7909. }
  7910. }
  7911. material = result.materials[ objJSON.material ];
  7912. objJSON.loading = true;
  7913. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  7914. // ColladaLoader
  7915. if ( loader.options ) {
  7916. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  7917. // UTF8Loader
  7918. // OBJLoader
  7919. } else {
  7920. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  7921. }
  7922. }
  7923. } else if ( objJSON.geometry !== undefined ) {
  7924. geometry = result.geometries[ objJSON.geometry ];
  7925. // geometry already loaded
  7926. if ( geometry ) {
  7927. var needsTangents = false;
  7928. material = result.materials[ objJSON.material ];
  7929. needsTangents = material instanceof THREE.ShaderMaterial;
  7930. pos = objJSON.position;
  7931. rot = objJSON.rotation;
  7932. scl = objJSON.scale;
  7933. mat = objJSON.matrix;
  7934. quat = objJSON.quaternion;
  7935. // use materials from the model file
  7936. // if there is no material specified in the object
  7937. if ( ! objJSON.material ) {
  7938. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7939. }
  7940. // use materials from the model file
  7941. // if there is just empty face material
  7942. // (must create new material as each model has its own face material)
  7943. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  7944. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  7945. }
  7946. if ( material instanceof THREE.MeshFaceMaterial ) {
  7947. for ( var i = 0; i < material.materials.length; i ++ ) {
  7948. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  7949. }
  7950. }
  7951. if ( needsTangents ) {
  7952. geometry.computeTangents();
  7953. }
  7954. if ( objJSON.skin ) {
  7955. object = new THREE.SkinnedMesh( geometry, material );
  7956. } else if ( objJSON.morph ) {
  7957. object = new THREE.MorphAnimMesh( geometry, material );
  7958. if ( objJSON.duration !== undefined ) {
  7959. object.duration = objJSON.duration;
  7960. }
  7961. if ( objJSON.time !== undefined ) {
  7962. object.time = objJSON.time;
  7963. }
  7964. if ( objJSON.mirroredLoop !== undefined ) {
  7965. object.mirroredLoop = objJSON.mirroredLoop;
  7966. }
  7967. if ( material.morphNormals ) {
  7968. geometry.computeMorphNormals();
  7969. }
  7970. } else {
  7971. object = new THREE.Mesh( geometry, material );
  7972. }
  7973. object.name = objID;
  7974. if ( mat ) {
  7975. object.matrixAutoUpdate = false;
  7976. object.matrix.set(
  7977. mat[0], mat[1], mat[2], mat[3],
  7978. mat[4], mat[5], mat[6], mat[7],
  7979. mat[8], mat[9], mat[10], mat[11],
  7980. mat[12], mat[13], mat[14], mat[15]
  7981. );
  7982. } else {
  7983. object.position.fromArray( pos );
  7984. if ( quat ) {
  7985. object.quaternion.fromArray( quat );
  7986. } else {
  7987. object.rotation.fromArray( rot );
  7988. }
  7989. object.scale.fromArray( scl );
  7990. }
  7991. object.visible = objJSON.visible;
  7992. object.castShadow = objJSON.castShadow;
  7993. object.receiveShadow = objJSON.receiveShadow;
  7994. parent.add( object );
  7995. result.objects[ objID ] = object;
  7996. }
  7997. // lights
  7998. } else if ( objJSON.type === "AmbientLight" || objJSON.type === "PointLight" ||
  7999. objJSON.type === "DirectionalLight" || objJSON.type === "SpotLight" ||
  8000. objJSON.type === "HemisphereLight" || objJSON.type === "AreaLight" ) {
  8001. var color = objJSON.color;
  8002. var intensity = objJSON.intensity;
  8003. var distance = objJSON.distance;
  8004. var position = objJSON.position;
  8005. var rotation = objJSON.rotation;
  8006. switch ( objJSON.type ) {
  8007. case 'AmbientLight':
  8008. light = new THREE.AmbientLight( color );
  8009. break;
  8010. case 'PointLight':
  8011. light = new THREE.PointLight( color, intensity, distance );
  8012. light.position.fromArray( position );
  8013. break;
  8014. case 'DirectionalLight':
  8015. light = new THREE.DirectionalLight( color, intensity );
  8016. light.position.fromArray( objJSON.direction );
  8017. break;
  8018. case 'SpotLight':
  8019. light = new THREE.SpotLight( color, intensity, distance, 1 );
  8020. light.angle = objJSON.angle;
  8021. light.position.fromArray( position );
  8022. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  8023. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  8024. break;
  8025. case 'HemisphereLight':
  8026. light = new THREE.DirectionalLight( color, intensity, distance );
  8027. light.target.set( position[ 0 ], position[ 1 ] - distance, position[ 2 ] );
  8028. light.target.applyEuler( new THREE.Euler( rotation[ 0 ], rotation[ 1 ], rotation[ 2 ], 'XYZ' ) );
  8029. break;
  8030. case 'AreaLight':
  8031. light = new THREE.AreaLight(color, intensity);
  8032. light.position.fromArray( position );
  8033. light.width = objJSON.size;
  8034. light.height = objJSON.size_y;
  8035. break;
  8036. }
  8037. parent.add( light );
  8038. light.name = objID;
  8039. result.lights[ objID ] = light;
  8040. result.objects[ objID ] = light;
  8041. // cameras
  8042. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  8043. pos = objJSON.position;
  8044. rot = objJSON.rotation;
  8045. quat = objJSON.quaternion;
  8046. if ( objJSON.type === "PerspectiveCamera" ) {
  8047. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  8048. } else if ( objJSON.type === "OrthographicCamera" ) {
  8049. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  8050. }
  8051. camera.name = objID;
  8052. camera.position.fromArray( pos );
  8053. if ( quat !== undefined ) {
  8054. camera.quaternion.fromArray( quat );
  8055. } else if ( rot !== undefined ) {
  8056. camera.rotation.fromArray( rot );
  8057. }
  8058. parent.add( camera );
  8059. result.cameras[ objID ] = camera;
  8060. result.objects[ objID ] = camera;
  8061. // pure Object3D
  8062. } else {
  8063. pos = objJSON.position;
  8064. rot = objJSON.rotation;
  8065. scl = objJSON.scale;
  8066. quat = objJSON.quaternion;
  8067. object = new THREE.Object3D();
  8068. object.name = objID;
  8069. object.position.fromArray( pos );
  8070. if ( quat ) {
  8071. object.quaternion.fromArray( quat );
  8072. } else {
  8073. object.rotation.fromArray( rot );
  8074. }
  8075. object.scale.fromArray( scl );
  8076. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  8077. parent.add( object );
  8078. result.objects[ objID ] = object;
  8079. result.empties[ objID ] = object;
  8080. }
  8081. if ( object ) {
  8082. if ( objJSON.userData !== undefined ) {
  8083. for ( var key in objJSON.userData ) {
  8084. var value = objJSON.userData[ key ];
  8085. object.userData[ key ] = value;
  8086. }
  8087. }
  8088. if ( objJSON.groups !== undefined ) {
  8089. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  8090. var groupID = objJSON.groups[ i ];
  8091. if ( result.groups[ groupID ] === undefined ) {
  8092. result.groups[ groupID ] = [];
  8093. }
  8094. result.groups[ groupID ].push( objID );
  8095. }
  8096. }
  8097. }
  8098. }
  8099. if ( object !== undefined && objJSON.children !== undefined ) {
  8100. handle_children( object, objJSON.children );
  8101. }
  8102. }
  8103. };
  8104. function handle_mesh( geo, mat, id ) {
  8105. result.geometries[ id ] = geo;
  8106. result.face_materials[ id ] = mat;
  8107. handle_objects();
  8108. };
  8109. function handle_hierarchy( node, id, parent, material, obj ) {
  8110. var p = obj.position;
  8111. var r = obj.rotation;
  8112. var q = obj.quaternion;
  8113. var s = obj.scale;
  8114. node.position.fromArray( p );
  8115. if ( q ) {
  8116. node.quaternion.fromArray( q );
  8117. } else {
  8118. node.rotation.fromArray( r );
  8119. }
  8120. node.scale.fromArray( s );
  8121. // override children materials
  8122. // if object material was specified in JSON explicitly
  8123. if ( material ) {
  8124. node.traverse( function ( child ) {
  8125. child.material = material;
  8126. } );
  8127. }
  8128. // override children visibility
  8129. // with root node visibility as specified in JSON
  8130. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  8131. node.traverse( function ( child ) {
  8132. child.visible = visible;
  8133. } );
  8134. parent.add( node );
  8135. node.name = id;
  8136. result.objects[ id ] = node;
  8137. handle_objects();
  8138. };
  8139. function create_callback_geometry( id ) {
  8140. return function ( geo, mat ) {
  8141. geo.name = id;
  8142. handle_mesh( geo, mat, id );
  8143. counter_models -= 1;
  8144. scope.onLoadComplete();
  8145. async_callback_gate();
  8146. }
  8147. };
  8148. function create_callback_hierachy( id, parent, material, obj ) {
  8149. return function ( event ) {
  8150. var result;
  8151. // loaders which use EventDispatcher
  8152. if ( event.content ) {
  8153. result = event.content;
  8154. // ColladaLoader
  8155. } else if ( event.dae ) {
  8156. result = event.scene;
  8157. // UTF8Loader
  8158. } else {
  8159. result = event;
  8160. }
  8161. handle_hierarchy( result, id, parent, material, obj );
  8162. counter_models -= 1;
  8163. scope.onLoadComplete();
  8164. async_callback_gate();
  8165. }
  8166. };
  8167. function create_callback_embed( id ) {
  8168. return function ( geo, mat ) {
  8169. geo.name = id;
  8170. result.geometries[ id ] = geo;
  8171. result.face_materials[ id ] = mat;
  8172. }
  8173. };
  8174. function async_callback_gate() {
  8175. var progress = {
  8176. totalModels : total_models,
  8177. totalTextures : total_textures,
  8178. loadedModels : total_models - counter_models,
  8179. loadedTextures : total_textures - counter_textures
  8180. };
  8181. scope.callbackProgress( progress, result );
  8182. scope.onLoadProgress();
  8183. if ( counter_models === 0 && counter_textures === 0 ) {
  8184. finalize();
  8185. callbackFinished( result );
  8186. }
  8187. };
  8188. function finalize() {
  8189. // take care of targets which could be asynchronously loaded objects
  8190. for ( var i = 0; i < target_array.length; i ++ ) {
  8191. var ta = target_array[ i ];
  8192. var target = result.objects[ ta.targetName ];
  8193. if ( target ) {
  8194. ta.object.target = target;
  8195. } else {
  8196. // if there was error and target of specified name doesn't exist in the scene file
  8197. // create instead dummy target
  8198. // (target must be added to scene explicitly as parent is already added)
  8199. ta.object.target = new THREE.Object3D();
  8200. result.scene.add( ta.object.target );
  8201. }
  8202. ta.object.target.userData.targetInverse = ta.object;
  8203. }
  8204. };
  8205. var callbackTexture = function ( count ) {
  8206. counter_textures -= count;
  8207. async_callback_gate();
  8208. scope.onLoadComplete();
  8209. };
  8210. // must use this instead of just directly calling callbackTexture
  8211. // because of closure in the calling context loop
  8212. var generateTextureCallback = function ( count ) {
  8213. return function () {
  8214. callbackTexture( count );
  8215. };
  8216. };
  8217. function traverse_json_hierarchy( objJSON, callback ) {
  8218. callback( objJSON );
  8219. if ( objJSON.children !== undefined ) {
  8220. for ( var objChildID in objJSON.children ) {
  8221. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  8222. }
  8223. }
  8224. };
  8225. // first go synchronous elements
  8226. // fogs
  8227. var fogID, fogJSON;
  8228. for ( fogID in data.fogs ) {
  8229. fogJSON = data.fogs[ fogID ];
  8230. if ( fogJSON.type === "linear" ) {
  8231. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  8232. } else if ( fogJSON.type === "exp2" ) {
  8233. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  8234. }
  8235. color = fogJSON.color;
  8236. fog.color.setRGB( color[0], color[1], color[2] );
  8237. result.fogs[ fogID ] = fog;
  8238. }
  8239. // now come potentially asynchronous elements
  8240. // geometries
  8241. // count how many geometries will be loaded asynchronously
  8242. var geoID, geoJSON;
  8243. for ( geoID in data.geometries ) {
  8244. geoJSON = data.geometries[ geoID ];
  8245. if ( geoJSON.type in this.geometryHandlers ) {
  8246. counter_models += 1;
  8247. scope.onLoadStart();
  8248. }
  8249. }
  8250. // count how many hierarchies will be loaded asynchronously
  8251. for ( var objID in data.objects ) {
  8252. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  8253. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  8254. counter_models += 1;
  8255. scope.onLoadStart();
  8256. }
  8257. });
  8258. }
  8259. total_models = counter_models;
  8260. for ( geoID in data.geometries ) {
  8261. geoJSON = data.geometries[ geoID ];
  8262. if ( geoJSON.type === "cube" ) {
  8263. geometry = new THREE.BoxGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  8264. geometry.name = geoID;
  8265. result.geometries[ geoID ] = geometry;
  8266. } else if ( geoJSON.type === "plane" ) {
  8267. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  8268. geometry.name = geoID;
  8269. result.geometries[ geoID ] = geometry;
  8270. } else if ( geoJSON.type === "sphere" ) {
  8271. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  8272. geometry.name = geoID;
  8273. result.geometries[ geoID ] = geometry;
  8274. } else if ( geoJSON.type === "cylinder" ) {
  8275. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  8276. geometry.name = geoID;
  8277. result.geometries[ geoID ] = geometry;
  8278. } else if ( geoJSON.type === "torus" ) {
  8279. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  8280. geometry.name = geoID;
  8281. result.geometries[ geoID ] = geometry;
  8282. } else if ( geoJSON.type === "icosahedron" ) {
  8283. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  8284. geometry.name = geoID;
  8285. result.geometries[ geoID ] = geometry;
  8286. } else if ( geoJSON.type in this.geometryHandlers ) {
  8287. var loaderParameters = {};
  8288. for ( var parType in geoJSON ) {
  8289. if ( parType !== "type" && parType !== "url" ) {
  8290. loaderParameters[ parType ] = geoJSON[ parType ];
  8291. }
  8292. }
  8293. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  8294. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  8295. } else if ( geoJSON.type === "embedded" ) {
  8296. var modelJson = data.embeds[ geoJSON.id ],
  8297. texture_path = "";
  8298. // pass metadata along to jsonLoader so it knows the format version
  8299. modelJson.metadata = data.metadata;
  8300. if ( modelJson ) {
  8301. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  8302. var model = jsonLoader.parse( modelJson, texture_path );
  8303. create_callback_embed( geoID )( model.geometry, model.materials );
  8304. }
  8305. }
  8306. }
  8307. // textures
  8308. // count how many textures will be loaded asynchronously
  8309. var textureID, textureJSON;
  8310. for ( textureID in data.textures ) {
  8311. textureJSON = data.textures[ textureID ];
  8312. if ( textureJSON.url instanceof Array ) {
  8313. counter_textures += textureJSON.url.length;
  8314. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  8315. scope.onLoadStart();
  8316. }
  8317. } else {
  8318. counter_textures += 1;
  8319. scope.onLoadStart();
  8320. }
  8321. }
  8322. total_textures = counter_textures;
  8323. for ( textureID in data.textures ) {
  8324. textureJSON = data.textures[ textureID ];
  8325. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  8326. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  8327. }
  8328. if ( textureJSON.url instanceof Array ) {
  8329. var count = textureJSON.url.length;
  8330. var url_array = [];
  8331. for( var i = 0; i < count; i ++ ) {
  8332. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  8333. }
  8334. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  8335. if ( isCompressed ) {
  8336. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8337. } else {
  8338. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  8339. }
  8340. } else {
  8341. var isCompressed = /\.dds$/i.test( textureJSON.url );
  8342. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  8343. var textureCallback = generateTextureCallback( 1 );
  8344. if ( isCompressed ) {
  8345. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  8346. } else {
  8347. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  8348. }
  8349. if ( THREE[ textureJSON.minFilter ] !== undefined )
  8350. texture.minFilter = THREE[ textureJSON.minFilter ];
  8351. if ( THREE[ textureJSON.magFilter ] !== undefined )
  8352. texture.magFilter = THREE[ textureJSON.magFilter ];
  8353. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  8354. if ( textureJSON.repeat ) {
  8355. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  8356. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  8357. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  8358. }
  8359. if ( textureJSON.offset ) {
  8360. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  8361. }
  8362. // handle wrap after repeat so that default repeat can be overriden
  8363. if ( textureJSON.wrap ) {
  8364. var wrapMap = {
  8365. "repeat": THREE.RepeatWrapping,
  8366. "mirror": THREE.MirroredRepeatWrapping
  8367. }
  8368. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  8369. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  8370. }
  8371. }
  8372. result.textures[ textureID ] = texture;
  8373. }
  8374. // materials
  8375. var matID, matJSON;
  8376. var parID;
  8377. for ( matID in data.materials ) {
  8378. matJSON = data.materials[ matID ];
  8379. for ( parID in matJSON.parameters ) {
  8380. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  8381. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  8382. } else if ( parID === "shading" ) {
  8383. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  8384. } else if ( parID === "side" ) {
  8385. if ( matJSON.parameters[ parID ] == "double" ) {
  8386. matJSON.parameters[ parID ] = THREE.DoubleSide;
  8387. } else if ( matJSON.parameters[ parID ] == "back" ) {
  8388. matJSON.parameters[ parID ] = THREE.BackSide;
  8389. } else {
  8390. matJSON.parameters[ parID ] = THREE.FrontSide;
  8391. }
  8392. } else if ( parID === "blending" ) {
  8393. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  8394. } else if ( parID === "combine" ) {
  8395. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  8396. } else if ( parID === "vertexColors" ) {
  8397. if ( matJSON.parameters[ parID ] == "face" ) {
  8398. matJSON.parameters[ parID ] = THREE.FaceColors;
  8399. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  8400. } else if ( matJSON.parameters[ parID ] ) {
  8401. matJSON.parameters[ parID ] = THREE.VertexColors;
  8402. }
  8403. } else if ( parID === "wrapRGB" ) {
  8404. var v3 = matJSON.parameters[ parID ];
  8405. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  8406. }
  8407. }
  8408. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  8409. matJSON.parameters.transparent = true;
  8410. }
  8411. if ( matJSON.parameters.normalMap ) {
  8412. var shader = THREE.ShaderLib[ "normalmap" ];
  8413. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  8414. var diffuse = matJSON.parameters.color;
  8415. var specular = matJSON.parameters.specular;
  8416. var ambient = matJSON.parameters.ambient;
  8417. var shininess = matJSON.parameters.shininess;
  8418. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  8419. if ( matJSON.parameters.normalScale ) {
  8420. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  8421. }
  8422. if ( matJSON.parameters.map ) {
  8423. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  8424. uniforms[ "enableDiffuse" ].value = true;
  8425. }
  8426. if ( matJSON.parameters.envMap ) {
  8427. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  8428. uniforms[ "enableReflection" ].value = true;
  8429. uniforms[ "reflectivity" ].value = matJSON.parameters.reflectivity;
  8430. }
  8431. if ( matJSON.parameters.lightMap ) {
  8432. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  8433. uniforms[ "enableAO" ].value = true;
  8434. }
  8435. if ( matJSON.parameters.specularMap ) {
  8436. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  8437. uniforms[ "enableSpecular" ].value = true;
  8438. }
  8439. if ( matJSON.parameters.displacementMap ) {
  8440. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  8441. uniforms[ "enableDisplacement" ].value = true;
  8442. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  8443. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  8444. }
  8445. uniforms[ "diffuse" ].value.setHex( diffuse );
  8446. uniforms[ "specular" ].value.setHex( specular );
  8447. uniforms[ "ambient" ].value.setHex( ambient );
  8448. uniforms[ "shininess" ].value = shininess;
  8449. if ( matJSON.parameters.opacity ) {
  8450. uniforms[ "opacity" ].value = matJSON.parameters.opacity;
  8451. }
  8452. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  8453. material = new THREE.ShaderMaterial( parameters );
  8454. } else {
  8455. material = new THREE[ matJSON.type ]( matJSON.parameters );
  8456. }
  8457. material.name = matID;
  8458. result.materials[ matID ] = material;
  8459. }
  8460. // second pass through all materials to initialize MeshFaceMaterials
  8461. // that could be referring to other materials out of order
  8462. for ( matID in data.materials ) {
  8463. matJSON = data.materials[ matID ];
  8464. if ( matJSON.parameters.materials ) {
  8465. var materialArray = [];
  8466. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  8467. var label = matJSON.parameters.materials[ i ];
  8468. materialArray.push( result.materials[ label ] );
  8469. }
  8470. result.materials[ matID ].materials = materialArray;
  8471. }
  8472. }
  8473. // objects ( synchronous init of procedural primitives )
  8474. handle_objects();
  8475. // defaults
  8476. if ( result.cameras && data.defaults.camera ) {
  8477. result.currentCamera = result.cameras[ data.defaults.camera ];
  8478. }
  8479. if ( result.fogs && data.defaults.fog ) {
  8480. result.scene.fog = result.fogs[ data.defaults.fog ];
  8481. }
  8482. // synchronous callback
  8483. scope.callbackSync( result );
  8484. // just in case there are no async elements
  8485. async_callback_gate();
  8486. }
  8487. }
  8488. /**
  8489. * @author mrdoob / http://mrdoob.com/
  8490. */
  8491. THREE.TextureLoader = function ( manager ) {
  8492. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  8493. };
  8494. THREE.TextureLoader.prototype = {
  8495. constructor: THREE.TextureLoader,
  8496. load: function ( url, onLoad, onProgress, onError ) {
  8497. var scope = this;
  8498. var loader = new THREE.ImageLoader( scope.manager );
  8499. loader.setCrossOrigin( this.crossOrigin );
  8500. loader.load( url, function ( image ) {
  8501. var texture = new THREE.Texture( image );
  8502. texture.needsUpdate = true;
  8503. if ( onLoad !== undefined ) {
  8504. onLoad( texture );
  8505. }
  8506. } );
  8507. },
  8508. setCrossOrigin: function ( value ) {
  8509. this.crossOrigin = value;
  8510. }
  8511. };
  8512. /**
  8513. * @author mrdoob / http://mrdoob.com/
  8514. * @author alteredq / http://alteredqualia.com/
  8515. */
  8516. THREE.Material = function () {
  8517. this.id = THREE.MaterialIdCount ++;
  8518. this.uuid = THREE.Math.generateUUID();
  8519. this.name = '';
  8520. this.side = THREE.FrontSide;
  8521. this.opacity = 1;
  8522. this.transparent = false;
  8523. this.blending = THREE.NormalBlending;
  8524. this.blendSrc = THREE.SrcAlphaFactor;
  8525. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  8526. this.blendEquation = THREE.AddEquation;
  8527. this.depthTest = true;
  8528. this.depthWrite = true;
  8529. this.polygonOffset = false;
  8530. this.polygonOffsetFactor = 0;
  8531. this.polygonOffsetUnits = 0;
  8532. this.alphaTest = 0;
  8533. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  8534. this.visible = true;
  8535. this.needsUpdate = true;
  8536. };
  8537. THREE.Material.prototype = {
  8538. constructor: THREE.Material,
  8539. setValues: function ( values ) {
  8540. if ( values === undefined ) return;
  8541. for ( var key in values ) {
  8542. var newValue = values[ key ];
  8543. if ( newValue === undefined ) {
  8544. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  8545. continue;
  8546. }
  8547. if ( key in this ) {
  8548. var currentValue = this[ key ];
  8549. if ( currentValue instanceof THREE.Color ) {
  8550. currentValue.set( newValue );
  8551. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  8552. currentValue.copy( newValue );
  8553. } else if ( key == 'overdraw') {
  8554. // ensure overdraw is backwards-compatable with legacy boolean type
  8555. this[ key ] = Number(newValue);
  8556. } else {
  8557. this[ key ] = newValue;
  8558. }
  8559. }
  8560. }
  8561. },
  8562. clone: function ( material ) {
  8563. if ( material === undefined ) material = new THREE.Material();
  8564. material.name = this.name;
  8565. material.side = this.side;
  8566. material.opacity = this.opacity;
  8567. material.transparent = this.transparent;
  8568. material.blending = this.blending;
  8569. material.blendSrc = this.blendSrc;
  8570. material.blendDst = this.blendDst;
  8571. material.blendEquation = this.blendEquation;
  8572. material.depthTest = this.depthTest;
  8573. material.depthWrite = this.depthWrite;
  8574. material.polygonOffset = this.polygonOffset;
  8575. material.polygonOffsetFactor = this.polygonOffsetFactor;
  8576. material.polygonOffsetUnits = this.polygonOffsetUnits;
  8577. material.alphaTest = this.alphaTest;
  8578. material.overdraw = this.overdraw;
  8579. material.visible = this.visible;
  8580. return material;
  8581. },
  8582. dispose: function () {
  8583. this.dispatchEvent( { type: 'dispose' } );
  8584. }
  8585. };
  8586. THREE.EventDispatcher.prototype.apply( THREE.Material.prototype );
  8587. THREE.MaterialIdCount = 0;
  8588. /**
  8589. * @author mrdoob / http://mrdoob.com/
  8590. * @author alteredq / http://alteredqualia.com/
  8591. *
  8592. * parameters = {
  8593. * color: <hex>,
  8594. * opacity: <float>,
  8595. *
  8596. * blending: THREE.NormalBlending,
  8597. * depthTest: <bool>,
  8598. * depthWrite: <bool>,
  8599. *
  8600. * linewidth: <float>,
  8601. * linecap: "round",
  8602. * linejoin: "round",
  8603. *
  8604. * vertexColors: <bool>
  8605. *
  8606. * fog: <bool>
  8607. * }
  8608. */
  8609. THREE.LineBasicMaterial = function ( parameters ) {
  8610. THREE.Material.call( this );
  8611. this.color = new THREE.Color( 0xffffff );
  8612. this.linewidth = 1;
  8613. this.linecap = 'round';
  8614. this.linejoin = 'round';
  8615. this.vertexColors = false;
  8616. this.fog = true;
  8617. this.setValues( parameters );
  8618. };
  8619. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8620. THREE.LineBasicMaterial.prototype.clone = function () {
  8621. var material = new THREE.LineBasicMaterial();
  8622. THREE.Material.prototype.clone.call( this, material );
  8623. material.color.copy( this.color );
  8624. material.linewidth = this.linewidth;
  8625. material.linecap = this.linecap;
  8626. material.linejoin = this.linejoin;
  8627. material.vertexColors = this.vertexColors;
  8628. material.fog = this.fog;
  8629. return material;
  8630. };
  8631. /**
  8632. * @author alteredq / http://alteredqualia.com/
  8633. *
  8634. * parameters = {
  8635. * color: <hex>,
  8636. * opacity: <float>,
  8637. *
  8638. * blending: THREE.NormalBlending,
  8639. * depthTest: <bool>,
  8640. * depthWrite: <bool>,
  8641. *
  8642. * linewidth: <float>,
  8643. *
  8644. * scale: <float>,
  8645. * dashSize: <float>,
  8646. * gapSize: <float>,
  8647. *
  8648. * vertexColors: <bool>
  8649. *
  8650. * fog: <bool>
  8651. * }
  8652. */
  8653. THREE.LineDashedMaterial = function ( parameters ) {
  8654. THREE.Material.call( this );
  8655. this.color = new THREE.Color( 0xffffff );
  8656. this.linewidth = 1;
  8657. this.scale = 1;
  8658. this.dashSize = 3;
  8659. this.gapSize = 1;
  8660. this.vertexColors = false;
  8661. this.fog = true;
  8662. this.setValues( parameters );
  8663. };
  8664. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  8665. THREE.LineDashedMaterial.prototype.clone = function () {
  8666. var material = new THREE.LineDashedMaterial();
  8667. THREE.Material.prototype.clone.call( this, material );
  8668. material.color.copy( this.color );
  8669. material.linewidth = this.linewidth;
  8670. material.scale = this.scale;
  8671. material.dashSize = this.dashSize;
  8672. material.gapSize = this.gapSize;
  8673. material.vertexColors = this.vertexColors;
  8674. material.fog = this.fog;
  8675. return material;
  8676. };
  8677. /**
  8678. * @author mrdoob / http://mrdoob.com/
  8679. * @author alteredq / http://alteredqualia.com/
  8680. *
  8681. * parameters = {
  8682. * color: <hex>,
  8683. * opacity: <float>,
  8684. * map: new THREE.Texture( <Image> ),
  8685. *
  8686. * lightMap: new THREE.Texture( <Image> ),
  8687. *
  8688. * specularMap: new THREE.Texture( <Image> ),
  8689. *
  8690. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8691. * combine: THREE.Multiply,
  8692. * reflectivity: <float>,
  8693. * refractionRatio: <float>,
  8694. *
  8695. * shading: THREE.SmoothShading,
  8696. * blending: THREE.NormalBlending,
  8697. * depthTest: <bool>,
  8698. * depthWrite: <bool>,
  8699. *
  8700. * wireframe: <boolean>,
  8701. * wireframeLinewidth: <float>,
  8702. *
  8703. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8704. *
  8705. * skinning: <bool>,
  8706. * morphTargets: <bool>,
  8707. *
  8708. * fog: <bool>
  8709. * }
  8710. */
  8711. THREE.MeshBasicMaterial = function ( parameters ) {
  8712. THREE.Material.call( this );
  8713. this.color = new THREE.Color( 0xffffff ); // emissive
  8714. this.map = null;
  8715. this.lightMap = null;
  8716. this.specularMap = null;
  8717. this.envMap = null;
  8718. this.combine = THREE.MultiplyOperation;
  8719. this.reflectivity = 1;
  8720. this.refractionRatio = 0.98;
  8721. this.fog = true;
  8722. this.shading = THREE.SmoothShading;
  8723. this.wireframe = false;
  8724. this.wireframeLinewidth = 1;
  8725. this.wireframeLinecap = 'round';
  8726. this.wireframeLinejoin = 'round';
  8727. this.vertexColors = THREE.NoColors;
  8728. this.skinning = false;
  8729. this.morphTargets = false;
  8730. this.setValues( parameters );
  8731. };
  8732. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  8733. THREE.MeshBasicMaterial.prototype.clone = function () {
  8734. var material = new THREE.MeshBasicMaterial();
  8735. THREE.Material.prototype.clone.call( this, material );
  8736. material.color.copy( this.color );
  8737. material.map = this.map;
  8738. material.lightMap = this.lightMap;
  8739. material.specularMap = this.specularMap;
  8740. material.envMap = this.envMap;
  8741. material.combine = this.combine;
  8742. material.reflectivity = this.reflectivity;
  8743. material.refractionRatio = this.refractionRatio;
  8744. material.fog = this.fog;
  8745. material.shading = this.shading;
  8746. material.wireframe = this.wireframe;
  8747. material.wireframeLinewidth = this.wireframeLinewidth;
  8748. material.wireframeLinecap = this.wireframeLinecap;
  8749. material.wireframeLinejoin = this.wireframeLinejoin;
  8750. material.vertexColors = this.vertexColors;
  8751. material.skinning = this.skinning;
  8752. material.morphTargets = this.morphTargets;
  8753. return material;
  8754. };
  8755. /**
  8756. * @author mrdoob / http://mrdoob.com/
  8757. * @author alteredq / http://alteredqualia.com/
  8758. *
  8759. * parameters = {
  8760. * color: <hex>,
  8761. * ambient: <hex>,
  8762. * emissive: <hex>,
  8763. * opacity: <float>,
  8764. *
  8765. * map: new THREE.Texture( <Image> ),
  8766. *
  8767. * lightMap: new THREE.Texture( <Image> ),
  8768. *
  8769. * specularMap: new THREE.Texture( <Image> ),
  8770. *
  8771. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8772. * combine: THREE.Multiply,
  8773. * reflectivity: <float>,
  8774. * refractionRatio: <float>,
  8775. *
  8776. * shading: THREE.SmoothShading,
  8777. * blending: THREE.NormalBlending,
  8778. * depthTest: <bool>,
  8779. * depthWrite: <bool>,
  8780. *
  8781. * wireframe: <boolean>,
  8782. * wireframeLinewidth: <float>,
  8783. *
  8784. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8785. *
  8786. * skinning: <bool>,
  8787. * morphTargets: <bool>,
  8788. * morphNormals: <bool>,
  8789. *
  8790. * fog: <bool>
  8791. * }
  8792. */
  8793. THREE.MeshLambertMaterial = function ( parameters ) {
  8794. THREE.Material.call( this );
  8795. this.color = new THREE.Color( 0xffffff ); // diffuse
  8796. this.ambient = new THREE.Color( 0xffffff );
  8797. this.emissive = new THREE.Color( 0x000000 );
  8798. this.wrapAround = false;
  8799. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8800. this.map = null;
  8801. this.lightMap = null;
  8802. this.specularMap = null;
  8803. this.envMap = null;
  8804. this.combine = THREE.MultiplyOperation;
  8805. this.reflectivity = 1;
  8806. this.refractionRatio = 0.98;
  8807. this.fog = true;
  8808. this.shading = THREE.SmoothShading;
  8809. this.wireframe = false;
  8810. this.wireframeLinewidth = 1;
  8811. this.wireframeLinecap = 'round';
  8812. this.wireframeLinejoin = 'round';
  8813. this.vertexColors = THREE.NoColors;
  8814. this.skinning = false;
  8815. this.morphTargets = false;
  8816. this.morphNormals = false;
  8817. this.setValues( parameters );
  8818. };
  8819. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  8820. THREE.MeshLambertMaterial.prototype.clone = function () {
  8821. var material = new THREE.MeshLambertMaterial();
  8822. THREE.Material.prototype.clone.call( this, material );
  8823. material.color.copy( this.color );
  8824. material.ambient.copy( this.ambient );
  8825. material.emissive.copy( this.emissive );
  8826. material.wrapAround = this.wrapAround;
  8827. material.wrapRGB.copy( this.wrapRGB );
  8828. material.map = this.map;
  8829. material.lightMap = this.lightMap;
  8830. material.specularMap = this.specularMap;
  8831. material.envMap = this.envMap;
  8832. material.combine = this.combine;
  8833. material.reflectivity = this.reflectivity;
  8834. material.refractionRatio = this.refractionRatio;
  8835. material.fog = this.fog;
  8836. material.shading = this.shading;
  8837. material.wireframe = this.wireframe;
  8838. material.wireframeLinewidth = this.wireframeLinewidth;
  8839. material.wireframeLinecap = this.wireframeLinecap;
  8840. material.wireframeLinejoin = this.wireframeLinejoin;
  8841. material.vertexColors = this.vertexColors;
  8842. material.skinning = this.skinning;
  8843. material.morphTargets = this.morphTargets;
  8844. material.morphNormals = this.morphNormals;
  8845. return material;
  8846. };
  8847. /**
  8848. * @author mrdoob / http://mrdoob.com/
  8849. * @author alteredq / http://alteredqualia.com/
  8850. *
  8851. * parameters = {
  8852. * color: <hex>,
  8853. * ambient: <hex>,
  8854. * emissive: <hex>,
  8855. * specular: <hex>,
  8856. * shininess: <float>,
  8857. * opacity: <float>,
  8858. *
  8859. * map: new THREE.Texture( <Image> ),
  8860. *
  8861. * lightMap: new THREE.Texture( <Image> ),
  8862. *
  8863. * bumpMap: new THREE.Texture( <Image> ),
  8864. * bumpScale: <float>,
  8865. *
  8866. * normalMap: new THREE.Texture( <Image> ),
  8867. * normalScale: <Vector2>,
  8868. *
  8869. * specularMap: new THREE.Texture( <Image> ),
  8870. *
  8871. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  8872. * combine: THREE.Multiply,
  8873. * reflectivity: <float>,
  8874. * refractionRatio: <float>,
  8875. *
  8876. * shading: THREE.SmoothShading,
  8877. * blending: THREE.NormalBlending,
  8878. * depthTest: <bool>,
  8879. * depthWrite: <bool>,
  8880. *
  8881. * wireframe: <boolean>,
  8882. * wireframeLinewidth: <float>,
  8883. *
  8884. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  8885. *
  8886. * skinning: <bool>,
  8887. * morphTargets: <bool>,
  8888. * morphNormals: <bool>,
  8889. *
  8890. * fog: <bool>
  8891. * }
  8892. */
  8893. THREE.MeshPhongMaterial = function ( parameters ) {
  8894. THREE.Material.call( this );
  8895. this.color = new THREE.Color( 0xffffff ); // diffuse
  8896. this.ambient = new THREE.Color( 0xffffff );
  8897. this.emissive = new THREE.Color( 0x000000 );
  8898. this.specular = new THREE.Color( 0x111111 );
  8899. this.shininess = 30;
  8900. this.metal = false;
  8901. this.wrapAround = false;
  8902. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  8903. this.map = null;
  8904. this.lightMap = null;
  8905. this.bumpMap = null;
  8906. this.bumpScale = 1;
  8907. this.normalMap = null;
  8908. this.normalScale = new THREE.Vector2( 1, 1 );
  8909. this.specularMap = null;
  8910. this.envMap = null;
  8911. this.combine = THREE.MultiplyOperation;
  8912. this.reflectivity = 1;
  8913. this.refractionRatio = 0.98;
  8914. this.fog = true;
  8915. this.shading = THREE.SmoothShading;
  8916. this.wireframe = false;
  8917. this.wireframeLinewidth = 1;
  8918. this.wireframeLinecap = 'round';
  8919. this.wireframeLinejoin = 'round';
  8920. this.vertexColors = THREE.NoColors;
  8921. this.skinning = false;
  8922. this.morphTargets = false;
  8923. this.morphNormals = false;
  8924. this.setValues( parameters );
  8925. };
  8926. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  8927. THREE.MeshPhongMaterial.prototype.clone = function () {
  8928. var material = new THREE.MeshPhongMaterial();
  8929. THREE.Material.prototype.clone.call( this, material );
  8930. material.color.copy( this.color );
  8931. material.ambient.copy( this.ambient );
  8932. material.emissive.copy( this.emissive );
  8933. material.specular.copy( this.specular );
  8934. material.shininess = this.shininess;
  8935. material.metal = this.metal;
  8936. material.wrapAround = this.wrapAround;
  8937. material.wrapRGB.copy( this.wrapRGB );
  8938. material.map = this.map;
  8939. material.lightMap = this.lightMap;
  8940. material.bumpMap = this.bumpMap;
  8941. material.bumpScale = this.bumpScale;
  8942. material.normalMap = this.normalMap;
  8943. material.normalScale.copy( this.normalScale );
  8944. material.specularMap = this.specularMap;
  8945. material.envMap = this.envMap;
  8946. material.combine = this.combine;
  8947. material.reflectivity = this.reflectivity;
  8948. material.refractionRatio = this.refractionRatio;
  8949. material.fog = this.fog;
  8950. material.shading = this.shading;
  8951. material.wireframe = this.wireframe;
  8952. material.wireframeLinewidth = this.wireframeLinewidth;
  8953. material.wireframeLinecap = this.wireframeLinecap;
  8954. material.wireframeLinejoin = this.wireframeLinejoin;
  8955. material.vertexColors = this.vertexColors;
  8956. material.skinning = this.skinning;
  8957. material.morphTargets = this.morphTargets;
  8958. material.morphNormals = this.morphNormals;
  8959. return material;
  8960. };
  8961. /**
  8962. * @author mrdoob / http://mrdoob.com/
  8963. * @author alteredq / http://alteredqualia.com/
  8964. *
  8965. * parameters = {
  8966. * opacity: <float>,
  8967. *
  8968. * blending: THREE.NormalBlending,
  8969. * depthTest: <bool>,
  8970. * depthWrite: <bool>,
  8971. *
  8972. * wireframe: <boolean>,
  8973. * wireframeLinewidth: <float>
  8974. * }
  8975. */
  8976. THREE.MeshDepthMaterial = function ( parameters ) {
  8977. THREE.Material.call( this );
  8978. this.wireframe = false;
  8979. this.wireframeLinewidth = 1;
  8980. this.setValues( parameters );
  8981. };
  8982. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  8983. THREE.MeshDepthMaterial.prototype.clone = function () {
  8984. var material = new THREE.MeshDepthMaterial();
  8985. THREE.Material.prototype.clone.call( this, material );
  8986. material.wireframe = this.wireframe;
  8987. material.wireframeLinewidth = this.wireframeLinewidth;
  8988. return material;
  8989. };
  8990. /**
  8991. * @author mrdoob / http://mrdoob.com/
  8992. *
  8993. * parameters = {
  8994. * opacity: <float>,
  8995. *
  8996. * shading: THREE.FlatShading,
  8997. * blending: THREE.NormalBlending,
  8998. * depthTest: <bool>,
  8999. * depthWrite: <bool>,
  9000. *
  9001. * wireframe: <boolean>,
  9002. * wireframeLinewidth: <float>
  9003. * }
  9004. */
  9005. THREE.MeshNormalMaterial = function ( parameters ) {
  9006. THREE.Material.call( this, parameters );
  9007. this.shading = THREE.FlatShading;
  9008. this.wireframe = false;
  9009. this.wireframeLinewidth = 1;
  9010. this.morphTargets = false;
  9011. this.setValues( parameters );
  9012. };
  9013. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  9014. THREE.MeshNormalMaterial.prototype.clone = function () {
  9015. var material = new THREE.MeshNormalMaterial();
  9016. THREE.Material.prototype.clone.call( this, material );
  9017. material.shading = this.shading;
  9018. material.wireframe = this.wireframe;
  9019. material.wireframeLinewidth = this.wireframeLinewidth;
  9020. return material;
  9021. };
  9022. /**
  9023. * @author mrdoob / http://mrdoob.com/
  9024. */
  9025. THREE.MeshFaceMaterial = function ( materials ) {
  9026. this.materials = materials instanceof Array ? materials : [];
  9027. };
  9028. THREE.MeshFaceMaterial.prototype.clone = function () {
  9029. var material = new THREE.MeshFaceMaterial();
  9030. for ( var i = 0; i < this.materials.length; i ++ ) {
  9031. material.materials.push( this.materials[ i ].clone() );
  9032. }
  9033. return material;
  9034. };
  9035. /**
  9036. * @author mrdoob / http://mrdoob.com/
  9037. * @author alteredq / http://alteredqualia.com/
  9038. *
  9039. * parameters = {
  9040. * color: <hex>,
  9041. * opacity: <float>,
  9042. * map: new THREE.Texture( <Image> ),
  9043. *
  9044. * size: <float>,
  9045. *
  9046. * blending: THREE.NormalBlending,
  9047. * depthTest: <bool>,
  9048. * depthWrite: <bool>,
  9049. *
  9050. * vertexColors: <bool>,
  9051. *
  9052. * fog: <bool>
  9053. * }
  9054. */
  9055. THREE.ParticleSystemMaterial = function ( parameters ) {
  9056. THREE.Material.call( this );
  9057. this.color = new THREE.Color( 0xffffff );
  9058. this.map = null;
  9059. this.size = 1;
  9060. this.sizeAttenuation = true;
  9061. this.vertexColors = false;
  9062. this.fog = true;
  9063. this.setValues( parameters );
  9064. };
  9065. THREE.ParticleSystemMaterial.prototype = Object.create( THREE.Material.prototype );
  9066. THREE.ParticleSystemMaterial.prototype.clone = function () {
  9067. var material = new THREE.ParticleSystemMaterial();
  9068. THREE.Material.prototype.clone.call( this, material );
  9069. material.color.copy( this.color );
  9070. material.map = this.map;
  9071. material.size = this.size;
  9072. material.sizeAttenuation = this.sizeAttenuation;
  9073. material.vertexColors = this.vertexColors;
  9074. material.fog = this.fog;
  9075. return material;
  9076. };
  9077. // backwards compatibility
  9078. THREE.ParticleBasicMaterial = THREE.ParticleSystemMaterial;
  9079. /**
  9080. * @author alteredq / http://alteredqualia.com/
  9081. *
  9082. * parameters = {
  9083. * fragmentShader: <string>,
  9084. * vertexShader: <string>,
  9085. *
  9086. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  9087. *
  9088. * defines: { "label" : "value" },
  9089. *
  9090. * shading: THREE.SmoothShading,
  9091. * blending: THREE.NormalBlending,
  9092. * depthTest: <bool>,
  9093. * depthWrite: <bool>,
  9094. *
  9095. * wireframe: <boolean>,
  9096. * wireframeLinewidth: <float>,
  9097. *
  9098. * lights: <bool>,
  9099. *
  9100. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  9101. *
  9102. * skinning: <bool>,
  9103. * morphTargets: <bool>,
  9104. * morphNormals: <bool>,
  9105. *
  9106. * fog: <bool>
  9107. * }
  9108. */
  9109. THREE.ShaderMaterial = function ( parameters ) {
  9110. THREE.Material.call( this );
  9111. this.fragmentShader = "void main() {}";
  9112. this.vertexShader = "void main() {}";
  9113. this.uniforms = {};
  9114. this.defines = {};
  9115. this.attributes = null;
  9116. this.shading = THREE.SmoothShading;
  9117. this.linewidth = 1;
  9118. this.wireframe = false;
  9119. this.wireframeLinewidth = 1;
  9120. this.fog = false; // set to use scene fog
  9121. this.lights = false; // set to use scene lights
  9122. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  9123. this.skinning = false; // set to use skinning attribute streams
  9124. this.morphTargets = false; // set to use morph targets
  9125. this.morphNormals = false; // set to use morph normals
  9126. // When rendered geometry doesn't include these attributes but the material does,
  9127. // use these default values in WebGL. This avoids errors when buffer data is missing.
  9128. this.defaultAttributeValues = {
  9129. "color" : [ 1, 1, 1 ],
  9130. "uv" : [ 0, 0 ],
  9131. "uv2" : [ 0, 0 ]
  9132. };
  9133. this.index0AttributeName = undefined;
  9134. this.setValues( parameters );
  9135. };
  9136. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  9137. THREE.ShaderMaterial.prototype.clone = function () {
  9138. var material = new THREE.ShaderMaterial();
  9139. THREE.Material.prototype.clone.call( this, material );
  9140. material.fragmentShader = this.fragmentShader;
  9141. material.vertexShader = this.vertexShader;
  9142. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  9143. material.attributes = this.attributes;
  9144. material.defines = this.defines;
  9145. material.shading = this.shading;
  9146. material.wireframe = this.wireframe;
  9147. material.wireframeLinewidth = this.wireframeLinewidth;
  9148. material.fog = this.fog;
  9149. material.lights = this.lights;
  9150. material.vertexColors = this.vertexColors;
  9151. material.skinning = this.skinning;
  9152. material.morphTargets = this.morphTargets;
  9153. material.morphNormals = this.morphNormals;
  9154. return material;
  9155. };
  9156. /**
  9157. * @author mrdoob / http://mrdoob.com/
  9158. */
  9159. THREE.RawShaderMaterial = function ( parameters ) {
  9160. THREE.ShaderMaterial.call( this, parameters );
  9161. };
  9162. THREE.RawShaderMaterial.prototype = Object.create( THREE.ShaderMaterial.prototype );
  9163. THREE.RawShaderMaterial.prototype.clone = function () {
  9164. var material = new THREE.RawShaderMaterial();
  9165. THREE.ShaderMaterial.prototype.clone.call( this, material );
  9166. return material;
  9167. };
  9168. /**
  9169. * @author alteredq / http://alteredqualia.com/
  9170. *
  9171. * parameters = {
  9172. * color: <hex>,
  9173. * opacity: <float>,
  9174. * map: new THREE.Texture( <Image> ),
  9175. *
  9176. * blending: THREE.NormalBlending,
  9177. * depthTest: <bool>,
  9178. * depthWrite: <bool>,
  9179. *
  9180. * uvOffset: new THREE.Vector2(),
  9181. * uvScale: new THREE.Vector2(),
  9182. *
  9183. * fog: <bool>
  9184. * }
  9185. */
  9186. THREE.SpriteMaterial = function ( parameters ) {
  9187. THREE.Material.call( this );
  9188. // defaults
  9189. this.color = new THREE.Color( 0xffffff );
  9190. this.map = null;
  9191. this.rotation = 0;
  9192. this.fog = false;
  9193. // set parameters
  9194. this.setValues( parameters );
  9195. };
  9196. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  9197. THREE.SpriteMaterial.prototype.clone = function () {
  9198. var material = new THREE.SpriteMaterial();
  9199. THREE.Material.prototype.clone.call( this, material );
  9200. material.color.copy( this.color );
  9201. material.map = this.map;
  9202. material.rotation = this.rotation;
  9203. material.fog = this.fog;
  9204. return material;
  9205. };
  9206. /**
  9207. * @author mrdoob / http://mrdoob.com/
  9208. *
  9209. * parameters = {
  9210. * color: <hex>,
  9211. * program: <function>,
  9212. * opacity: <float>,
  9213. * blending: THREE.NormalBlending
  9214. * }
  9215. */
  9216. THREE.SpriteCanvasMaterial = function ( parameters ) {
  9217. THREE.Material.call( this );
  9218. this.color = new THREE.Color( 0xffffff );
  9219. this.program = function ( context, color ) {};
  9220. this.setValues( parameters );
  9221. };
  9222. THREE.SpriteCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  9223. THREE.SpriteCanvasMaterial.prototype.clone = function () {
  9224. var material = new THREE.SpriteCanvasMaterial();
  9225. THREE.Material.prototype.clone.call( this, material );
  9226. material.color.copy( this.color );
  9227. material.program = this.program;
  9228. return material;
  9229. };
  9230. // backwards compatibility
  9231. THREE.ParticleCanvasMaterial = THREE.SpriteCanvasMaterial;
  9232. /**
  9233. * @author mrdoob / http://mrdoob.com/
  9234. * @author alteredq / http://alteredqualia.com/
  9235. * @author szimek / https://github.com/szimek/
  9236. */
  9237. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  9238. this.id = THREE.TextureIdCount ++;
  9239. this.uuid = THREE.Math.generateUUID();
  9240. this.name = '';
  9241. this.image = image;
  9242. this.mipmaps = [];
  9243. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  9244. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  9245. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  9246. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  9247. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  9248. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  9249. this.format = format !== undefined ? format : THREE.RGBAFormat;
  9250. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  9251. this.offset = new THREE.Vector2( 0, 0 );
  9252. this.repeat = new THREE.Vector2( 1, 1 );
  9253. this.generateMipmaps = true;
  9254. this.premultiplyAlpha = false;
  9255. this.flipY = true;
  9256. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  9257. this._needsUpdate = false;
  9258. this.onUpdate = null;
  9259. };
  9260. THREE.Texture.prototype = {
  9261. constructor: THREE.Texture,
  9262. get needsUpdate () {
  9263. return this._needsUpdate;
  9264. },
  9265. set needsUpdate ( value ) {
  9266. if ( value === true ) this.update();
  9267. this._needsUpdate = value;
  9268. },
  9269. clone: function ( texture ) {
  9270. if ( texture === undefined ) texture = new THREE.Texture();
  9271. texture.image = this.image;
  9272. texture.mipmaps = this.mipmaps.slice(0);
  9273. texture.mapping = this.mapping;
  9274. texture.wrapS = this.wrapS;
  9275. texture.wrapT = this.wrapT;
  9276. texture.magFilter = this.magFilter;
  9277. texture.minFilter = this.minFilter;
  9278. texture.anisotropy = this.anisotropy;
  9279. texture.format = this.format;
  9280. texture.type = this.type;
  9281. texture.offset.copy( this.offset );
  9282. texture.repeat.copy( this.repeat );
  9283. texture.generateMipmaps = this.generateMipmaps;
  9284. texture.premultiplyAlpha = this.premultiplyAlpha;
  9285. texture.flipY = this.flipY;
  9286. texture.unpackAlignment = this.unpackAlignment;
  9287. return texture;
  9288. },
  9289. update: function () {
  9290. this.dispatchEvent( { type: 'update' } );
  9291. },
  9292. dispose: function () {
  9293. this.dispatchEvent( { type: 'dispose' } );
  9294. }
  9295. };
  9296. THREE.EventDispatcher.prototype.apply( THREE.Texture.prototype );
  9297. THREE.TextureIdCount = 0;
  9298. /**
  9299. * @author alteredq / http://alteredqualia.com/
  9300. */
  9301. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9302. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9303. this.image = { width: width, height: height };
  9304. this.mipmaps = mipmaps;
  9305. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  9306. };
  9307. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  9308. THREE.CompressedTexture.prototype.clone = function () {
  9309. var texture = new THREE.CompressedTexture();
  9310. THREE.Texture.prototype.clone.call( this, texture );
  9311. return texture;
  9312. };
  9313. /**
  9314. * @author alteredq / http://alteredqualia.com/
  9315. */
  9316. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  9317. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  9318. this.image = { data: data, width: width, height: height };
  9319. };
  9320. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  9321. THREE.DataTexture.prototype.clone = function () {
  9322. var texture = new THREE.DataTexture();
  9323. THREE.Texture.prototype.clone.call( this, texture );
  9324. return texture;
  9325. };
  9326. /**
  9327. * @author alteredq / http://alteredqualia.com/
  9328. */
  9329. THREE.ParticleSystem = function ( geometry, material ) {
  9330. THREE.Object3D.call( this );
  9331. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9332. this.material = material !== undefined ? material : new THREE.ParticleSystemMaterial( { color: Math.random() * 0xffffff } );
  9333. this.sortParticles = false;
  9334. this.frustumCulled = false;
  9335. };
  9336. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  9337. THREE.ParticleSystem.prototype.clone = function ( object ) {
  9338. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  9339. object.sortParticles = this.sortParticles;
  9340. THREE.Object3D.prototype.clone.call( this, object );
  9341. return object;
  9342. };
  9343. /**
  9344. * @author mrdoob / http://mrdoob.com/
  9345. */
  9346. THREE.Line = function ( geometry, material, type ) {
  9347. THREE.Object3D.call( this );
  9348. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9349. this.material = material !== undefined ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  9350. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  9351. };
  9352. THREE.LineStrip = 0;
  9353. THREE.LinePieces = 1;
  9354. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  9355. THREE.Line.prototype.clone = function ( object ) {
  9356. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  9357. THREE.Object3D.prototype.clone.call( this, object );
  9358. return object;
  9359. };
  9360. /**
  9361. * @author mrdoob / http://mrdoob.com/
  9362. * @author alteredq / http://alteredqualia.com/
  9363. * @author mikael emtinger / http://gomo.se/
  9364. * @author jonobr1 / http://jonobr1.com/
  9365. */
  9366. THREE.Mesh = function ( geometry, material ) {
  9367. THREE.Object3D.call( this );
  9368. this.geometry = geometry !== undefined ? geometry : new THREE.Geometry();
  9369. this.material = material !== undefined ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff } );
  9370. this.updateMorphTargets();
  9371. };
  9372. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  9373. THREE.Mesh.prototype.updateMorphTargets = function () {
  9374. if ( this.geometry.morphTargets !== undefined && this.geometry.morphTargets.length > 0 ) {
  9375. this.morphTargetBase = -1;
  9376. this.morphTargetForcedOrder = [];
  9377. this.morphTargetInfluences = [];
  9378. this.morphTargetDictionary = {};
  9379. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  9380. this.morphTargetInfluences.push( 0 );
  9381. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  9382. }
  9383. }
  9384. };
  9385. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  9386. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  9387. return this.morphTargetDictionary[ name ];
  9388. }
  9389. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  9390. return 0;
  9391. };
  9392. THREE.Mesh.prototype.clone = function ( object, recursive ) {
  9393. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  9394. THREE.Object3D.prototype.clone.call( this, object, recursive );
  9395. return object;
  9396. };
  9397. /**
  9398. * @author mikael emtinger / http://gomo.se/
  9399. * @author alteredq / http://alteredqualia.com/
  9400. */
  9401. THREE.Bone = function( belongsToSkin ) {
  9402. THREE.Object3D.call( this );
  9403. this.skin = belongsToSkin;
  9404. this.skinMatrix = new THREE.Matrix4();
  9405. };
  9406. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  9407. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  9408. // update local
  9409. if ( this.matrixAutoUpdate ) {
  9410. forceUpdate |= this.updateMatrix();
  9411. }
  9412. // update skin matrix
  9413. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  9414. if ( parentSkinMatrix ) {
  9415. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  9416. } else {
  9417. this.skinMatrix.copy( this.matrix );
  9418. }
  9419. this.matrixWorldNeedsUpdate = false;
  9420. forceUpdate = true;
  9421. }
  9422. // update children
  9423. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9424. this.children[ i ].update( this.skinMatrix, forceUpdate );
  9425. }
  9426. };
  9427. /**
  9428. * @author mikael emtinger / http://gomo.se/
  9429. * @author alteredq / http://alteredqualia.com/
  9430. */
  9431. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  9432. THREE.Mesh.call( this, geometry, material );
  9433. //
  9434. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  9435. // init bones
  9436. this.identityMatrix = new THREE.Matrix4();
  9437. this.bones = [];
  9438. this.boneMatrices = [];
  9439. var b, bone, gbone, p, q, s;
  9440. if ( this.geometry && this.geometry.bones !== undefined ) {
  9441. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  9442. gbone = this.geometry.bones[ b ];
  9443. p = gbone.pos;
  9444. q = gbone.rotq;
  9445. s = gbone.scl;
  9446. bone = this.addBone();
  9447. bone.name = gbone.name;
  9448. bone.position.set( p[0], p[1], p[2] );
  9449. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  9450. if ( s !== undefined ) {
  9451. bone.scale.set( s[0], s[1], s[2] );
  9452. } else {
  9453. bone.scale.set( 1, 1, 1 );
  9454. }
  9455. }
  9456. for ( b = 0; b < this.bones.length; b ++ ) {
  9457. gbone = this.geometry.bones[ b ];
  9458. bone = this.bones[ b ];
  9459. if ( gbone.parent === -1 ) {
  9460. this.add( bone );
  9461. } else {
  9462. this.bones[ gbone.parent ].add( bone );
  9463. }
  9464. }
  9465. //
  9466. var nBones = this.bones.length;
  9467. if ( this.useVertexTexture ) {
  9468. // layout (1 matrix = 4 pixels)
  9469. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  9470. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  9471. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  9472. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  9473. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  9474. var size;
  9475. if ( nBones > 256 )
  9476. size = 64;
  9477. else if ( nBones > 64 )
  9478. size = 32;
  9479. else if ( nBones > 16 )
  9480. size = 16;
  9481. else
  9482. size = 8;
  9483. this.boneTextureWidth = size;
  9484. this.boneTextureHeight = size;
  9485. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  9486. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  9487. this.boneTexture.minFilter = THREE.NearestFilter;
  9488. this.boneTexture.magFilter = THREE.NearestFilter;
  9489. this.boneTexture.generateMipmaps = false;
  9490. this.boneTexture.flipY = false;
  9491. } else {
  9492. this.boneMatrices = new Float32Array( 16 * nBones );
  9493. }
  9494. this.pose();
  9495. }
  9496. };
  9497. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  9498. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  9499. if ( bone === undefined ) {
  9500. bone = new THREE.Bone( this );
  9501. }
  9502. this.bones.push( bone );
  9503. return bone;
  9504. };
  9505. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  9506. var offsetMatrix = new THREE.Matrix4();
  9507. return function ( force ) {
  9508. this.matrixAutoUpdate && this.updateMatrix();
  9509. // update matrixWorld
  9510. if ( this.matrixWorldNeedsUpdate || force ) {
  9511. if ( this.parent ) {
  9512. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  9513. } else {
  9514. this.matrixWorld.copy( this.matrix );
  9515. }
  9516. this.matrixWorldNeedsUpdate = false;
  9517. force = true;
  9518. }
  9519. // update children
  9520. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  9521. var child = this.children[ i ];
  9522. if ( child instanceof THREE.Bone ) {
  9523. child.update( this.identityMatrix, false );
  9524. } else {
  9525. child.updateMatrixWorld( true );
  9526. }
  9527. }
  9528. // make a snapshot of the bones' rest position
  9529. if ( this.boneInverses == undefined ) {
  9530. this.boneInverses = [];
  9531. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9532. var inverse = new THREE.Matrix4();
  9533. inverse.getInverse( this.bones[ b ].skinMatrix );
  9534. this.boneInverses.push( inverse );
  9535. }
  9536. }
  9537. // flatten bone matrices to array
  9538. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  9539. // compute the offset between the current and the original transform;
  9540. // TODO: we could get rid of this multiplication step if the skinMatrix
  9541. // was already representing the offset; however, this requires some
  9542. // major changes to the animation system
  9543. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  9544. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  9545. }
  9546. if ( this.useVertexTexture ) {
  9547. this.boneTexture.needsUpdate = true;
  9548. }
  9549. };
  9550. }();
  9551. THREE.SkinnedMesh.prototype.pose = function () {
  9552. this.updateMatrixWorld( true );
  9553. this.normalizeSkinWeights();
  9554. };
  9555. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  9556. if ( this.geometry instanceof THREE.Geometry ) {
  9557. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  9558. var sw = this.geometry.skinWeights[ i ];
  9559. var scale = 1.0 / sw.lengthManhattan();
  9560. if ( scale !== Infinity ) {
  9561. sw.multiplyScalar( scale );
  9562. } else {
  9563. sw.set( 1 ); // this will be normalized by the shader anyway
  9564. }
  9565. }
  9566. } else {
  9567. // skinning weights assumed to be normalized for THREE.BufferGeometry
  9568. }
  9569. };
  9570. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  9571. if ( object === undefined ) {
  9572. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  9573. }
  9574. THREE.Mesh.prototype.clone.call( this, object );
  9575. return object;
  9576. };
  9577. /**
  9578. * @author alteredq / http://alteredqualia.com/
  9579. */
  9580. THREE.MorphAnimMesh = function ( geometry, material ) {
  9581. THREE.Mesh.call( this, geometry, material );
  9582. // API
  9583. this.duration = 1000; // milliseconds
  9584. this.mirroredLoop = false;
  9585. this.time = 0;
  9586. // internals
  9587. this.lastKeyframe = 0;
  9588. this.currentKeyframe = 0;
  9589. this.direction = 1;
  9590. this.directionBackwards = false;
  9591. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  9592. };
  9593. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  9594. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  9595. this.startKeyframe = start;
  9596. this.endKeyframe = end;
  9597. this.length = this.endKeyframe - this.startKeyframe + 1;
  9598. };
  9599. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  9600. this.direction = 1;
  9601. this.directionBackwards = false;
  9602. };
  9603. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  9604. this.direction = -1;
  9605. this.directionBackwards = true;
  9606. };
  9607. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  9608. var geometry = this.geometry;
  9609. if ( ! geometry.animations ) geometry.animations = {};
  9610. var firstAnimation, animations = geometry.animations;
  9611. var pattern = /([a-z]+)(\d+)/;
  9612. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  9613. var morph = geometry.morphTargets[ i ];
  9614. var parts = morph.name.match( pattern );
  9615. if ( parts && parts.length > 1 ) {
  9616. var label = parts[ 1 ];
  9617. var num = parts[ 2 ];
  9618. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  9619. var animation = animations[ label ];
  9620. if ( i < animation.start ) animation.start = i;
  9621. if ( i > animation.end ) animation.end = i;
  9622. if ( ! firstAnimation ) firstAnimation = label;
  9623. }
  9624. }
  9625. geometry.firstAnimation = firstAnimation;
  9626. };
  9627. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  9628. if ( ! this.geometry.animations ) this.geometry.animations = {};
  9629. this.geometry.animations[ label ] = { start: start, end: end };
  9630. };
  9631. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  9632. var animation = this.geometry.animations[ label ];
  9633. if ( animation ) {
  9634. this.setFrameRange( animation.start, animation.end );
  9635. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  9636. this.time = 0;
  9637. } else {
  9638. console.warn( "animation[" + label + "] undefined" );
  9639. }
  9640. };
  9641. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  9642. var frameTime = this.duration / this.length;
  9643. this.time += this.direction * delta;
  9644. if ( this.mirroredLoop ) {
  9645. if ( this.time > this.duration || this.time < 0 ) {
  9646. this.direction *= -1;
  9647. if ( this.time > this.duration ) {
  9648. this.time = this.duration;
  9649. this.directionBackwards = true;
  9650. }
  9651. if ( this.time < 0 ) {
  9652. this.time = 0;
  9653. this.directionBackwards = false;
  9654. }
  9655. }
  9656. } else {
  9657. this.time = this.time % this.duration;
  9658. if ( this.time < 0 ) this.time += this.duration;
  9659. }
  9660. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  9661. if ( keyframe !== this.currentKeyframe ) {
  9662. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  9663. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  9664. this.morphTargetInfluences[ keyframe ] = 0;
  9665. this.lastKeyframe = this.currentKeyframe;
  9666. this.currentKeyframe = keyframe;
  9667. }
  9668. var mix = ( this.time % frameTime ) / frameTime;
  9669. if ( this.directionBackwards ) {
  9670. mix = 1 - mix;
  9671. }
  9672. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  9673. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  9674. };
  9675. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  9676. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  9677. object.duration = this.duration;
  9678. object.mirroredLoop = this.mirroredLoop;
  9679. object.time = this.time;
  9680. object.lastKeyframe = this.lastKeyframe;
  9681. object.currentKeyframe = this.currentKeyframe;
  9682. object.direction = this.direction;
  9683. object.directionBackwards = this.directionBackwards;
  9684. THREE.Mesh.prototype.clone.call( this, object );
  9685. return object;
  9686. };
  9687. /**
  9688. * @author mikael emtinger / http://gomo.se/
  9689. * @author alteredq / http://alteredqualia.com/
  9690. * @author mrdoob / http://mrdoob.com/
  9691. */
  9692. THREE.LOD = function () {
  9693. THREE.Object3D.call( this );
  9694. this.objects = [];
  9695. };
  9696. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  9697. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  9698. if ( distance === undefined ) distance = 0;
  9699. distance = Math.abs( distance );
  9700. for ( var l = 0; l < this.objects.length; l ++ ) {
  9701. if ( distance < this.objects[ l ].distance ) {
  9702. break;
  9703. }
  9704. }
  9705. this.objects.splice( l, 0, { distance: distance, object: object } );
  9706. this.add( object );
  9707. };
  9708. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  9709. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9710. if ( distance < this.objects[ i ].distance ) {
  9711. break;
  9712. }
  9713. }
  9714. return this.objects[ i - 1 ].object;
  9715. };
  9716. THREE.LOD.prototype.update = function () {
  9717. var v1 = new THREE.Vector3();
  9718. var v2 = new THREE.Vector3();
  9719. return function ( camera ) {
  9720. if ( this.objects.length > 1 ) {
  9721. v1.setFromMatrixPosition( camera.matrixWorld );
  9722. v2.setFromMatrixPosition( this.matrixWorld );
  9723. var distance = v1.distanceTo( v2 );
  9724. this.objects[ 0 ].object.visible = true;
  9725. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  9726. if ( distance >= this.objects[ i ].distance ) {
  9727. this.objects[ i - 1 ].object.visible = false;
  9728. this.objects[ i ].object.visible = true;
  9729. } else {
  9730. break;
  9731. }
  9732. }
  9733. for( ; i < l; i ++ ) {
  9734. this.objects[ i ].object.visible = false;
  9735. }
  9736. }
  9737. };
  9738. }();
  9739. THREE.LOD.prototype.clone = function ( object ) {
  9740. if ( object === undefined ) object = new THREE.LOD();
  9741. THREE.Object3D.prototype.clone.call( this, object );
  9742. for ( var i = 0, l = this.objects.length; i < l; i ++ ) {
  9743. var x = this.objects[i].object.clone();
  9744. x.visible = i === 0;
  9745. object.addLevel( x, this.objects[i].distance );
  9746. }
  9747. return object;
  9748. };
  9749. /**
  9750. * @author mikael emtinger / http://gomo.se/
  9751. * @author alteredq / http://alteredqualia.com/
  9752. */
  9753. THREE.Sprite = ( function () {
  9754. var vertices = new THREE.Float32Attribute( 3, 3 );
  9755. vertices.set( [ - 0.5, - 0.5, 0, 0.5, - 0.5, 0, 0.5, 0.5, 0 ] );
  9756. var geometry = new THREE.BufferGeometry();
  9757. geometry.addAttribute( 'position', vertices );
  9758. return function ( material ) {
  9759. THREE.Object3D.call( this );
  9760. this.geometry = geometry;
  9761. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  9762. };
  9763. } )();
  9764. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  9765. /*
  9766. * Custom update matrix
  9767. */
  9768. THREE.Sprite.prototype.updateMatrix = function () {
  9769. this.matrix.compose( this.position, this.quaternion, this.scale );
  9770. this.matrixWorldNeedsUpdate = true;
  9771. };
  9772. THREE.Sprite.prototype.clone = function ( object ) {
  9773. if ( object === undefined ) object = new THREE.Sprite( this.material );
  9774. THREE.Object3D.prototype.clone.call( this, object );
  9775. return object;
  9776. };
  9777. // Backwards compatibility
  9778. THREE.Particle = THREE.Sprite;
  9779. /**
  9780. * @author mrdoob / http://mrdoob.com/
  9781. */
  9782. THREE.Scene = function () {
  9783. THREE.Object3D.call( this );
  9784. this.fog = null;
  9785. this.overrideMaterial = null;
  9786. this.autoUpdate = true; // checked by the renderer
  9787. this.matrixAutoUpdate = false;
  9788. this.__lights = [];
  9789. this.__objectsAdded = [];
  9790. this.__objectsRemoved = [];
  9791. };
  9792. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  9793. THREE.Scene.prototype.__addObject = function ( object ) {
  9794. if ( object instanceof THREE.Light ) {
  9795. if ( this.__lights.indexOf( object ) === - 1 ) {
  9796. this.__lights.push( object );
  9797. }
  9798. if ( object.target && object.target.parent === undefined ) {
  9799. this.add( object.target );
  9800. }
  9801. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  9802. this.__objectsAdded.push( object );
  9803. // check if previously removed
  9804. var i = this.__objectsRemoved.indexOf( object );
  9805. if ( i !== -1 ) {
  9806. this.__objectsRemoved.splice( i, 1 );
  9807. }
  9808. }
  9809. this.dispatchEvent( { type: 'objectAdded', object: object } );
  9810. object.dispatchEvent( { type: 'addedToScene', scene: this } );
  9811. for ( var c = 0; c < object.children.length; c ++ ) {
  9812. this.__addObject( object.children[ c ] );
  9813. }
  9814. };
  9815. THREE.Scene.prototype.__removeObject = function ( object ) {
  9816. if ( object instanceof THREE.Light ) {
  9817. var i = this.__lights.indexOf( object );
  9818. if ( i !== -1 ) {
  9819. this.__lights.splice( i, 1 );
  9820. }
  9821. if ( object.shadowCascadeArray ) {
  9822. for ( var x = 0; x < object.shadowCascadeArray.length; x ++ ) {
  9823. this.__removeObject( object.shadowCascadeArray[ x ] );
  9824. }
  9825. }
  9826. } else if ( !( object instanceof THREE.Camera ) ) {
  9827. this.__objectsRemoved.push( object );
  9828. // check if previously added
  9829. var i = this.__objectsAdded.indexOf( object );
  9830. if ( i !== -1 ) {
  9831. this.__objectsAdded.splice( i, 1 );
  9832. }
  9833. }
  9834. this.dispatchEvent( { type: 'objectRemoved', object: object } );
  9835. object.dispatchEvent( { type: 'removedFromScene', scene: this } );
  9836. for ( var c = 0; c < object.children.length; c ++ ) {
  9837. this.__removeObject( object.children[ c ] );
  9838. }
  9839. };
  9840. THREE.Scene.prototype.clone = function ( object ) {
  9841. if ( object === undefined ) object = new THREE.Scene();
  9842. THREE.Object3D.prototype.clone.call(this, object);
  9843. if ( this.fog !== null ) object.fog = this.fog.clone();
  9844. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  9845. object.autoUpdate = this.autoUpdate;
  9846. object.matrixAutoUpdate = this.matrixAutoUpdate;
  9847. return object;
  9848. };
  9849. /**
  9850. * @author mrdoob / http://mrdoob.com/
  9851. * @author alteredq / http://alteredqualia.com/
  9852. */
  9853. THREE.Fog = function ( color, near, far ) {
  9854. this.name = '';
  9855. this.color = new THREE.Color( color );
  9856. this.near = ( near !== undefined ) ? near : 1;
  9857. this.far = ( far !== undefined ) ? far : 1000;
  9858. };
  9859. THREE.Fog.prototype.clone = function () {
  9860. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  9861. };
  9862. /**
  9863. * @author mrdoob / http://mrdoob.com/
  9864. * @author alteredq / http://alteredqualia.com/
  9865. */
  9866. THREE.FogExp2 = function ( color, density ) {
  9867. this.name = '';
  9868. this.color = new THREE.Color( color );
  9869. this.density = ( density !== undefined ) ? density : 0.00025;
  9870. };
  9871. THREE.FogExp2.prototype.clone = function () {
  9872. return new THREE.FogExp2( this.color.getHex(), this.density );
  9873. };
  9874. /**
  9875. * @author mrdoob / http://mrdoob.com/
  9876. */
  9877. THREE.CanvasRenderer = function ( parameters ) {
  9878. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  9879. var smoothstep = THREE.Math.smoothstep;
  9880. parameters = parameters || {};
  9881. var _this = this,
  9882. _renderData, _elements, _lights,
  9883. _projector = new THREE.Projector(),
  9884. _canvas = parameters.canvas !== undefined
  9885. ? parameters.canvas
  9886. : document.createElement( 'canvas' ),
  9887. _canvasWidth = _canvas.width,
  9888. _canvasHeight = _canvas.height,
  9889. _canvasWidthHalf = Math.floor( _canvasWidth / 2 ),
  9890. _canvasHeightHalf = Math.floor( _canvasHeight / 2 ),
  9891. _context = _canvas.getContext( '2d', {
  9892. alpha: parameters.alpha === true
  9893. } ),
  9894. _clearColor = new THREE.Color( 0x000000 ),
  9895. _clearAlpha = 0,
  9896. _contextGlobalAlpha = 1,
  9897. _contextGlobalCompositeOperation = 0,
  9898. _contextStrokeStyle = null,
  9899. _contextFillStyle = null,
  9900. _contextLineWidth = null,
  9901. _contextLineCap = null,
  9902. _contextLineJoin = null,
  9903. _contextDashSize = null,
  9904. _contextGapSize = 0,
  9905. _camera,
  9906. _v1, _v2, _v3, _v4,
  9907. _v5 = new THREE.RenderableVertex(),
  9908. _v6 = new THREE.RenderableVertex(),
  9909. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  9910. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  9911. _color = new THREE.Color(),
  9912. _color1 = new THREE.Color(),
  9913. _color2 = new THREE.Color(),
  9914. _color3 = new THREE.Color(),
  9915. _color4 = new THREE.Color(),
  9916. _diffuseColor = new THREE.Color(),
  9917. _emissiveColor = new THREE.Color(),
  9918. _lightColor = new THREE.Color(),
  9919. _patterns = {},
  9920. _image, _uvs,
  9921. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  9922. _clipBox = new THREE.Box2(),
  9923. _clearBox = new THREE.Box2(),
  9924. _elemBox = new THREE.Box2(),
  9925. _ambientLight = new THREE.Color(),
  9926. _directionalLights = new THREE.Color(),
  9927. _pointLights = new THREE.Color(),
  9928. _vector3 = new THREE.Vector3(), // Needed for PointLight
  9929. _centroid = new THREE.Vector3(),
  9930. _normal = new THREE.Vector3(),
  9931. _normalViewMatrix = new THREE.Matrix3();
  9932. // dash+gap fallbacks for Firefox and everything else
  9933. if ( _context.setLineDash === undefined ) {
  9934. if ( _context.mozDash !== undefined ) {
  9935. _context.setLineDash = function ( values ) {
  9936. _context.mozDash = values[ 0 ] !== null ? values : null;
  9937. }
  9938. } else {
  9939. _context.setLineDash = function () {}
  9940. }
  9941. }
  9942. this.domElement = _canvas;
  9943. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  9944. ? parameters.devicePixelRatio
  9945. : self.devicePixelRatio !== undefined
  9946. ? self.devicePixelRatio
  9947. : 1;
  9948. this.autoClear = true;
  9949. this.sortObjects = true;
  9950. this.sortElements = true;
  9951. this.info = {
  9952. render: {
  9953. vertices: 0,
  9954. faces: 0
  9955. }
  9956. }
  9957. // WebGLRenderer compatibility
  9958. this.supportsVertexTextures = function () {};
  9959. this.setFaceCulling = function () {};
  9960. this.setSize = function ( width, height, updateStyle ) {
  9961. _canvasWidth = width * this.devicePixelRatio;
  9962. _canvasHeight = height * this.devicePixelRatio;
  9963. _canvas.width = _canvasWidth;
  9964. _canvas.height = _canvasHeight;
  9965. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  9966. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  9967. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  9968. _canvas.style.width = width + 'px';
  9969. _canvas.style.height = height + 'px';
  9970. }
  9971. _clipBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf ),
  9972. _clipBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9973. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9974. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9975. _contextGlobalAlpha = 1;
  9976. _contextGlobalCompositeOperation = 0;
  9977. _contextStrokeStyle = null;
  9978. _contextFillStyle = null;
  9979. _contextLineWidth = null;
  9980. _contextLineCap = null;
  9981. _contextLineJoin = null;
  9982. this.setViewport( 0, 0, width, height );
  9983. };
  9984. this.setViewport = function ( x, y, width, height ) {
  9985. _context.setTransform( width / _canvasWidth, 0, 0, - height / _canvasHeight, x, _canvasHeight - y );
  9986. _context.translate( _canvasWidthHalf, _canvasHeightHalf );
  9987. };
  9988. this.setScissor = function () {};
  9989. this.enableScissorTest = function () {};
  9990. this.setClearColor = function ( color, alpha ) {
  9991. _clearColor.set( color );
  9992. _clearAlpha = alpha !== undefined ? alpha : 1;
  9993. _clearBox.min.set( - _canvasWidthHalf, - _canvasHeightHalf );
  9994. _clearBox.max.set( _canvasWidthHalf, _canvasHeightHalf );
  9995. };
  9996. this.setClearColorHex = function ( hex, alpha ) {
  9997. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  9998. this.setClearColor( hex, alpha );
  9999. };
  10000. this.getMaxAnisotropy = function () {
  10001. return 0;
  10002. };
  10003. this.clear = function () {
  10004. if ( _clearBox.empty() === false ) {
  10005. _clearBox.intersect( _clipBox );
  10006. _clearBox.expandByScalar( 2 );
  10007. if ( _clearAlpha < 1 ) {
  10008. _context.clearRect(
  10009. _clearBox.min.x | 0,
  10010. _clearBox.min.y | 0,
  10011. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  10012. ( _clearBox.max.y - _clearBox.min.y ) | 0
  10013. );
  10014. }
  10015. if ( _clearAlpha > 0 ) {
  10016. setBlending( THREE.NormalBlending );
  10017. setOpacity( 1 );
  10018. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  10019. _context.fillRect(
  10020. _clearBox.min.x | 0,
  10021. _clearBox.min.y | 0,
  10022. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  10023. ( _clearBox.max.y - _clearBox.min.y ) | 0
  10024. );
  10025. }
  10026. _clearBox.makeEmpty();
  10027. }
  10028. };
  10029. // compatibility
  10030. this.clearColor = function () {};
  10031. this.clearDepth = function () {};
  10032. this.clearStencil = function () {};
  10033. this.render = function ( scene, camera ) {
  10034. if ( camera instanceof THREE.Camera === false ) {
  10035. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  10036. return;
  10037. }
  10038. if ( this.autoClear === true ) this.clear();
  10039. _this.info.render.vertices = 0;
  10040. _this.info.render.faces = 0;
  10041. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  10042. _elements = _renderData.elements;
  10043. _lights = _renderData.lights;
  10044. _camera = camera;
  10045. _normalViewMatrix.getNormalMatrix( camera.matrixWorldInverse );
  10046. /* DEBUG
  10047. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  10048. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  10049. */
  10050. calculateLights();
  10051. for ( var e = 0, el = _elements.length; e < el; e ++ ) {
  10052. var element = _elements[ e ];
  10053. var material = element.material;
  10054. if ( material === undefined || material.visible === false ) continue;
  10055. _elemBox.makeEmpty();
  10056. if ( element instanceof THREE.RenderableSprite ) {
  10057. _v1 = element;
  10058. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  10059. renderSprite( _v1, element, material );
  10060. } else if ( element instanceof THREE.RenderableLine ) {
  10061. _v1 = element.v1; _v2 = element.v2;
  10062. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  10063. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  10064. _elemBox.setFromPoints( [
  10065. _v1.positionScreen,
  10066. _v2.positionScreen
  10067. ] );
  10068. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  10069. renderLine( _v1, _v2, element, material );
  10070. }
  10071. } else if ( element instanceof THREE.RenderableFace ) {
  10072. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  10073. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  10074. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  10075. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  10076. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  10077. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  10078. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  10079. if ( material.overdraw > 0 ) {
  10080. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  10081. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  10082. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  10083. }
  10084. _elemBox.setFromPoints( [
  10085. _v1.positionScreen,
  10086. _v2.positionScreen,
  10087. _v3.positionScreen
  10088. ] );
  10089. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  10090. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  10091. }
  10092. }
  10093. /* DEBUG
  10094. setLineWidth( 1 );
  10095. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  10096. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  10097. */
  10098. _clearBox.union( _elemBox );
  10099. }
  10100. /* DEBUG
  10101. setLineWidth( 1 );
  10102. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  10103. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  10104. */
  10105. // _context.setTransform( 1, 0, 0, 1, 0, 0 );
  10106. };
  10107. //
  10108. function calculateLights() {
  10109. _ambientLight.setRGB( 0, 0, 0 );
  10110. _directionalLights.setRGB( 0, 0, 0 );
  10111. _pointLights.setRGB( 0, 0, 0 );
  10112. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  10113. var light = _lights[ l ];
  10114. var lightColor = light.color;
  10115. if ( light instanceof THREE.AmbientLight ) {
  10116. _ambientLight.add( lightColor );
  10117. } else if ( light instanceof THREE.DirectionalLight ) {
  10118. // for sprites
  10119. _directionalLights.add( lightColor );
  10120. } else if ( light instanceof THREE.PointLight ) {
  10121. // for sprites
  10122. _pointLights.add( lightColor );
  10123. }
  10124. }
  10125. }
  10126. function calculateLight( position, normal, color ) {
  10127. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  10128. var light = _lights[ l ];
  10129. _lightColor.copy( light.color );
  10130. if ( light instanceof THREE.DirectionalLight ) {
  10131. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld ).normalize();
  10132. var amount = normal.dot( lightPosition );
  10133. if ( amount <= 0 ) continue;
  10134. amount *= light.intensity;
  10135. color.add( _lightColor.multiplyScalar( amount ) );
  10136. } else if ( light instanceof THREE.PointLight ) {
  10137. var lightPosition = _vector3.setFromMatrixPosition( light.matrixWorld );
  10138. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  10139. if ( amount <= 0 ) continue;
  10140. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  10141. if ( amount == 0 ) continue;
  10142. amount *= light.intensity;
  10143. color.add( _lightColor.multiplyScalar( amount ) );
  10144. }
  10145. }
  10146. }
  10147. function renderSprite( v1, element, material ) {
  10148. setOpacity( material.opacity );
  10149. setBlending( material.blending );
  10150. var scaleX = element.scale.x * _canvasWidthHalf;
  10151. var scaleY = element.scale.y * _canvasHeightHalf;
  10152. var dist = 0.5 * Math.sqrt( scaleX * scaleX + scaleY * scaleY ); // allow for rotated sprite
  10153. _elemBox.min.set( v1.x - dist, v1.y - dist );
  10154. _elemBox.max.set( v1.x + dist, v1.y + dist );
  10155. if ( material instanceof THREE.SpriteMaterial ||
  10156. material instanceof THREE.ParticleSystemMaterial ) { // Backwards compatibility
  10157. var texture = material.map;
  10158. if ( texture !== null ) {
  10159. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10160. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10161. textureToPattern( texture );
  10162. }
  10163. texture.addEventListener( 'update', onTextureUpdate );
  10164. }
  10165. var pattern = _patterns[ texture.id ];
  10166. if ( pattern !== undefined ) {
  10167. setFillStyle( pattern );
  10168. } else {
  10169. setFillStyle( 'rgba( 0, 0, 0, 1 )' );
  10170. }
  10171. //
  10172. var bitmap = texture.image;
  10173. var ox = bitmap.width * texture.offset.x;
  10174. var oy = bitmap.height * texture.offset.y;
  10175. var sx = bitmap.width * texture.repeat.x;
  10176. var sy = bitmap.height * texture.repeat.y;
  10177. var cx = scaleX / sx;
  10178. var cy = scaleY / sy;
  10179. _context.save();
  10180. _context.translate( v1.x, v1.y );
  10181. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10182. _context.translate( - scaleX / 2, - scaleY / 2 );
  10183. _context.scale( cx, cy );
  10184. _context.translate( - ox, - oy );
  10185. _context.fillRect( ox, oy, sx, sy );
  10186. _context.restore();
  10187. } else { // no texture
  10188. setFillStyle( material.color.getStyle() );
  10189. _context.save();
  10190. _context.translate( v1.x, v1.y );
  10191. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10192. _context.scale( scaleX, - scaleY );
  10193. _context.fillRect( - 0.5, - 0.5, 1, 1 );
  10194. _context.restore();
  10195. }
  10196. } else if ( material instanceof THREE.SpriteCanvasMaterial ) {
  10197. setStrokeStyle( material.color.getStyle() );
  10198. setFillStyle( material.color.getStyle() );
  10199. _context.save();
  10200. _context.translate( v1.x, v1.y );
  10201. if ( material.rotation !== 0 ) _context.rotate( material.rotation );
  10202. _context.scale( scaleX, scaleY );
  10203. material.program( _context );
  10204. _context.restore();
  10205. }
  10206. /* DEBUG
  10207. setStrokeStyle( 'rgb(255,255,0)' );
  10208. _context.beginPath();
  10209. _context.moveTo( v1.x - 10, v1.y );
  10210. _context.lineTo( v1.x + 10, v1.y );
  10211. _context.moveTo( v1.x, v1.y - 10 );
  10212. _context.lineTo( v1.x, v1.y + 10 );
  10213. _context.stroke();
  10214. */
  10215. }
  10216. function renderLine( v1, v2, element, material ) {
  10217. setOpacity( material.opacity );
  10218. setBlending( material.blending );
  10219. _context.beginPath();
  10220. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  10221. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  10222. if ( material instanceof THREE.LineBasicMaterial ) {
  10223. setLineWidth( material.linewidth );
  10224. setLineCap( material.linecap );
  10225. setLineJoin( material.linejoin );
  10226. if ( material.vertexColors !== THREE.VertexColors ) {
  10227. setStrokeStyle( material.color.getStyle() );
  10228. } else {
  10229. var colorStyle1 = element.vertexColors[0].getStyle();
  10230. var colorStyle2 = element.vertexColors[1].getStyle();
  10231. if ( colorStyle1 === colorStyle2 ) {
  10232. setStrokeStyle( colorStyle1 );
  10233. } else {
  10234. try {
  10235. var grad = _context.createLinearGradient(
  10236. v1.positionScreen.x,
  10237. v1.positionScreen.y,
  10238. v2.positionScreen.x,
  10239. v2.positionScreen.y
  10240. );
  10241. grad.addColorStop( 0, colorStyle1 );
  10242. grad.addColorStop( 1, colorStyle2 );
  10243. } catch ( exception ) {
  10244. grad = colorStyle1;
  10245. }
  10246. setStrokeStyle( grad );
  10247. }
  10248. }
  10249. _context.stroke();
  10250. _elemBox.expandByScalar( material.linewidth * 2 );
  10251. } else if ( material instanceof THREE.LineDashedMaterial ) {
  10252. setLineWidth( material.linewidth );
  10253. setLineCap( material.linecap );
  10254. setLineJoin( material.linejoin );
  10255. setStrokeStyle( material.color.getStyle() );
  10256. setDashAndGap( material.dashSize, material.gapSize );
  10257. _context.stroke();
  10258. _elemBox.expandByScalar( material.linewidth * 2 );
  10259. setDashAndGap( null, null );
  10260. }
  10261. }
  10262. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  10263. _this.info.render.vertices += 3;
  10264. _this.info.render.faces ++;
  10265. setOpacity( material.opacity );
  10266. setBlending( material.blending );
  10267. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  10268. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  10269. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  10270. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  10271. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  10272. _diffuseColor.copy( material.color );
  10273. _emissiveColor.copy( material.emissive );
  10274. if ( material.vertexColors === THREE.FaceColors ) {
  10275. _diffuseColor.multiply( element.color );
  10276. }
  10277. _color.copy( _ambientLight );
  10278. _centroid.copy( v1.positionWorld ).add( v2.positionWorld ).add( v3.positionWorld ).divideScalar( 3 );
  10279. calculateLight( _centroid, element.normalModel, _color );
  10280. _color.multiply( _diffuseColor ).add( _emissiveColor );
  10281. material.wireframe === true
  10282. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10283. : fillPath( _color );
  10284. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  10285. if ( material.map !== null ) {
  10286. if ( material.map.mapping instanceof THREE.UVMapping ) {
  10287. _uvs = element.uvs;
  10288. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].x, _uvs[ uv1 ].y, _uvs[ uv2 ].x, _uvs[ uv2 ].y, _uvs[ uv3 ].x, _uvs[ uv3 ].y, material.map );
  10289. }
  10290. } else if ( material.envMap !== null ) {
  10291. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  10292. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10293. _uv1x = 0.5 * _normal.x + 0.5;
  10294. _uv1y = 0.5 * _normal.y + 0.5;
  10295. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10296. _uv2x = 0.5 * _normal.x + 0.5;
  10297. _uv2y = 0.5 * _normal.y + 0.5;
  10298. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10299. _uv3x = 0.5 * _normal.x + 0.5;
  10300. _uv3y = 0.5 * _normal.y + 0.5;
  10301. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  10302. } else if ( material.envMap.mapping instanceof THREE.SphericalRefractionMapping ) {
  10303. _normal.copy( element.vertexNormalsModel[ uv1 ] ).applyMatrix3( _normalViewMatrix );
  10304. _uv1x = - 0.5 * _normal.x + 0.5;
  10305. _uv1y = - 0.5 * _normal.y + 0.5;
  10306. _normal.copy( element.vertexNormalsModel[ uv2 ] ).applyMatrix3( _normalViewMatrix );
  10307. _uv2x = - 0.5 * _normal.x + 0.5;
  10308. _uv2y = - 0.5 * _normal.y + 0.5;
  10309. _normal.copy( element.vertexNormalsModel[ uv3 ] ).applyMatrix3( _normalViewMatrix );
  10310. _uv3x = - 0.5 * _normal.x + 0.5;
  10311. _uv3y = - 0.5 * _normal.y + 0.5;
  10312. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  10313. }
  10314. } else {
  10315. _color.copy( material.color );
  10316. if ( material.vertexColors === THREE.FaceColors ) {
  10317. _color.multiply( element.color );
  10318. }
  10319. material.wireframe === true
  10320. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10321. : fillPath( _color );
  10322. }
  10323. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  10324. _color.r = _color.g = _color.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _camera.near, _camera.far );
  10325. material.wireframe === true
  10326. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10327. : fillPath( _color );
  10328. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  10329. _normal.copy( element.normalModel ).applyMatrix3( _normalViewMatrix );
  10330. _color.setRGB( _normal.x, _normal.y, _normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  10331. material.wireframe === true
  10332. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10333. : fillPath( _color );
  10334. } else {
  10335. _color.setRGB( 1, 1, 1 );
  10336. material.wireframe === true
  10337. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  10338. : fillPath( _color );
  10339. }
  10340. }
  10341. //
  10342. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  10343. _context.beginPath();
  10344. _context.moveTo( x0, y0 );
  10345. _context.lineTo( x1, y1 );
  10346. _context.lineTo( x2, y2 );
  10347. _context.closePath();
  10348. }
  10349. function strokePath( color, linewidth, linecap, linejoin ) {
  10350. setLineWidth( linewidth );
  10351. setLineCap( linecap );
  10352. setLineJoin( linejoin );
  10353. setStrokeStyle( color.getStyle() );
  10354. _context.stroke();
  10355. _elemBox.expandByScalar( linewidth * 2 );
  10356. }
  10357. function fillPath( color ) {
  10358. setFillStyle( color.getStyle() );
  10359. _context.fill();
  10360. }
  10361. function onTextureUpdate ( event ) {
  10362. textureToPattern( event.target );
  10363. }
  10364. function textureToPattern( texture ) {
  10365. var repeatX = texture.wrapS === THREE.RepeatWrapping;
  10366. var repeatY = texture.wrapT === THREE.RepeatWrapping;
  10367. var image = texture.image;
  10368. var canvas = document.createElement( 'canvas' );
  10369. canvas.width = image.width;
  10370. canvas.height = image.height;
  10371. var context = canvas.getContext( '2d' );
  10372. context.setTransform( 1, 0, 0, - 1, 0, image.height );
  10373. context.drawImage( image, 0, 0 );
  10374. _patterns[ texture.id ] = _context.createPattern(
  10375. canvas, repeatX === true && repeatY === true
  10376. ? 'repeat'
  10377. : repeatX === true && repeatY === false
  10378. ? 'repeat-x'
  10379. : repeatX === false && repeatY === true
  10380. ? 'repeat-y'
  10381. : 'no-repeat'
  10382. );
  10383. }
  10384. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  10385. if ( texture instanceof THREE.DataTexture ) return;
  10386. if ( texture.hasEventListener( 'update', onTextureUpdate ) === false ) {
  10387. if ( texture.image !== undefined && texture.image.width > 0 ) {
  10388. textureToPattern( texture );
  10389. }
  10390. texture.addEventListener( 'update', onTextureUpdate );
  10391. }
  10392. var pattern = _patterns[ texture.id ];
  10393. if ( pattern !== undefined ) {
  10394. setFillStyle( pattern );
  10395. } else {
  10396. setFillStyle( 'rgba(0,0,0,1)' );
  10397. _context.fill();
  10398. return;
  10399. }
  10400. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10401. var a, b, c, d, e, f, det, idet,
  10402. offsetX = texture.offset.x / texture.repeat.x,
  10403. offsetY = texture.offset.y / texture.repeat.y,
  10404. width = texture.image.width * texture.repeat.x,
  10405. height = texture.image.height * texture.repeat.y;
  10406. u0 = ( u0 + offsetX ) * width;
  10407. v0 = ( v0 + offsetY ) * height;
  10408. u1 = ( u1 + offsetX ) * width;
  10409. v1 = ( v1 + offsetY ) * height;
  10410. u2 = ( u2 + offsetX ) * width;
  10411. v2 = ( v2 + offsetY ) * height;
  10412. x1 -= x0; y1 -= y0;
  10413. x2 -= x0; y2 -= y0;
  10414. u1 -= u0; v1 -= v0;
  10415. u2 -= u0; v2 -= v0;
  10416. det = u1 * v2 - u2 * v1;
  10417. if ( det === 0 ) return;
  10418. idet = 1 / det;
  10419. a = ( v2 * x1 - v1 * x2 ) * idet;
  10420. b = ( v2 * y1 - v1 * y2 ) * idet;
  10421. c = ( u1 * x2 - u2 * x1 ) * idet;
  10422. d = ( u1 * y2 - u2 * y1 ) * idet;
  10423. e = x0 - a * u0 - c * v0;
  10424. f = y0 - b * u0 - d * v0;
  10425. _context.save();
  10426. _context.transform( a, b, c, d, e, f );
  10427. _context.fill();
  10428. _context.restore();
  10429. }
  10430. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  10431. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  10432. var a, b, c, d, e, f, det, idet,
  10433. width = image.width - 1,
  10434. height = image.height - 1;
  10435. u0 *= width; v0 *= height;
  10436. u1 *= width; v1 *= height;
  10437. u2 *= width; v2 *= height;
  10438. x1 -= x0; y1 -= y0;
  10439. x2 -= x0; y2 -= y0;
  10440. u1 -= u0; v1 -= v0;
  10441. u2 -= u0; v2 -= v0;
  10442. det = u1 * v2 - u2 * v1;
  10443. idet = 1 / det;
  10444. a = ( v2 * x1 - v1 * x2 ) * idet;
  10445. b = ( v2 * y1 - v1 * y2 ) * idet;
  10446. c = ( u1 * x2 - u2 * x1 ) * idet;
  10447. d = ( u1 * y2 - u2 * y1 ) * idet;
  10448. e = x0 - a * u0 - c * v0;
  10449. f = y0 - b * u0 - d * v0;
  10450. _context.save();
  10451. _context.transform( a, b, c, d, e, f );
  10452. _context.clip();
  10453. _context.drawImage( image, 0, 0 );
  10454. _context.restore();
  10455. }
  10456. // Hide anti-alias gaps
  10457. function expand( v1, v2, pixels ) {
  10458. var x = v2.x - v1.x, y = v2.y - v1.y,
  10459. det = x * x + y * y, idet;
  10460. if ( det === 0 ) return;
  10461. idet = pixels / Math.sqrt( det );
  10462. x *= idet; y *= idet;
  10463. v2.x += x; v2.y += y;
  10464. v1.x -= x; v1.y -= y;
  10465. }
  10466. // Context cached methods.
  10467. function setOpacity( value ) {
  10468. if ( _contextGlobalAlpha !== value ) {
  10469. _context.globalAlpha = value;
  10470. _contextGlobalAlpha = value;
  10471. }
  10472. }
  10473. function setBlending( value ) {
  10474. if ( _contextGlobalCompositeOperation !== value ) {
  10475. if ( value === THREE.NormalBlending ) {
  10476. _context.globalCompositeOperation = 'source-over';
  10477. } else if ( value === THREE.AdditiveBlending ) {
  10478. _context.globalCompositeOperation = 'lighter';
  10479. } else if ( value === THREE.SubtractiveBlending ) {
  10480. _context.globalCompositeOperation = 'darker';
  10481. }
  10482. _contextGlobalCompositeOperation = value;
  10483. }
  10484. }
  10485. function setLineWidth( value ) {
  10486. if ( _contextLineWidth !== value ) {
  10487. _context.lineWidth = value;
  10488. _contextLineWidth = value;
  10489. }
  10490. }
  10491. function setLineCap( value ) {
  10492. // "butt", "round", "square"
  10493. if ( _contextLineCap !== value ) {
  10494. _context.lineCap = value;
  10495. _contextLineCap = value;
  10496. }
  10497. }
  10498. function setLineJoin( value ) {
  10499. // "round", "bevel", "miter"
  10500. if ( _contextLineJoin !== value ) {
  10501. _context.lineJoin = value;
  10502. _contextLineJoin = value;
  10503. }
  10504. }
  10505. function setStrokeStyle( value ) {
  10506. if ( _contextStrokeStyle !== value ) {
  10507. _context.strokeStyle = value;
  10508. _contextStrokeStyle = value;
  10509. }
  10510. }
  10511. function setFillStyle( value ) {
  10512. if ( _contextFillStyle !== value ) {
  10513. _context.fillStyle = value;
  10514. _contextFillStyle = value;
  10515. }
  10516. }
  10517. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  10518. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  10519. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  10520. _contextDashSize = dashSizeValue;
  10521. _contextGapSize = gapSizeValue;
  10522. }
  10523. }
  10524. };
  10525. /**
  10526. * Shader chunks for WebLG Shader library
  10527. *
  10528. * @author alteredq / http://alteredqualia.com/
  10529. * @author mrdoob / http://mrdoob.com/
  10530. * @author mikael emtinger / http://gomo.se/
  10531. */
  10532. THREE.ShaderChunk = {
  10533. // FOG
  10534. fog_pars_fragment: [
  10535. "#ifdef USE_FOG",
  10536. " uniform vec3 fogColor;",
  10537. " #ifdef FOG_EXP2",
  10538. " uniform float fogDensity;",
  10539. " #else",
  10540. " uniform float fogNear;",
  10541. " uniform float fogFar;",
  10542. " #endif",
  10543. "#endif"
  10544. ].join("\n"),
  10545. fog_fragment: [
  10546. "#ifdef USE_FOG",
  10547. " #ifdef USE_LOGDEPTHBUF_EXT",
  10548. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  10549. " #else",
  10550. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10551. " #endif",
  10552. " #ifdef FOG_EXP2",
  10553. " const float LOG2 = 1.442695;",
  10554. " float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  10555. " fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  10556. " #else",
  10557. " float fogFactor = smoothstep( fogNear, fogFar, depth );",
  10558. " #endif",
  10559. " gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  10560. "#endif"
  10561. ].join("\n"),
  10562. // ENVIRONMENT MAP
  10563. envmap_pars_fragment: [
  10564. "#ifdef USE_ENVMAP",
  10565. " uniform float reflectivity;",
  10566. " uniform samplerCube envMap;",
  10567. " uniform float flipEnvMap;",
  10568. " uniform int combine;",
  10569. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10570. " uniform bool useRefract;",
  10571. " uniform float refractionRatio;",
  10572. " #else",
  10573. " varying vec3 vReflect;",
  10574. " #endif",
  10575. "#endif"
  10576. ].join("\n"),
  10577. envmap_fragment: [
  10578. "#ifdef USE_ENVMAP",
  10579. " vec3 reflectVec;",
  10580. " #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  10581. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  10582. // http://en.wikibooks.org/wiki/GLSL_Programming/Applying_Matrix_Transformations
  10583. // "Transforming Normal Vectors with the Inverse Transformation"
  10584. " vec3 worldNormal = normalize( vec3( vec4( normal, 0.0 ) * viewMatrix ) );",
  10585. " if ( useRefract ) {",
  10586. " reflectVec = refract( cameraToVertex, worldNormal, refractionRatio );",
  10587. " } else { ",
  10588. " reflectVec = reflect( cameraToVertex, worldNormal );",
  10589. " }",
  10590. " #else",
  10591. " reflectVec = vReflect;",
  10592. " #endif",
  10593. " #ifdef DOUBLE_SIDED",
  10594. " float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10595. " vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10596. " #else",
  10597. " vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  10598. " #endif",
  10599. " #ifdef GAMMA_INPUT",
  10600. " cubeColor.xyz *= cubeColor.xyz;",
  10601. " #endif",
  10602. " if ( combine == 1 ) {",
  10603. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  10604. " } else if ( combine == 2 ) {",
  10605. " gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  10606. " } else {",
  10607. " gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  10608. " }",
  10609. "#endif"
  10610. ].join("\n"),
  10611. envmap_pars_vertex: [
  10612. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10613. " varying vec3 vReflect;",
  10614. " uniform float refractionRatio;",
  10615. " uniform bool useRefract;",
  10616. "#endif"
  10617. ].join("\n"),
  10618. worldpos_vertex : [
  10619. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  10620. " #ifdef USE_SKINNING",
  10621. " vec4 worldPosition = modelMatrix * skinned;",
  10622. " #endif",
  10623. " #if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10624. " vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  10625. " #endif",
  10626. " #if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  10627. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  10628. " #endif",
  10629. "#endif"
  10630. ].join("\n"),
  10631. envmap_vertex : [
  10632. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  10633. " vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  10634. " worldNormal = normalize( worldNormal );",
  10635. " vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  10636. " if ( useRefract ) {",
  10637. " vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  10638. " } else {",
  10639. " vReflect = reflect( cameraToVertex, worldNormal );",
  10640. " }",
  10641. "#endif"
  10642. ].join("\n"),
  10643. // COLOR MAP (particles)
  10644. map_particle_pars_fragment: [
  10645. "#ifdef USE_MAP",
  10646. " uniform sampler2D map;",
  10647. "#endif"
  10648. ].join("\n"),
  10649. map_particle_fragment: [
  10650. "#ifdef USE_MAP",
  10651. " gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  10652. "#endif"
  10653. ].join("\n"),
  10654. // COLOR MAP (triangles)
  10655. map_pars_vertex: [
  10656. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10657. " varying vec2 vUv;",
  10658. " uniform vec4 offsetRepeat;",
  10659. "#endif"
  10660. ].join("\n"),
  10661. map_pars_fragment: [
  10662. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10663. " varying vec2 vUv;",
  10664. "#endif",
  10665. "#ifdef USE_MAP",
  10666. " uniform sampler2D map;",
  10667. "#endif"
  10668. ].join("\n"),
  10669. map_vertex: [
  10670. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  10671. " vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  10672. "#endif"
  10673. ].join("\n"),
  10674. map_fragment: [
  10675. "#ifdef USE_MAP",
  10676. " vec4 texelColor = texture2D( map, vUv );",
  10677. " #ifdef GAMMA_INPUT",
  10678. " texelColor.xyz *= texelColor.xyz;",
  10679. " #endif",
  10680. " gl_FragColor = gl_FragColor * texelColor;",
  10681. "#endif"
  10682. ].join("\n"),
  10683. // LIGHT MAP
  10684. lightmap_pars_fragment: [
  10685. "#ifdef USE_LIGHTMAP",
  10686. " varying vec2 vUv2;",
  10687. " uniform sampler2D lightMap;",
  10688. "#endif"
  10689. ].join("\n"),
  10690. lightmap_pars_vertex: [
  10691. "#ifdef USE_LIGHTMAP",
  10692. " varying vec2 vUv2;",
  10693. "#endif"
  10694. ].join("\n"),
  10695. lightmap_fragment: [
  10696. "#ifdef USE_LIGHTMAP",
  10697. " gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  10698. "#endif"
  10699. ].join("\n"),
  10700. lightmap_vertex: [
  10701. "#ifdef USE_LIGHTMAP",
  10702. " vUv2 = uv2;",
  10703. "#endif"
  10704. ].join("\n"),
  10705. // BUMP MAP
  10706. bumpmap_pars_fragment: [
  10707. "#ifdef USE_BUMPMAP",
  10708. " uniform sampler2D bumpMap;",
  10709. " uniform float bumpScale;",
  10710. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  10711. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  10712. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  10713. " vec2 dHdxy_fwd() {",
  10714. " vec2 dSTdx = dFdx( vUv );",
  10715. " vec2 dSTdy = dFdy( vUv );",
  10716. " float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  10717. " float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  10718. " float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  10719. " return vec2( dBx, dBy );",
  10720. " }",
  10721. " vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  10722. " vec3 vSigmaX = dFdx( surf_pos );",
  10723. " vec3 vSigmaY = dFdy( surf_pos );",
  10724. " vec3 vN = surf_norm;", // normalized
  10725. " vec3 R1 = cross( vSigmaY, vN );",
  10726. " vec3 R2 = cross( vN, vSigmaX );",
  10727. " float fDet = dot( vSigmaX, R1 );",
  10728. " vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  10729. " return normalize( abs( fDet ) * surf_norm - vGrad );",
  10730. " }",
  10731. "#endif"
  10732. ].join("\n"),
  10733. // NORMAL MAP
  10734. normalmap_pars_fragment: [
  10735. "#ifdef USE_NORMALMAP",
  10736. " uniform sampler2D normalMap;",
  10737. " uniform vec2 normalScale;",
  10738. // Per-Pixel Tangent Space Normal Mapping
  10739. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  10740. " vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  10741. " vec3 q0 = dFdx( eye_pos.xyz );",
  10742. " vec3 q1 = dFdy( eye_pos.xyz );",
  10743. " vec2 st0 = dFdx( vUv.st );",
  10744. " vec2 st1 = dFdy( vUv.st );",
  10745. " vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  10746. " vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  10747. " vec3 N = normalize( surf_norm );",
  10748. " vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  10749. " mapN.xy = normalScale * mapN.xy;",
  10750. " mat3 tsn = mat3( S, T, N );",
  10751. " return normalize( tsn * mapN );",
  10752. " }",
  10753. "#endif"
  10754. ].join("\n"),
  10755. // SPECULAR MAP
  10756. specularmap_pars_fragment: [
  10757. "#ifdef USE_SPECULARMAP",
  10758. " uniform sampler2D specularMap;",
  10759. "#endif"
  10760. ].join("\n"),
  10761. specularmap_fragment: [
  10762. "float specularStrength;",
  10763. "#ifdef USE_SPECULARMAP",
  10764. " vec4 texelSpecular = texture2D( specularMap, vUv );",
  10765. " specularStrength = texelSpecular.r;",
  10766. "#else",
  10767. " specularStrength = 1.0;",
  10768. "#endif"
  10769. ].join("\n"),
  10770. // LIGHTS LAMBERT
  10771. lights_lambert_pars_vertex: [
  10772. "uniform vec3 ambient;",
  10773. "uniform vec3 diffuse;",
  10774. "uniform vec3 emissive;",
  10775. "uniform vec3 ambientLightColor;",
  10776. "#if MAX_DIR_LIGHTS > 0",
  10777. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10778. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10779. "#endif",
  10780. "#if MAX_HEMI_LIGHTS > 0",
  10781. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10782. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10783. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10784. "#endif",
  10785. "#if MAX_POINT_LIGHTS > 0",
  10786. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10787. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10788. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10789. "#endif",
  10790. "#if MAX_SPOT_LIGHTS > 0",
  10791. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10792. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10793. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10794. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10795. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10796. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10797. "#endif",
  10798. "#ifdef WRAP_AROUND",
  10799. " uniform vec3 wrapRGB;",
  10800. "#endif"
  10801. ].join("\n"),
  10802. lights_lambert_vertex: [
  10803. "vLightFront = vec3( 0.0 );",
  10804. "#ifdef DOUBLE_SIDED",
  10805. " vLightBack = vec3( 0.0 );",
  10806. "#endif",
  10807. "transformedNormal = normalize( transformedNormal );",
  10808. "#if MAX_DIR_LIGHTS > 0",
  10809. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10810. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10811. " vec3 dirVector = normalize( lDirection.xyz );",
  10812. " float dotProduct = dot( transformedNormal, dirVector );",
  10813. " vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10814. " #ifdef DOUBLE_SIDED",
  10815. " vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10816. " #ifdef WRAP_AROUND",
  10817. " vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10818. " #endif",
  10819. " #endif",
  10820. " #ifdef WRAP_AROUND",
  10821. " vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10822. " directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  10823. " #ifdef DOUBLE_SIDED",
  10824. " directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  10825. " #endif",
  10826. " #endif",
  10827. " vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  10828. " #ifdef DOUBLE_SIDED",
  10829. " vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  10830. " #endif",
  10831. "}",
  10832. "#endif",
  10833. "#if MAX_POINT_LIGHTS > 0",
  10834. " for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10835. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10836. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10837. " float lDistance = 1.0;",
  10838. " if ( pointLightDistance[ i ] > 0.0 )",
  10839. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10840. " lVector = normalize( lVector );",
  10841. " float dotProduct = dot( transformedNormal, lVector );",
  10842. " vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10843. " #ifdef DOUBLE_SIDED",
  10844. " vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10845. " #ifdef WRAP_AROUND",
  10846. " vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10847. " #endif",
  10848. " #endif",
  10849. " #ifdef WRAP_AROUND",
  10850. " vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10851. " pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  10852. " #ifdef DOUBLE_SIDED",
  10853. " pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  10854. " #endif",
  10855. " #endif",
  10856. " vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  10857. " #ifdef DOUBLE_SIDED",
  10858. " vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  10859. " #endif",
  10860. " }",
  10861. "#endif",
  10862. "#if MAX_SPOT_LIGHTS > 0",
  10863. " for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10864. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10865. " vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  10866. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  10867. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10868. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10869. " float lDistance = 1.0;",
  10870. " if ( spotLightDistance[ i ] > 0.0 )",
  10871. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10872. " lVector = normalize( lVector );",
  10873. " float dotProduct = dot( transformedNormal, lVector );",
  10874. " vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  10875. " #ifdef DOUBLE_SIDED",
  10876. " vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  10877. " #ifdef WRAP_AROUND",
  10878. " vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  10879. " #endif",
  10880. " #endif",
  10881. " #ifdef WRAP_AROUND",
  10882. " vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  10883. " spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  10884. " #ifdef DOUBLE_SIDED",
  10885. " spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  10886. " #endif",
  10887. " #endif",
  10888. " vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  10889. " #ifdef DOUBLE_SIDED",
  10890. " vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  10891. " #endif",
  10892. " }",
  10893. " }",
  10894. "#endif",
  10895. "#if MAX_HEMI_LIGHTS > 0",
  10896. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10897. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10898. " vec3 lVector = normalize( lDirection.xyz );",
  10899. " float dotProduct = dot( transformedNormal, lVector );",
  10900. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10901. " float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  10902. " vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10903. " #ifdef DOUBLE_SIDED",
  10904. " vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  10905. " #endif",
  10906. " }",
  10907. "#endif",
  10908. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  10909. "#ifdef DOUBLE_SIDED",
  10910. " vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  10911. "#endif"
  10912. ].join("\n"),
  10913. // LIGHTS PHONG
  10914. lights_phong_pars_vertex: [
  10915. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10916. " varying vec3 vWorldPosition;",
  10917. "#endif"
  10918. ].join("\n"),
  10919. lights_phong_vertex: [
  10920. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10921. " vWorldPosition = worldPosition.xyz;",
  10922. "#endif"
  10923. ].join("\n"),
  10924. lights_phong_pars_fragment: [
  10925. "uniform vec3 ambientLightColor;",
  10926. "#if MAX_DIR_LIGHTS > 0",
  10927. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  10928. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  10929. "#endif",
  10930. "#if MAX_HEMI_LIGHTS > 0",
  10931. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  10932. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  10933. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  10934. "#endif",
  10935. "#if MAX_POINT_LIGHTS > 0",
  10936. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10937. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10938. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10939. "#endif",
  10940. "#if MAX_SPOT_LIGHTS > 0",
  10941. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10942. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10943. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10944. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10945. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10946. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10947. "#endif",
  10948. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP ) || defined( USE_ENVMAP )",
  10949. " varying vec3 vWorldPosition;",
  10950. "#endif",
  10951. "#ifdef WRAP_AROUND",
  10952. " uniform vec3 wrapRGB;",
  10953. "#endif",
  10954. "varying vec3 vViewPosition;",
  10955. "varying vec3 vNormal;"
  10956. ].join("\n"),
  10957. lights_phong_fragment: [
  10958. "vec3 normal = normalize( vNormal );",
  10959. "vec3 viewPosition = normalize( vViewPosition );",
  10960. "#ifdef DOUBLE_SIDED",
  10961. " normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10962. "#endif",
  10963. "#ifdef USE_NORMALMAP",
  10964. " normal = perturbNormal2Arb( -vViewPosition, normal );",
  10965. "#elif defined( USE_BUMPMAP )",
  10966. " normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10967. "#endif",
  10968. "#if MAX_POINT_LIGHTS > 0",
  10969. " vec3 pointDiffuse = vec3( 0.0 );",
  10970. " vec3 pointSpecular = vec3( 0.0 );",
  10971. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10972. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10973. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10974. " float lDistance = 1.0;",
  10975. " if ( pointLightDistance[ i ] > 0.0 )",
  10976. " lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10977. " lVector = normalize( lVector );",
  10978. // diffuse
  10979. " float dotProduct = dot( normal, lVector );",
  10980. " #ifdef WRAP_AROUND",
  10981. " float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10982. " float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10983. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10984. " #else",
  10985. " float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10986. " #endif",
  10987. " pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10988. // specular
  10989. " vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10990. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10991. " float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10992. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10993. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10994. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, pointHalfVector ), 0.0 ), 5.0 );",
  10995. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10996. " }",
  10997. "#endif",
  10998. "#if MAX_SPOT_LIGHTS > 0",
  10999. " vec3 spotDiffuse = vec3( 0.0 );",
  11000. " vec3 spotSpecular = vec3( 0.0 );",
  11001. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11002. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11003. " vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  11004. " float lDistance = 1.0;",
  11005. " if ( spotLightDistance[ i ] > 0.0 )",
  11006. " lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  11007. " lVector = normalize( lVector );",
  11008. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11009. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11010. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11011. // diffuse
  11012. " float dotProduct = dot( normal, lVector );",
  11013. " #ifdef WRAP_AROUND",
  11014. " float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  11015. " float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  11016. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11017. " #else",
  11018. " float spotDiffuseWeight = max( dotProduct, 0.0 );",
  11019. " #endif",
  11020. " spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  11021. // specular
  11022. " vec3 spotHalfVector = normalize( lVector + viewPosition );",
  11023. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11024. " float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  11025. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11026. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11027. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, spotHalfVector ), 0.0 ), 5.0 );",
  11028. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  11029. " }",
  11030. " }",
  11031. "#endif",
  11032. "#if MAX_DIR_LIGHTS > 0",
  11033. " vec3 dirDiffuse = vec3( 0.0 );",
  11034. " vec3 dirSpecular = vec3( 0.0 );" ,
  11035. " for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  11036. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11037. " vec3 dirVector = normalize( lDirection.xyz );",
  11038. // diffuse
  11039. " float dotProduct = dot( normal, dirVector );",
  11040. " #ifdef WRAP_AROUND",
  11041. " float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  11042. " float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  11043. " vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  11044. " #else",
  11045. " float dirDiffuseWeight = max( dotProduct, 0.0 );",
  11046. " #endif",
  11047. " dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  11048. // specular
  11049. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11050. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11051. " float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  11052. /*
  11053. // fresnel term from skin shader
  11054. " const float F0 = 0.128;",
  11055. " float base = 1.0 - dot( viewPosition, dirHalfVector );",
  11056. " float exponential = pow( base, 5.0 );",
  11057. " float fresnel = exponential + F0 * ( 1.0 - exponential );",
  11058. */
  11059. /*
  11060. // fresnel term from fresnel shader
  11061. " const float mFresnelBias = 0.08;",
  11062. " const float mFresnelScale = 0.3;",
  11063. " const float mFresnelPower = 5.0;",
  11064. " float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  11065. */
  11066. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11067. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11068. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  11069. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( dirVector, dirHalfVector ), 0.0 ), 5.0 );",
  11070. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11071. " }",
  11072. "#endif",
  11073. "#if MAX_HEMI_LIGHTS > 0",
  11074. " vec3 hemiDiffuse = vec3( 0.0 );",
  11075. " vec3 hemiSpecular = vec3( 0.0 );" ,
  11076. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11077. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11078. " vec3 lVector = normalize( lDirection.xyz );",
  11079. // diffuse
  11080. " float dotProduct = dot( normal, lVector );",
  11081. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11082. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11083. " hemiDiffuse += diffuse * hemiColor;",
  11084. // specular (sky light)
  11085. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11086. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11087. " float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  11088. // specular (ground light)
  11089. " vec3 lVectorGround = -lVector;",
  11090. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11091. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11092. " float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  11093. " float dotProductGround = dot( normal, lVectorGround );",
  11094. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11095. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  11096. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVector, hemiHalfVectorSky ), 0.0 ), 5.0 );",
  11097. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( max( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 0.0 ), 5.0 );",
  11098. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11099. " }",
  11100. "#endif",
  11101. "vec3 totalDiffuse = vec3( 0.0 );",
  11102. "vec3 totalSpecular = vec3( 0.0 );",
  11103. "#if MAX_DIR_LIGHTS > 0",
  11104. " totalDiffuse += dirDiffuse;",
  11105. " totalSpecular += dirSpecular;",
  11106. "#endif",
  11107. "#if MAX_HEMI_LIGHTS > 0",
  11108. " totalDiffuse += hemiDiffuse;",
  11109. " totalSpecular += hemiSpecular;",
  11110. "#endif",
  11111. "#if MAX_POINT_LIGHTS > 0",
  11112. " totalDiffuse += pointDiffuse;",
  11113. " totalSpecular += pointSpecular;",
  11114. "#endif",
  11115. "#if MAX_SPOT_LIGHTS > 0",
  11116. " totalDiffuse += spotDiffuse;",
  11117. " totalSpecular += spotSpecular;",
  11118. "#endif",
  11119. "#ifdef METAL",
  11120. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  11121. "#else",
  11122. " gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  11123. "#endif"
  11124. ].join("\n"),
  11125. // VERTEX COLORS
  11126. color_pars_fragment: [
  11127. "#ifdef USE_COLOR",
  11128. " varying vec3 vColor;",
  11129. "#endif"
  11130. ].join("\n"),
  11131. color_fragment: [
  11132. "#ifdef USE_COLOR",
  11133. " gl_FragColor = gl_FragColor * vec4( vColor, 1.0 );",
  11134. "#endif"
  11135. ].join("\n"),
  11136. color_pars_vertex: [
  11137. "#ifdef USE_COLOR",
  11138. " varying vec3 vColor;",
  11139. "#endif"
  11140. ].join("\n"),
  11141. color_vertex: [
  11142. "#ifdef USE_COLOR",
  11143. " #ifdef GAMMA_INPUT",
  11144. " vColor = color * color;",
  11145. " #else",
  11146. " vColor = color;",
  11147. " #endif",
  11148. "#endif"
  11149. ].join("\n"),
  11150. // SKINNING
  11151. skinning_pars_vertex: [
  11152. "#ifdef USE_SKINNING",
  11153. " #ifdef BONE_TEXTURE",
  11154. " uniform sampler2D boneTexture;",
  11155. " uniform int boneTextureWidth;",
  11156. " uniform int boneTextureHeight;",
  11157. " mat4 getBoneMatrix( const in float i ) {",
  11158. " float j = i * 4.0;",
  11159. " float x = mod( j, float( boneTextureWidth ) );",
  11160. " float y = floor( j / float( boneTextureWidth ) );",
  11161. " float dx = 1.0 / float( boneTextureWidth );",
  11162. " float dy = 1.0 / float( boneTextureHeight );",
  11163. " y = dy * ( y + 0.5 );",
  11164. " vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  11165. " vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  11166. " vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  11167. " vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  11168. " mat4 bone = mat4( v1, v2, v3, v4 );",
  11169. " return bone;",
  11170. " }",
  11171. " #else",
  11172. " uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  11173. " mat4 getBoneMatrix( const in float i ) {",
  11174. " mat4 bone = boneGlobalMatrices[ int(i) ];",
  11175. " return bone;",
  11176. " }",
  11177. " #endif",
  11178. "#endif"
  11179. ].join("\n"),
  11180. skinbase_vertex: [
  11181. "#ifdef USE_SKINNING",
  11182. " mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  11183. " mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  11184. " mat4 boneMatZ = getBoneMatrix( skinIndex.z );",
  11185. " mat4 boneMatW = getBoneMatrix( skinIndex.w );",
  11186. "#endif"
  11187. ].join("\n"),
  11188. skinning_vertex: [
  11189. "#ifdef USE_SKINNING",
  11190. " #ifdef USE_MORPHTARGETS",
  11191. " vec4 skinVertex = vec4( morphed, 1.0 );",
  11192. " #else",
  11193. " vec4 skinVertex = vec4( position, 1.0 );",
  11194. " #endif",
  11195. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11196. " skinned += boneMatY * skinVertex * skinWeight.y;",
  11197. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  11198. " skinned += boneMatW * skinVertex * skinWeight.w;",
  11199. "#endif"
  11200. ].join("\n"),
  11201. // MORPHING
  11202. morphtarget_pars_vertex: [
  11203. "#ifdef USE_MORPHTARGETS",
  11204. " #ifndef USE_MORPHNORMALS",
  11205. " uniform float morphTargetInfluences[ 8 ];",
  11206. " #else",
  11207. " uniform float morphTargetInfluences[ 4 ];",
  11208. " #endif",
  11209. "#endif"
  11210. ].join("\n"),
  11211. morphtarget_vertex: [
  11212. "#ifdef USE_MORPHTARGETS",
  11213. " vec3 morphed = vec3( 0.0 );",
  11214. " morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  11215. " morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  11216. " morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  11217. " morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  11218. " #ifndef USE_MORPHNORMALS",
  11219. " morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  11220. " morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  11221. " morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  11222. " morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  11223. " #endif",
  11224. " morphed += position;",
  11225. "#endif"
  11226. ].join("\n"),
  11227. default_vertex : [
  11228. "vec4 mvPosition;",
  11229. "#ifdef USE_SKINNING",
  11230. " mvPosition = modelViewMatrix * skinned;",
  11231. "#endif",
  11232. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  11233. " mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  11234. "#endif",
  11235. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  11236. " mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11237. "#endif",
  11238. "gl_Position = projectionMatrix * mvPosition;"
  11239. ].join("\n"),
  11240. morphnormal_vertex: [
  11241. "#ifdef USE_MORPHNORMALS",
  11242. " vec3 morphedNormal = vec3( 0.0 );",
  11243. " morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  11244. " morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  11245. " morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  11246. " morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  11247. " morphedNormal += normal;",
  11248. "#endif"
  11249. ].join("\n"),
  11250. skinnormal_vertex: [
  11251. "#ifdef USE_SKINNING",
  11252. " mat4 skinMatrix = skinWeight.x * boneMatX;",
  11253. " skinMatrix += skinWeight.y * boneMatY;",
  11254. " skinMatrix += skinWeight.z * boneMatZ;",
  11255. " skinMatrix += skinWeight.w * boneMatW;",
  11256. " #ifdef USE_MORPHNORMALS",
  11257. " vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  11258. " #else",
  11259. " vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  11260. " #endif",
  11261. "#endif"
  11262. ].join("\n"),
  11263. defaultnormal_vertex: [
  11264. "vec3 objectNormal;",
  11265. "#ifdef USE_SKINNING",
  11266. " objectNormal = skinnedNormal.xyz;",
  11267. "#endif",
  11268. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  11269. " objectNormal = morphedNormal;",
  11270. "#endif",
  11271. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  11272. " objectNormal = normal;",
  11273. "#endif",
  11274. "#ifdef FLIP_SIDED",
  11275. " objectNormal = -objectNormal;",
  11276. "#endif",
  11277. "vec3 transformedNormal = normalMatrix * objectNormal;"
  11278. ].join("\n"),
  11279. // SHADOW MAP
  11280. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  11281. // http://spidergl.org/example.php?id=6
  11282. // http://fabiensanglard.net/shadowmapping
  11283. shadowmap_pars_fragment: [
  11284. "#ifdef USE_SHADOWMAP",
  11285. " uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  11286. " uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  11287. " uniform float shadowDarkness[ MAX_SHADOWS ];",
  11288. " uniform float shadowBias[ MAX_SHADOWS ];",
  11289. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11290. " float unpackDepth( const in vec4 rgba_depth ) {",
  11291. " 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 );",
  11292. " float depth = dot( rgba_depth, bit_shift );",
  11293. " return depth;",
  11294. " }",
  11295. "#endif"
  11296. ].join("\n"),
  11297. shadowmap_fragment: [
  11298. "#ifdef USE_SHADOWMAP",
  11299. " #ifdef SHADOWMAP_DEBUG",
  11300. " vec3 frustumColors[3];",
  11301. " frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  11302. " frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  11303. " frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  11304. " #endif",
  11305. " #ifdef SHADOWMAP_CASCADE",
  11306. " int inFrustumCount = 0;",
  11307. " #endif",
  11308. " float fDepth;",
  11309. " vec3 shadowColor = vec3( 1.0 );",
  11310. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11311. " vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  11312. // "if ( something && something )" breaks ATI OpenGL shader compiler
  11313. // "if ( all( something, something ) )" using this instead
  11314. " bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  11315. " bool inFrustum = all( inFrustumVec );",
  11316. // don't shadow pixels outside of light frustum
  11317. // use just first frustum (for cascades)
  11318. // don't shadow pixels behind far plane of light frustum
  11319. " #ifdef SHADOWMAP_CASCADE",
  11320. " inFrustumCount += int( inFrustum );",
  11321. " bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  11322. " #else",
  11323. " bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  11324. " #endif",
  11325. " bool frustumTest = all( frustumTestVec );",
  11326. " if ( frustumTest ) {",
  11327. " shadowCoord.z += shadowBias[ i ];",
  11328. " #if defined( SHADOWMAP_TYPE_PCF )",
  11329. // Percentage-close filtering
  11330. // (9 pixel kernel)
  11331. // http://fabiensanglard.net/shadowmappingPCF/
  11332. " float shadow = 0.0;",
  11333. /*
  11334. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  11335. // must enroll loop manually
  11336. " for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  11337. " for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  11338. " vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  11339. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  11340. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  11341. " float fDepth = unpackDepth( rgbaDepth );",
  11342. " if ( fDepth < shadowCoord.z )",
  11343. " shadow += 1.0;",
  11344. " }",
  11345. " shadow /= 9.0;",
  11346. */
  11347. " const float shadowDelta = 1.0 / 9.0;",
  11348. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11349. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11350. " float dx0 = -1.25 * xPixelOffset;",
  11351. " float dy0 = -1.25 * yPixelOffset;",
  11352. " float dx1 = 1.25 * xPixelOffset;",
  11353. " float dy1 = 1.25 * yPixelOffset;",
  11354. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11355. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11356. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11357. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11358. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11359. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11360. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11361. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11362. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11363. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11364. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11365. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11366. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11367. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11368. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11369. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11370. " fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11371. " if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  11372. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11373. " #elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  11374. // Percentage-close filtering
  11375. // (9 pixel kernel)
  11376. // http://fabiensanglard.net/shadowmappingPCF/
  11377. " float shadow = 0.0;",
  11378. " float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  11379. " float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  11380. " float dx0 = -1.0 * xPixelOffset;",
  11381. " float dy0 = -1.0 * yPixelOffset;",
  11382. " float dx1 = 1.0 * xPixelOffset;",
  11383. " float dy1 = 1.0 * yPixelOffset;",
  11384. " mat3 shadowKernel;",
  11385. " mat3 depthKernel;",
  11386. " depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  11387. " depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  11388. " depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  11389. " depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  11390. " depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  11391. " depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  11392. " depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  11393. " depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  11394. " depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  11395. " vec3 shadowZ = vec3( shadowCoord.z );",
  11396. " shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  11397. " shadowKernel[0] *= vec3(0.25);",
  11398. " shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  11399. " shadowKernel[1] *= vec3(0.25);",
  11400. " shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  11401. " shadowKernel[2] *= vec3(0.25);",
  11402. " vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  11403. " shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  11404. " shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  11405. " vec4 shadowValues;",
  11406. " shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  11407. " shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  11408. " shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  11409. " shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  11410. " shadow = dot( shadowValues, vec4( 1.0 ) );",
  11411. " shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  11412. " #else",
  11413. " vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  11414. " float fDepth = unpackDepth( rgbaDepth );",
  11415. " if ( fDepth < shadowCoord.z )",
  11416. // spot with multiple shadows is darker
  11417. " shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  11418. // spot with multiple shadows has the same color as single shadow spot
  11419. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  11420. " #endif",
  11421. " }",
  11422. " #ifdef SHADOWMAP_DEBUG",
  11423. " #ifdef SHADOWMAP_CASCADE",
  11424. " if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  11425. " #else",
  11426. " if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  11427. " #endif",
  11428. " #endif",
  11429. " }",
  11430. " #ifdef GAMMA_OUTPUT",
  11431. " shadowColor *= shadowColor;",
  11432. " #endif",
  11433. " gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  11434. "#endif"
  11435. ].join("\n"),
  11436. shadowmap_pars_vertex: [
  11437. "#ifdef USE_SHADOWMAP",
  11438. " varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  11439. " uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  11440. "#endif"
  11441. ].join("\n"),
  11442. shadowmap_vertex: [
  11443. "#ifdef USE_SHADOWMAP",
  11444. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11445. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11446. " }",
  11447. "#endif"
  11448. ].join("\n"),
  11449. // ALPHATEST
  11450. alphatest_fragment: [
  11451. "#ifdef ALPHATEST",
  11452. " if ( gl_FragColor.a < ALPHATEST ) discard;",
  11453. "#endif"
  11454. ].join("\n"),
  11455. // LINEAR SPACE
  11456. linear_to_gamma_fragment: [
  11457. "#ifdef GAMMA_OUTPUT",
  11458. " gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  11459. "#endif"
  11460. ].join("\n"),
  11461. // LOGARITHMIC DEPTH BUFFER
  11462. // http://outerra.blogspot.com/2012/11/maximizing-depth-buffer-range-and.html
  11463. // WebGL doesn't support gl_FragDepth out of the box, unless the EXT_frag_depth extension is available. On platforms
  11464. // without EXT_frag_depth, we have to fall back on linear z-buffer in the fragment shader, which means that some long
  11465. // faces close to the camera may have issues. This can be worked around by tesselating the model more finely when
  11466. // the camera is near the surface.
  11467. logdepthbuf_pars_vertex: [
  11468. "#ifdef USE_LOGDEPTHBUF",
  11469. " #ifdef USE_LOGDEPTHBUF_EXT",
  11470. " varying float vFragDepth;",
  11471. " #endif",
  11472. " uniform float logDepthBufFC;",
  11473. "#endif",
  11474. ].join('\n'),
  11475. logdepthbuf_vertex: [
  11476. "#ifdef USE_LOGDEPTHBUF",
  11477. " gl_Position.z = log2(max(1e-6, gl_Position.w + 1.0)) * logDepthBufFC;",
  11478. " #ifdef USE_LOGDEPTHBUF_EXT",
  11479. " vFragDepth = 1.0 + gl_Position.w;",
  11480. "#else",
  11481. " gl_Position.z = (gl_Position.z - 1.0) * gl_Position.w;",
  11482. " #endif",
  11483. "#endif"
  11484. ].join("\n"),
  11485. logdepthbuf_pars_fragment: [
  11486. "#ifdef USE_LOGDEPTHBUF",
  11487. " uniform float logDepthBufFC;",
  11488. " #ifdef USE_LOGDEPTHBUF_EXT",
  11489. " #extension GL_EXT_frag_depth : enable",
  11490. " varying float vFragDepth;",
  11491. " #endif",
  11492. "#endif"
  11493. ].join('\n'),
  11494. logdepthbuf_fragment: [
  11495. "#if defined(USE_LOGDEPTHBUF) && defined(USE_LOGDEPTHBUF_EXT)",
  11496. " gl_FragDepthEXT = log2(vFragDepth) * logDepthBufFC * 0.5;",
  11497. "#endif"
  11498. ].join("\n")
  11499. };
  11500. /**
  11501. * Uniform Utilities
  11502. */
  11503. THREE.UniformsUtils = {
  11504. merge: function ( uniforms ) {
  11505. var u, p, tmp, merged = {};
  11506. for ( u = 0; u < uniforms.length; u ++ ) {
  11507. tmp = this.clone( uniforms[ u ] );
  11508. for ( p in tmp ) {
  11509. merged[ p ] = tmp[ p ];
  11510. }
  11511. }
  11512. return merged;
  11513. },
  11514. clone: function ( uniforms_src ) {
  11515. var u, p, parameter, parameter_src, uniforms_dst = {};
  11516. for ( u in uniforms_src ) {
  11517. uniforms_dst[ u ] = {};
  11518. for ( p in uniforms_src[ u ] ) {
  11519. parameter_src = uniforms_src[ u ][ p ];
  11520. if ( parameter_src instanceof THREE.Color ||
  11521. parameter_src instanceof THREE.Vector2 ||
  11522. parameter_src instanceof THREE.Vector3 ||
  11523. parameter_src instanceof THREE.Vector4 ||
  11524. parameter_src instanceof THREE.Matrix4 ||
  11525. parameter_src instanceof THREE.Texture ) {
  11526. uniforms_dst[ u ][ p ] = parameter_src.clone();
  11527. } else if ( parameter_src instanceof Array ) {
  11528. uniforms_dst[ u ][ p ] = parameter_src.slice();
  11529. } else {
  11530. uniforms_dst[ u ][ p ] = parameter_src;
  11531. }
  11532. }
  11533. }
  11534. return uniforms_dst;
  11535. }
  11536. };
  11537. /**
  11538. * Uniforms library for shared webgl shaders
  11539. */
  11540. THREE.UniformsLib = {
  11541. common: {
  11542. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11543. "opacity" : { type: "f", value: 1.0 },
  11544. "map" : { type: "t", value: null },
  11545. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  11546. "lightMap" : { type: "t", value: null },
  11547. "specularMap" : { type: "t", value: null },
  11548. "envMap" : { type: "t", value: null },
  11549. "flipEnvMap" : { type: "f", value: -1 },
  11550. "useRefract" : { type: "i", value: 0 },
  11551. "reflectivity" : { type: "f", value: 1.0 },
  11552. "refractionRatio" : { type: "f", value: 0.98 },
  11553. "combine" : { type: "i", value: 0 },
  11554. "morphTargetInfluences" : { type: "f", value: 0 }
  11555. },
  11556. bump: {
  11557. "bumpMap" : { type: "t", value: null },
  11558. "bumpScale" : { type: "f", value: 1 }
  11559. },
  11560. normalmap: {
  11561. "normalMap" : { type: "t", value: null },
  11562. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  11563. },
  11564. fog : {
  11565. "fogDensity" : { type: "f", value: 0.00025 },
  11566. "fogNear" : { type: "f", value: 1 },
  11567. "fogFar" : { type: "f", value: 2000 },
  11568. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11569. },
  11570. lights: {
  11571. "ambientLightColor" : { type: "fv", value: [] },
  11572. "directionalLightDirection" : { type: "fv", value: [] },
  11573. "directionalLightColor" : { type: "fv", value: [] },
  11574. "hemisphereLightDirection" : { type: "fv", value: [] },
  11575. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  11576. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  11577. "pointLightColor" : { type: "fv", value: [] },
  11578. "pointLightPosition" : { type: "fv", value: [] },
  11579. "pointLightDistance" : { type: "fv1", value: [] },
  11580. "spotLightColor" : { type: "fv", value: [] },
  11581. "spotLightPosition" : { type: "fv", value: [] },
  11582. "spotLightDirection" : { type: "fv", value: [] },
  11583. "spotLightDistance" : { type: "fv1", value: [] },
  11584. "spotLightAngleCos" : { type: "fv1", value: [] },
  11585. "spotLightExponent" : { type: "fv1", value: [] }
  11586. },
  11587. particle: {
  11588. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  11589. "opacity" : { type: "f", value: 1.0 },
  11590. "size" : { type: "f", value: 1.0 },
  11591. "scale" : { type: "f", value: 1.0 },
  11592. "map" : { type: "t", value: null },
  11593. "fogDensity" : { type: "f", value: 0.00025 },
  11594. "fogNear" : { type: "f", value: 1 },
  11595. "fogFar" : { type: "f", value: 2000 },
  11596. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  11597. },
  11598. shadowmap: {
  11599. "shadowMap": { type: "tv", value: [] },
  11600. "shadowMapSize": { type: "v2v", value: [] },
  11601. "shadowBias" : { type: "fv1", value: [] },
  11602. "shadowDarkness": { type: "fv1", value: [] },
  11603. "shadowMatrix" : { type: "m4v", value: [] }
  11604. }
  11605. };
  11606. /**
  11607. * Webgl Shader Library for three.js
  11608. *
  11609. * @author alteredq / http://alteredqualia.com/
  11610. * @author mrdoob / http://mrdoob.com/
  11611. * @author mikael emtinger / http://gomo.se/
  11612. */
  11613. THREE.ShaderLib = {
  11614. 'basic': {
  11615. uniforms: THREE.UniformsUtils.merge( [
  11616. THREE.UniformsLib[ "common" ],
  11617. THREE.UniformsLib[ "fog" ],
  11618. THREE.UniformsLib[ "shadowmap" ]
  11619. ] ),
  11620. vertexShader: [
  11621. THREE.ShaderChunk[ "map_pars_vertex" ],
  11622. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11623. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11624. THREE.ShaderChunk[ "color_pars_vertex" ],
  11625. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11626. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11627. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11628. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11629. "void main() {",
  11630. THREE.ShaderChunk[ "map_vertex" ],
  11631. THREE.ShaderChunk[ "lightmap_vertex" ],
  11632. THREE.ShaderChunk[ "color_vertex" ],
  11633. THREE.ShaderChunk[ "skinbase_vertex" ],
  11634. " #ifdef USE_ENVMAP",
  11635. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11636. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11637. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11638. " #endif",
  11639. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11640. THREE.ShaderChunk[ "skinning_vertex" ],
  11641. THREE.ShaderChunk[ "default_vertex" ],
  11642. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11643. THREE.ShaderChunk[ "worldpos_vertex" ],
  11644. THREE.ShaderChunk[ "envmap_vertex" ],
  11645. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11646. "}"
  11647. ].join("\n"),
  11648. fragmentShader: [
  11649. "uniform vec3 diffuse;",
  11650. "uniform float opacity;",
  11651. THREE.ShaderChunk[ "color_pars_fragment" ],
  11652. THREE.ShaderChunk[ "map_pars_fragment" ],
  11653. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11654. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11655. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11656. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11657. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11658. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11659. "void main() {",
  11660. " gl_FragColor = vec4( diffuse, opacity );",
  11661. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11662. THREE.ShaderChunk[ "map_fragment" ],
  11663. THREE.ShaderChunk[ "alphatest_fragment" ],
  11664. THREE.ShaderChunk[ "specularmap_fragment" ],
  11665. THREE.ShaderChunk[ "lightmap_fragment" ],
  11666. THREE.ShaderChunk[ "color_fragment" ],
  11667. THREE.ShaderChunk[ "envmap_fragment" ],
  11668. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11669. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11670. THREE.ShaderChunk[ "fog_fragment" ],
  11671. "}"
  11672. ].join("\n")
  11673. },
  11674. 'lambert': {
  11675. uniforms: THREE.UniformsUtils.merge( [
  11676. THREE.UniformsLib[ "common" ],
  11677. THREE.UniformsLib[ "fog" ],
  11678. THREE.UniformsLib[ "lights" ],
  11679. THREE.UniformsLib[ "shadowmap" ],
  11680. {
  11681. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11682. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11683. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11684. }
  11685. ] ),
  11686. vertexShader: [
  11687. "#define LAMBERT",
  11688. "varying vec3 vLightFront;",
  11689. "#ifdef DOUBLE_SIDED",
  11690. " varying vec3 vLightBack;",
  11691. "#endif",
  11692. THREE.ShaderChunk[ "map_pars_vertex" ],
  11693. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11694. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11695. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  11696. THREE.ShaderChunk[ "color_pars_vertex" ],
  11697. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11698. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11699. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11700. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11701. "void main() {",
  11702. THREE.ShaderChunk[ "map_vertex" ],
  11703. THREE.ShaderChunk[ "lightmap_vertex" ],
  11704. THREE.ShaderChunk[ "color_vertex" ],
  11705. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11706. THREE.ShaderChunk[ "skinbase_vertex" ],
  11707. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11708. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11709. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11710. THREE.ShaderChunk[ "skinning_vertex" ],
  11711. THREE.ShaderChunk[ "default_vertex" ],
  11712. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11713. THREE.ShaderChunk[ "worldpos_vertex" ],
  11714. THREE.ShaderChunk[ "envmap_vertex" ],
  11715. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  11716. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11717. "}"
  11718. ].join("\n"),
  11719. fragmentShader: [
  11720. "uniform float opacity;",
  11721. "varying vec3 vLightFront;",
  11722. "#ifdef DOUBLE_SIDED",
  11723. " varying vec3 vLightBack;",
  11724. "#endif",
  11725. THREE.ShaderChunk[ "color_pars_fragment" ],
  11726. THREE.ShaderChunk[ "map_pars_fragment" ],
  11727. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11728. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11729. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11730. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11731. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11732. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11733. "void main() {",
  11734. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11735. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11736. THREE.ShaderChunk[ "map_fragment" ],
  11737. THREE.ShaderChunk[ "alphatest_fragment" ],
  11738. THREE.ShaderChunk[ "specularmap_fragment" ],
  11739. " #ifdef DOUBLE_SIDED",
  11740. //"float isFront = float( gl_FrontFacing );",
  11741. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  11742. " if ( gl_FrontFacing )",
  11743. " gl_FragColor.xyz *= vLightFront;",
  11744. " else",
  11745. " gl_FragColor.xyz *= vLightBack;",
  11746. " #else",
  11747. " gl_FragColor.xyz *= vLightFront;",
  11748. " #endif",
  11749. THREE.ShaderChunk[ "lightmap_fragment" ],
  11750. THREE.ShaderChunk[ "color_fragment" ],
  11751. THREE.ShaderChunk[ "envmap_fragment" ],
  11752. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11753. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11754. THREE.ShaderChunk[ "fog_fragment" ],
  11755. "}"
  11756. ].join("\n")
  11757. },
  11758. 'phong': {
  11759. uniforms: THREE.UniformsUtils.merge( [
  11760. THREE.UniformsLib[ "common" ],
  11761. THREE.UniformsLib[ "bump" ],
  11762. THREE.UniformsLib[ "normalmap" ],
  11763. THREE.UniformsLib[ "fog" ],
  11764. THREE.UniformsLib[ "lights" ],
  11765. THREE.UniformsLib[ "shadowmap" ],
  11766. {
  11767. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  11768. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  11769. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  11770. "shininess": { type: "f", value: 30 },
  11771. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11772. }
  11773. ] ),
  11774. vertexShader: [
  11775. "#define PHONG",
  11776. "varying vec3 vViewPosition;",
  11777. "varying vec3 vNormal;",
  11778. THREE.ShaderChunk[ "map_pars_vertex" ],
  11779. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  11780. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  11781. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  11782. THREE.ShaderChunk[ "color_pars_vertex" ],
  11783. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11784. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11785. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11786. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11787. "void main() {",
  11788. THREE.ShaderChunk[ "map_vertex" ],
  11789. THREE.ShaderChunk[ "lightmap_vertex" ],
  11790. THREE.ShaderChunk[ "color_vertex" ],
  11791. THREE.ShaderChunk[ "morphnormal_vertex" ],
  11792. THREE.ShaderChunk[ "skinbase_vertex" ],
  11793. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11794. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  11795. " vNormal = normalize( transformedNormal );",
  11796. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11797. THREE.ShaderChunk[ "skinning_vertex" ],
  11798. THREE.ShaderChunk[ "default_vertex" ],
  11799. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11800. " vViewPosition = -mvPosition.xyz;",
  11801. THREE.ShaderChunk[ "worldpos_vertex" ],
  11802. THREE.ShaderChunk[ "envmap_vertex" ],
  11803. THREE.ShaderChunk[ "lights_phong_vertex" ],
  11804. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11805. "}"
  11806. ].join("\n"),
  11807. fragmentShader: [
  11808. "uniform vec3 diffuse;",
  11809. "uniform float opacity;",
  11810. "uniform vec3 ambient;",
  11811. "uniform vec3 emissive;",
  11812. "uniform vec3 specular;",
  11813. "uniform float shininess;",
  11814. THREE.ShaderChunk[ "color_pars_fragment" ],
  11815. THREE.ShaderChunk[ "map_pars_fragment" ],
  11816. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  11817. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  11818. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11819. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  11820. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11821. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  11822. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  11823. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  11824. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11825. "void main() {",
  11826. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  11827. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11828. THREE.ShaderChunk[ "map_fragment" ],
  11829. THREE.ShaderChunk[ "alphatest_fragment" ],
  11830. THREE.ShaderChunk[ "specularmap_fragment" ],
  11831. THREE.ShaderChunk[ "lights_phong_fragment" ],
  11832. THREE.ShaderChunk[ "lightmap_fragment" ],
  11833. THREE.ShaderChunk[ "color_fragment" ],
  11834. THREE.ShaderChunk[ "envmap_fragment" ],
  11835. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11836. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11837. THREE.ShaderChunk[ "fog_fragment" ],
  11838. "}"
  11839. ].join("\n")
  11840. },
  11841. 'particle_basic': {
  11842. uniforms: THREE.UniformsUtils.merge( [
  11843. THREE.UniformsLib[ "particle" ],
  11844. THREE.UniformsLib[ "shadowmap" ]
  11845. ] ),
  11846. vertexShader: [
  11847. "uniform float size;",
  11848. "uniform float scale;",
  11849. THREE.ShaderChunk[ "color_pars_vertex" ],
  11850. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11851. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11852. "void main() {",
  11853. THREE.ShaderChunk[ "color_vertex" ],
  11854. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11855. " #ifdef USE_SIZEATTENUATION",
  11856. " gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  11857. " #else",
  11858. " gl_PointSize = size;",
  11859. " #endif",
  11860. " gl_Position = projectionMatrix * mvPosition;",
  11861. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11862. THREE.ShaderChunk[ "worldpos_vertex" ],
  11863. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11864. "}"
  11865. ].join("\n"),
  11866. fragmentShader: [
  11867. "uniform vec3 psColor;",
  11868. "uniform float opacity;",
  11869. THREE.ShaderChunk[ "color_pars_fragment" ],
  11870. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  11871. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11872. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11873. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11874. "void main() {",
  11875. " gl_FragColor = vec4( psColor, opacity );",
  11876. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11877. THREE.ShaderChunk[ "map_particle_fragment" ],
  11878. THREE.ShaderChunk[ "alphatest_fragment" ],
  11879. THREE.ShaderChunk[ "color_fragment" ],
  11880. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11881. THREE.ShaderChunk[ "fog_fragment" ],
  11882. "}"
  11883. ].join("\n")
  11884. },
  11885. 'dashed': {
  11886. uniforms: THREE.UniformsUtils.merge( [
  11887. THREE.UniformsLib[ "common" ],
  11888. THREE.UniformsLib[ "fog" ],
  11889. {
  11890. "scale": { type: "f", value: 1 },
  11891. "dashSize": { type: "f", value: 1 },
  11892. "totalSize": { type: "f", value: 2 }
  11893. }
  11894. ] ),
  11895. vertexShader: [
  11896. "uniform float scale;",
  11897. "attribute float lineDistance;",
  11898. "varying float vLineDistance;",
  11899. THREE.ShaderChunk[ "color_pars_vertex" ],
  11900. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11901. "void main() {",
  11902. THREE.ShaderChunk[ "color_vertex" ],
  11903. " vLineDistance = scale * lineDistance;",
  11904. " vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11905. " gl_Position = projectionMatrix * mvPosition;",
  11906. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11907. "}"
  11908. ].join("\n"),
  11909. fragmentShader: [
  11910. "uniform vec3 diffuse;",
  11911. "uniform float opacity;",
  11912. "uniform float dashSize;",
  11913. "uniform float totalSize;",
  11914. "varying float vLineDistance;",
  11915. THREE.ShaderChunk[ "color_pars_fragment" ],
  11916. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11917. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11918. "void main() {",
  11919. " if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  11920. " discard;",
  11921. " }",
  11922. " gl_FragColor = vec4( diffuse, opacity );",
  11923. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11924. THREE.ShaderChunk[ "color_fragment" ],
  11925. THREE.ShaderChunk[ "fog_fragment" ],
  11926. "}"
  11927. ].join("\n")
  11928. },
  11929. 'depth': {
  11930. uniforms: {
  11931. "mNear": { type: "f", value: 1.0 },
  11932. "mFar" : { type: "f", value: 2000.0 },
  11933. "opacity" : { type: "f", value: 1.0 }
  11934. },
  11935. vertexShader: [
  11936. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11937. "void main() {",
  11938. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11939. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11940. "}"
  11941. ].join("\n"),
  11942. fragmentShader: [
  11943. "uniform float mNear;",
  11944. "uniform float mFar;",
  11945. "uniform float opacity;",
  11946. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11947. "void main() {",
  11948. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11949. " #ifdef USE_LOGDEPTHBUF_EXT",
  11950. " float depth = gl_FragDepthEXT / gl_FragCoord.w;",
  11951. " #else",
  11952. " float depth = gl_FragCoord.z / gl_FragCoord.w;",
  11953. " #endif",
  11954. " float color = 1.0 - smoothstep( mNear, mFar, depth );",
  11955. " gl_FragColor = vec4( vec3( color ), opacity );",
  11956. "}"
  11957. ].join("\n")
  11958. },
  11959. 'normal': {
  11960. uniforms: {
  11961. "opacity" : { type: "f", value: 1.0 }
  11962. },
  11963. vertexShader: [
  11964. "varying vec3 vNormal;",
  11965. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11966. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  11967. "void main() {",
  11968. " vNormal = normalize( normalMatrix * normal );",
  11969. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11970. THREE.ShaderChunk[ "default_vertex" ],
  11971. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  11972. "}"
  11973. ].join("\n"),
  11974. fragmentShader: [
  11975. "uniform float opacity;",
  11976. "varying vec3 vNormal;",
  11977. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  11978. "void main() {",
  11979. " gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  11980. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  11981. "}"
  11982. ].join("\n")
  11983. },
  11984. /* -------------------------------------------------------------------------
  11985. // Normal map shader
  11986. // - Blinn-Phong
  11987. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  11988. // - point and directional lights (use with "lights: true" material option)
  11989. ------------------------------------------------------------------------- */
  11990. 'normalmap' : {
  11991. uniforms: THREE.UniformsUtils.merge( [
  11992. THREE.UniformsLib[ "fog" ],
  11993. THREE.UniformsLib[ "lights" ],
  11994. THREE.UniformsLib[ "shadowmap" ],
  11995. {
  11996. "enableAO" : { type: "i", value: 0 },
  11997. "enableDiffuse" : { type: "i", value: 0 },
  11998. "enableSpecular" : { type: "i", value: 0 },
  11999. "enableReflection": { type: "i", value: 0 },
  12000. "enableDisplacement": { type: "i", value: 0 },
  12001. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  12002. "tDiffuse" : { type: "t", value: null },
  12003. "tCube" : { type: "t", value: null },
  12004. "tNormal" : { type: "t", value: null },
  12005. "tSpecular" : { type: "t", value: null },
  12006. "tAO" : { type: "t", value: null },
  12007. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  12008. "uDisplacementBias": { type: "f", value: 0.0 },
  12009. "uDisplacementScale": { type: "f", value: 1.0 },
  12010. "diffuse": { type: "c", value: new THREE.Color( 0xffffff ) },
  12011. "specular": { type: "c", value: new THREE.Color( 0x111111 ) },
  12012. "ambient": { type: "c", value: new THREE.Color( 0xffffff ) },
  12013. "shininess": { type: "f", value: 30 },
  12014. "opacity": { type: "f", value: 1 },
  12015. "useRefract": { type: "i", value: 0 },
  12016. "refractionRatio": { type: "f", value: 0.98 },
  12017. "reflectivity": { type: "f", value: 0.5 },
  12018. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  12019. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  12020. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  12021. }
  12022. ] ),
  12023. fragmentShader: [
  12024. "uniform vec3 ambient;",
  12025. "uniform vec3 diffuse;",
  12026. "uniform vec3 specular;",
  12027. "uniform float shininess;",
  12028. "uniform float opacity;",
  12029. "uniform bool enableDiffuse;",
  12030. "uniform bool enableSpecular;",
  12031. "uniform bool enableAO;",
  12032. "uniform bool enableReflection;",
  12033. "uniform sampler2D tDiffuse;",
  12034. "uniform sampler2D tNormal;",
  12035. "uniform sampler2D tSpecular;",
  12036. "uniform sampler2D tAO;",
  12037. "uniform samplerCube tCube;",
  12038. "uniform vec2 uNormalScale;",
  12039. "uniform bool useRefract;",
  12040. "uniform float refractionRatio;",
  12041. "uniform float reflectivity;",
  12042. "varying vec3 vTangent;",
  12043. "varying vec3 vBinormal;",
  12044. "varying vec3 vNormal;",
  12045. "varying vec2 vUv;",
  12046. "uniform vec3 ambientLightColor;",
  12047. "#if MAX_DIR_LIGHTS > 0",
  12048. " uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  12049. " uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  12050. "#endif",
  12051. "#if MAX_HEMI_LIGHTS > 0",
  12052. " uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  12053. " uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  12054. " uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  12055. "#endif",
  12056. "#if MAX_POINT_LIGHTS > 0",
  12057. " uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  12058. " uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  12059. " uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  12060. "#endif",
  12061. "#if MAX_SPOT_LIGHTS > 0",
  12062. " uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  12063. " uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  12064. " uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  12065. " uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  12066. " uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  12067. " uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  12068. "#endif",
  12069. "#ifdef WRAP_AROUND",
  12070. " uniform vec3 wrapRGB;",
  12071. "#endif",
  12072. "varying vec3 vWorldPosition;",
  12073. "varying vec3 vViewPosition;",
  12074. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  12075. THREE.ShaderChunk[ "fog_pars_fragment" ],
  12076. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12077. "void main() {",
  12078. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12079. " gl_FragColor = vec4( vec3( 1.0 ), opacity );",
  12080. " vec3 specularTex = vec3( 1.0 );",
  12081. " vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  12082. " normalTex.xy *= uNormalScale;",
  12083. " normalTex = normalize( normalTex );",
  12084. " if( enableDiffuse ) {",
  12085. " #ifdef GAMMA_INPUT",
  12086. " vec4 texelColor = texture2D( tDiffuse, vUv );",
  12087. " texelColor.xyz *= texelColor.xyz;",
  12088. " gl_FragColor = gl_FragColor * texelColor;",
  12089. " #else",
  12090. " gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  12091. " #endif",
  12092. " }",
  12093. " if( enableAO ) {",
  12094. " #ifdef GAMMA_INPUT",
  12095. " vec4 aoColor = texture2D( tAO, vUv );",
  12096. " aoColor.xyz *= aoColor.xyz;",
  12097. " gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  12098. " #else",
  12099. " gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  12100. " #endif",
  12101. " }",
  12102. " if( enableSpecular )",
  12103. " specularTex = texture2D( tSpecular, vUv ).xyz;",
  12104. " mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  12105. " vec3 finalNormal = tsb * normalTex;",
  12106. " #ifdef FLIP_SIDED",
  12107. " finalNormal = -finalNormal;",
  12108. " #endif",
  12109. " vec3 normal = normalize( finalNormal );",
  12110. " vec3 viewPosition = normalize( vViewPosition );",
  12111. // point lights
  12112. " #if MAX_POINT_LIGHTS > 0",
  12113. " vec3 pointDiffuse = vec3( 0.0 );",
  12114. " vec3 pointSpecular = vec3( 0.0 );",
  12115. " for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  12116. " vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  12117. " vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  12118. " float pointDistance = 1.0;",
  12119. " if ( pointLightDistance[ i ] > 0.0 )",
  12120. " pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  12121. " pointVector = normalize( pointVector );",
  12122. // diffuse
  12123. " #ifdef WRAP_AROUND",
  12124. " float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  12125. " float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  12126. " vec3 pointDiffuseWeight = mix( vec3( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  12127. " #else",
  12128. " float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  12129. " #endif",
  12130. " pointDiffuse += pointDistance * pointLightColor[ i ] * diffuse * pointDiffuseWeight;",
  12131. // specular
  12132. " vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  12133. " float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  12134. " float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  12135. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12136. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12137. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  12138. " pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  12139. " }",
  12140. " #endif",
  12141. // spot lights
  12142. " #if MAX_SPOT_LIGHTS > 0",
  12143. " vec3 spotDiffuse = vec3( 0.0 );",
  12144. " vec3 spotSpecular = vec3( 0.0 );",
  12145. " for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  12146. " vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  12147. " vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  12148. " float spotDistance = 1.0;",
  12149. " if ( spotLightDistance[ i ] > 0.0 )",
  12150. " spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  12151. " spotVector = normalize( spotVector );",
  12152. " float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  12153. " if ( spotEffect > spotLightAngleCos[ i ] ) {",
  12154. " spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  12155. // diffuse
  12156. " #ifdef WRAP_AROUND",
  12157. " float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  12158. " float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  12159. " vec3 spotDiffuseWeight = mix( vec3( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  12160. " #else",
  12161. " float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  12162. " #endif",
  12163. " spotDiffuse += spotDistance * spotLightColor[ i ] * diffuse * spotDiffuseWeight * spotEffect;",
  12164. // specular
  12165. " vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  12166. " float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  12167. " float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  12168. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12169. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12170. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  12171. " spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  12172. " }",
  12173. " }",
  12174. " #endif",
  12175. // directional lights
  12176. " #if MAX_DIR_LIGHTS > 0",
  12177. " vec3 dirDiffuse = vec3( 0.0 );",
  12178. " vec3 dirSpecular = vec3( 0.0 );",
  12179. " for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  12180. " vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  12181. " vec3 dirVector = normalize( lDirection.xyz );",
  12182. // diffuse
  12183. " #ifdef WRAP_AROUND",
  12184. " float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  12185. " float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  12186. " vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  12187. " #else",
  12188. " float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  12189. " #endif",
  12190. " dirDiffuse += directionalLightColor[ i ] * diffuse * dirDiffuseWeight;",
  12191. // specular
  12192. " vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  12193. " float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  12194. " float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  12195. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12196. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12197. " vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  12198. " dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  12199. " }",
  12200. " #endif",
  12201. // hemisphere lights
  12202. " #if MAX_HEMI_LIGHTS > 0",
  12203. " vec3 hemiDiffuse = vec3( 0.0 );",
  12204. " vec3 hemiSpecular = vec3( 0.0 );" ,
  12205. " for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  12206. " vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  12207. " vec3 lVector = normalize( lDirection.xyz );",
  12208. // diffuse
  12209. " float dotProduct = dot( normal, lVector );",
  12210. " float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  12211. " vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  12212. " hemiDiffuse += diffuse * hemiColor;",
  12213. // specular (sky light)
  12214. " vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  12215. " float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  12216. " float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  12217. // specular (ground light)
  12218. " vec3 lVectorGround = -lVector;",
  12219. " vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  12220. " float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  12221. " float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  12222. " float dotProductGround = dot( normal, lVectorGround );",
  12223. // 2.0 => 2.0001 is hack to work around ANGLE bug
  12224. " float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  12225. " vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  12226. " vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  12227. " hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  12228. " }",
  12229. " #endif",
  12230. // all lights contribution summation
  12231. " vec3 totalDiffuse = vec3( 0.0 );",
  12232. " vec3 totalSpecular = vec3( 0.0 );",
  12233. " #if MAX_DIR_LIGHTS > 0",
  12234. " totalDiffuse += dirDiffuse;",
  12235. " totalSpecular += dirSpecular;",
  12236. " #endif",
  12237. " #if MAX_HEMI_LIGHTS > 0",
  12238. " totalDiffuse += hemiDiffuse;",
  12239. " totalSpecular += hemiSpecular;",
  12240. " #endif",
  12241. " #if MAX_POINT_LIGHTS > 0",
  12242. " totalDiffuse += pointDiffuse;",
  12243. " totalSpecular += pointSpecular;",
  12244. " #endif",
  12245. " #if MAX_SPOT_LIGHTS > 0",
  12246. " totalDiffuse += spotDiffuse;",
  12247. " totalSpecular += spotSpecular;",
  12248. " #endif",
  12249. " #ifdef METAL",
  12250. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  12251. " #else",
  12252. " gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  12253. " #endif",
  12254. " if ( enableReflection ) {",
  12255. " vec3 vReflect;",
  12256. " vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  12257. " if ( useRefract ) {",
  12258. " vReflect = refract( cameraToVertex, normal, refractionRatio );",
  12259. " } else {",
  12260. " vReflect = reflect( cameraToVertex, normal );",
  12261. " }",
  12262. " vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  12263. " #ifdef GAMMA_INPUT",
  12264. " cubeColor.xyz *= cubeColor.xyz;",
  12265. " #endif",
  12266. " gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * reflectivity );",
  12267. " }",
  12268. THREE.ShaderChunk[ "shadowmap_fragment" ],
  12269. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  12270. THREE.ShaderChunk[ "fog_fragment" ],
  12271. "}"
  12272. ].join("\n"),
  12273. vertexShader: [
  12274. "attribute vec4 tangent;",
  12275. "uniform vec2 uOffset;",
  12276. "uniform vec2 uRepeat;",
  12277. "uniform bool enableDisplacement;",
  12278. "#ifdef VERTEX_TEXTURES",
  12279. " uniform sampler2D tDisplacement;",
  12280. " uniform float uDisplacementScale;",
  12281. " uniform float uDisplacementBias;",
  12282. "#endif",
  12283. "varying vec3 vTangent;",
  12284. "varying vec3 vBinormal;",
  12285. "varying vec3 vNormal;",
  12286. "varying vec2 vUv;",
  12287. "varying vec3 vWorldPosition;",
  12288. "varying vec3 vViewPosition;",
  12289. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12290. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  12291. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12292. "void main() {",
  12293. THREE.ShaderChunk[ "skinbase_vertex" ],
  12294. THREE.ShaderChunk[ "skinnormal_vertex" ],
  12295. // normal, tangent and binormal vectors
  12296. " #ifdef USE_SKINNING",
  12297. " vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  12298. " vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  12299. " vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  12300. " #else",
  12301. " vNormal = normalize( normalMatrix * normal );",
  12302. " vTangent = normalize( normalMatrix * tangent.xyz );",
  12303. " #endif",
  12304. " vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  12305. " vUv = uv * uRepeat + uOffset;",
  12306. // displacement mapping
  12307. " vec3 displacedPosition;",
  12308. " #ifdef VERTEX_TEXTURES",
  12309. " if ( enableDisplacement ) {",
  12310. " vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  12311. " float df = uDisplacementScale * dv.x + uDisplacementBias;",
  12312. " displacedPosition = position + normalize( normal ) * df;",
  12313. " } else {",
  12314. " #ifdef USE_SKINNING",
  12315. " vec4 skinVertex = vec4( position, 1.0 );",
  12316. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  12317. " skinned += boneMatY * skinVertex * skinWeight.y;",
  12318. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  12319. " skinned += boneMatW * skinVertex * skinWeight.w;",
  12320. " displacedPosition = skinned.xyz;",
  12321. " #else",
  12322. " displacedPosition = position;",
  12323. " #endif",
  12324. " }",
  12325. " #else",
  12326. " #ifdef USE_SKINNING",
  12327. " vec4 skinVertex = vec4( position, 1.0 );",
  12328. " vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  12329. " skinned += boneMatY * skinVertex * skinWeight.y;",
  12330. " skinned += boneMatZ * skinVertex * skinWeight.z;",
  12331. " skinned += boneMatW * skinVertex * skinWeight.w;",
  12332. " displacedPosition = skinned.xyz;",
  12333. " #else",
  12334. " displacedPosition = position;",
  12335. " #endif",
  12336. " #endif",
  12337. //
  12338. " vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  12339. " vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  12340. " gl_Position = projectionMatrix * mvPosition;",
  12341. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12342. //
  12343. " vWorldPosition = worldPosition.xyz;",
  12344. " vViewPosition = -mvPosition.xyz;",
  12345. // shadows
  12346. " #ifdef USE_SHADOWMAP",
  12347. " for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  12348. " vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  12349. " }",
  12350. " #endif",
  12351. "}"
  12352. ].join("\n")
  12353. },
  12354. /* -------------------------------------------------------------------------
  12355. // Cube map shader
  12356. ------------------------------------------------------------------------- */
  12357. 'cube': {
  12358. uniforms: { "tCube": { type: "t", value: null },
  12359. "tFlip": { type: "f", value: -1 } },
  12360. vertexShader: [
  12361. "varying vec3 vWorldPosition;",
  12362. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12363. "void main() {",
  12364. " vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  12365. " vWorldPosition = worldPosition.xyz;",
  12366. " gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  12367. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12368. "}"
  12369. ].join("\n"),
  12370. fragmentShader: [
  12371. "uniform samplerCube tCube;",
  12372. "uniform float tFlip;",
  12373. "varying vec3 vWorldPosition;",
  12374. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12375. "void main() {",
  12376. " gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  12377. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12378. "}"
  12379. ].join("\n")
  12380. },
  12381. // Depth encoding into RGBA texture
  12382. // based on SpiderGL shadow map example
  12383. // http://spidergl.org/example.php?id=6
  12384. // originally from
  12385. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  12386. // see also here:
  12387. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  12388. 'depthRGBA': {
  12389. uniforms: {},
  12390. vertexShader: [
  12391. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  12392. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  12393. THREE.ShaderChunk[ "logdepthbuf_pars_vertex" ],
  12394. "void main() {",
  12395. THREE.ShaderChunk[ "skinbase_vertex" ],
  12396. THREE.ShaderChunk[ "morphtarget_vertex" ],
  12397. THREE.ShaderChunk[ "skinning_vertex" ],
  12398. THREE.ShaderChunk[ "default_vertex" ],
  12399. THREE.ShaderChunk[ "logdepthbuf_vertex" ],
  12400. "}"
  12401. ].join("\n"),
  12402. fragmentShader: [
  12403. THREE.ShaderChunk[ "logdepthbuf_pars_fragment" ],
  12404. "vec4 pack_depth( const in float depth ) {",
  12405. " const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  12406. " const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  12407. " vec4 res = mod( depth * bit_shift * vec4( 255 ), vec4( 256 ) ) / vec4( 255 );", // " vec4 res = fract( depth * bit_shift );",
  12408. " res -= res.xxyz * bit_mask;",
  12409. " return res;",
  12410. "}",
  12411. "void main() {",
  12412. THREE.ShaderChunk[ "logdepthbuf_fragment" ],
  12413. " #ifdef USE_LOGDEPTHBUF_EXT",
  12414. " gl_FragData[ 0 ] = pack_depth( gl_FragDepthEXT );",
  12415. " #else",
  12416. " gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  12417. " #endif",
  12418. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  12419. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  12420. //"gl_FragData[ 0 ] = pack_depth( z );",
  12421. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  12422. "}"
  12423. ].join("\n")
  12424. }
  12425. };
  12426. /**
  12427. * @author supereggbert / http://www.paulbrunt.co.uk/
  12428. * @author mrdoob / http://mrdoob.com/
  12429. * @author alteredq / http://alteredqualia.com/
  12430. * @author szimek / https://github.com/szimek/
  12431. */
  12432. THREE.WebGLRenderer = function ( parameters ) {
  12433. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  12434. parameters = parameters || {};
  12435. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  12436. _context = parameters.context !== undefined ? parameters.context : null,
  12437. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  12438. _buffers = {},
  12439. _alpha = parameters.alpha !== undefined ? parameters.alpha : false,
  12440. _depth = parameters.depth !== undefined ? parameters.depth : true,
  12441. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  12442. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  12443. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  12444. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  12445. _logarithmicDepthBuffer = parameters.logarithmicDepthBuffer !== undefined ? parameters.logarithmicDepthBuffer : false,
  12446. _clearColor = new THREE.Color( 0x000000 ),
  12447. _clearAlpha = 0;
  12448. // public properties
  12449. this.domElement = _canvas;
  12450. this.context = null;
  12451. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  12452. ? parameters.devicePixelRatio
  12453. : self.devicePixelRatio !== undefined
  12454. ? self.devicePixelRatio
  12455. : 1;
  12456. // clearing
  12457. this.autoClear = true;
  12458. this.autoClearColor = true;
  12459. this.autoClearDepth = true;
  12460. this.autoClearStencil = true;
  12461. // scene graph
  12462. this.sortObjects = true;
  12463. this.autoUpdateObjects = true;
  12464. // physically based shading
  12465. this.gammaInput = false;
  12466. this.gammaOutput = false;
  12467. // shadow map
  12468. this.shadowMapEnabled = false;
  12469. this.shadowMapAutoUpdate = true;
  12470. this.shadowMapType = THREE.PCFShadowMap;
  12471. this.shadowMapCullFace = THREE.CullFaceFront;
  12472. this.shadowMapDebug = false;
  12473. this.shadowMapCascade = false;
  12474. // morphs
  12475. this.maxMorphTargets = 8;
  12476. this.maxMorphNormals = 4;
  12477. // flags
  12478. this.autoScaleCubemaps = true;
  12479. // custom render plugins
  12480. this.renderPluginsPre = [];
  12481. this.renderPluginsPost = [];
  12482. // info
  12483. this.info = {
  12484. memory: {
  12485. programs: 0,
  12486. geometries: 0,
  12487. textures: 0
  12488. },
  12489. render: {
  12490. calls: 0,
  12491. vertices: 0,
  12492. faces: 0,
  12493. points: 0
  12494. }
  12495. };
  12496. // internal properties
  12497. var _this = this,
  12498. _programs = [],
  12499. // internal state cache
  12500. _currentProgram = null,
  12501. _currentFramebuffer = null,
  12502. _currentMaterialId = -1,
  12503. _currentGeometryGroupHash = null,
  12504. _currentCamera = null,
  12505. _usedTextureUnits = 0,
  12506. // GL state cache
  12507. _oldDoubleSided = -1,
  12508. _oldFlipSided = -1,
  12509. _oldBlending = -1,
  12510. _oldBlendEquation = -1,
  12511. _oldBlendSrc = -1,
  12512. _oldBlendDst = -1,
  12513. _oldDepthTest = -1,
  12514. _oldDepthWrite = -1,
  12515. _oldPolygonOffset = null,
  12516. _oldPolygonOffsetFactor = null,
  12517. _oldPolygonOffsetUnits = null,
  12518. _oldLineWidth = null,
  12519. _viewportX = 0,
  12520. _viewportY = 0,
  12521. _viewportWidth = _canvas.width,
  12522. _viewportHeight = _canvas.height,
  12523. _currentWidth = 0,
  12524. _currentHeight = 0,
  12525. _newAttributes = new Uint8Array( 16 ),
  12526. _enabledAttributes = new Uint8Array( 16 ),
  12527. // frustum
  12528. _frustum = new THREE.Frustum(),
  12529. // camera matrices cache
  12530. _projScreenMatrix = new THREE.Matrix4(),
  12531. _projScreenMatrixPS = new THREE.Matrix4(),
  12532. _vector3 = new THREE.Vector3(),
  12533. // light arrays cache
  12534. _direction = new THREE.Vector3(),
  12535. _lightsNeedUpdate = true,
  12536. _lights = {
  12537. ambient: [ 0, 0, 0 ],
  12538. directional: { length: 0, colors: new Array(), positions: new Array() },
  12539. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  12540. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  12541. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  12542. };
  12543. // initialize
  12544. var _gl;
  12545. var _glExtensionTextureFloat;
  12546. var _glExtensionTextureFloatLinear;
  12547. var _glExtensionStandardDerivatives;
  12548. var _glExtensionTextureFilterAnisotropic;
  12549. var _glExtensionCompressedTextureS3TC;
  12550. var _glExtensionElementIndexUint;
  12551. var _glExtensionFragDepth;
  12552. initGL();
  12553. setDefaultGLState();
  12554. this.context = _gl;
  12555. // GPU capabilities
  12556. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  12557. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  12558. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  12559. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  12560. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  12561. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  12562. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  12563. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  12564. //
  12565. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  12566. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  12567. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  12568. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  12569. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  12570. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  12571. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  12572. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  12573. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  12574. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  12575. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  12576. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  12577. // clamp precision to maximum available
  12578. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  12579. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  12580. if ( _precision === "highp" && ! highpAvailable ) {
  12581. if ( mediumpAvailable ) {
  12582. _precision = "mediump";
  12583. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  12584. } else {
  12585. _precision = "lowp";
  12586. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  12587. }
  12588. }
  12589. if ( _precision === "mediump" && ! mediumpAvailable ) {
  12590. _precision = "lowp";
  12591. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  12592. }
  12593. // API
  12594. this.getContext = function () {
  12595. return _gl;
  12596. };
  12597. this.supportsVertexTextures = function () {
  12598. return _supportsVertexTextures;
  12599. };
  12600. this.supportsFloatTextures = function () {
  12601. return _glExtensionTextureFloat;
  12602. };
  12603. this.supportsStandardDerivatives = function () {
  12604. return _glExtensionStandardDerivatives;
  12605. };
  12606. this.supportsCompressedTextureS3TC = function () {
  12607. return _glExtensionCompressedTextureS3TC;
  12608. };
  12609. this.getMaxAnisotropy = function () {
  12610. return _maxAnisotropy;
  12611. };
  12612. this.getPrecision = function () {
  12613. return _precision;
  12614. };
  12615. this.setSize = function ( width, height, updateStyle ) {
  12616. _canvas.width = width * this.devicePixelRatio;
  12617. _canvas.height = height * this.devicePixelRatio;
  12618. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  12619. _canvas.style.width = width + 'px';
  12620. _canvas.style.height = height + 'px';
  12621. }
  12622. this.setViewport( 0, 0, width, height );
  12623. };
  12624. this.setViewport = function ( x, y, width, height ) {
  12625. _viewportX = x * this.devicePixelRatio;
  12626. _viewportY = y * this.devicePixelRatio;
  12627. _viewportWidth = width * this.devicePixelRatio;
  12628. _viewportHeight = height * this.devicePixelRatio;
  12629. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  12630. };
  12631. this.setScissor = function ( x, y, width, height ) {
  12632. _gl.scissor(
  12633. x * this.devicePixelRatio,
  12634. y * this.devicePixelRatio,
  12635. width * this.devicePixelRatio,
  12636. height * this.devicePixelRatio
  12637. );
  12638. };
  12639. this.enableScissorTest = function ( enable ) {
  12640. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  12641. };
  12642. // Clearing
  12643. this.setClearColor = function ( color, alpha ) {
  12644. _clearColor.set( color );
  12645. _clearAlpha = alpha !== undefined ? alpha : 1;
  12646. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  12647. };
  12648. this.setClearColorHex = function ( hex, alpha ) {
  12649. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  12650. this.setClearColor( hex, alpha );
  12651. };
  12652. this.getClearColor = function () {
  12653. return _clearColor;
  12654. };
  12655. this.getClearAlpha = function () {
  12656. return _clearAlpha;
  12657. };
  12658. this.clear = function ( color, depth, stencil ) {
  12659. var bits = 0;
  12660. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  12661. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  12662. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  12663. _gl.clear( bits );
  12664. };
  12665. this.clearColor = function () {
  12666. _gl.clear( _gl.COLOR_BUFFER_BIT );
  12667. };
  12668. this.clearDepth = function () {
  12669. _gl.clear( _gl.DEPTH_BUFFER_BIT );
  12670. };
  12671. this.clearStencil = function () {
  12672. _gl.clear( _gl.STENCIL_BUFFER_BIT );
  12673. };
  12674. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  12675. this.setRenderTarget( renderTarget );
  12676. this.clear( color, depth, stencil );
  12677. };
  12678. // Plugins
  12679. this.addPostPlugin = function ( plugin ) {
  12680. plugin.init( this );
  12681. this.renderPluginsPost.push( plugin );
  12682. };
  12683. this.addPrePlugin = function ( plugin ) {
  12684. plugin.init( this );
  12685. this.renderPluginsPre.push( plugin );
  12686. };
  12687. // Rendering
  12688. this.updateShadowMap = function ( scene, camera ) {
  12689. _currentProgram = null;
  12690. _oldBlending = -1;
  12691. _oldDepthTest = -1;
  12692. _oldDepthWrite = -1;
  12693. _currentGeometryGroupHash = -1;
  12694. _currentMaterialId = -1;
  12695. _lightsNeedUpdate = true;
  12696. _oldDoubleSided = -1;
  12697. _oldFlipSided = -1;
  12698. this.shadowMapPlugin.update( scene, camera );
  12699. };
  12700. // Internal functions
  12701. // Buffer allocation
  12702. function createParticleBuffers ( geometry ) {
  12703. geometry.__webglVertexBuffer = _gl.createBuffer();
  12704. geometry.__webglColorBuffer = _gl.createBuffer();
  12705. _this.info.memory.geometries ++;
  12706. };
  12707. function createLineBuffers ( geometry ) {
  12708. geometry.__webglVertexBuffer = _gl.createBuffer();
  12709. geometry.__webglColorBuffer = _gl.createBuffer();
  12710. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  12711. _this.info.memory.geometries ++;
  12712. };
  12713. function createMeshBuffers ( geometryGroup ) {
  12714. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  12715. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  12716. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  12717. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  12718. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  12719. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  12720. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  12721. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  12722. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  12723. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  12724. var m, ml;
  12725. if ( geometryGroup.numMorphTargets ) {
  12726. geometryGroup.__webglMorphTargetsBuffers = [];
  12727. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12728. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  12729. }
  12730. }
  12731. if ( geometryGroup.numMorphNormals ) {
  12732. geometryGroup.__webglMorphNormalsBuffers = [];
  12733. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12734. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  12735. }
  12736. }
  12737. _this.info.memory.geometries ++;
  12738. };
  12739. // Events
  12740. var onGeometryDispose = function ( event ) {
  12741. var geometry = event.target;
  12742. geometry.removeEventListener( 'dispose', onGeometryDispose );
  12743. deallocateGeometry( geometry );
  12744. };
  12745. var onTextureDispose = function ( event ) {
  12746. var texture = event.target;
  12747. texture.removeEventListener( 'dispose', onTextureDispose );
  12748. deallocateTexture( texture );
  12749. _this.info.memory.textures --;
  12750. };
  12751. var onRenderTargetDispose = function ( event ) {
  12752. var renderTarget = event.target;
  12753. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  12754. deallocateRenderTarget( renderTarget );
  12755. _this.info.memory.textures --;
  12756. };
  12757. var onMaterialDispose = function ( event ) {
  12758. var material = event.target;
  12759. material.removeEventListener( 'dispose', onMaterialDispose );
  12760. deallocateMaterial( material );
  12761. };
  12762. // Buffer deallocation
  12763. var deleteBuffers = function ( geometry ) {
  12764. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  12765. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  12766. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  12767. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  12768. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  12769. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  12770. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  12771. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  12772. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  12773. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  12774. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  12775. // custom attributes
  12776. if ( geometry.__webglCustomAttributesList !== undefined ) {
  12777. for ( var id in geometry.__webglCustomAttributesList ) {
  12778. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  12779. }
  12780. }
  12781. _this.info.memory.geometries --;
  12782. };
  12783. var deallocateGeometry = function ( geometry ) {
  12784. geometry.__webglInit = undefined;
  12785. if ( geometry instanceof THREE.BufferGeometry ) {
  12786. var attributes = geometry.attributes;
  12787. for ( var key in attributes ) {
  12788. if ( attributes[ key ].buffer !== undefined ) {
  12789. _gl.deleteBuffer( attributes[ key ].buffer );
  12790. }
  12791. }
  12792. _this.info.memory.geometries --;
  12793. } else {
  12794. if ( geometry.geometryGroups !== undefined ) {
  12795. for ( var g in geometry.geometryGroups ) {
  12796. var geometryGroup = geometry.geometryGroups[ g ];
  12797. if ( geometryGroup.numMorphTargets !== undefined ) {
  12798. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12799. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  12800. }
  12801. }
  12802. if ( geometryGroup.numMorphNormals !== undefined ) {
  12803. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12804. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  12805. }
  12806. }
  12807. deleteBuffers( geometryGroup );
  12808. }
  12809. } else {
  12810. deleteBuffers( geometry );
  12811. }
  12812. }
  12813. };
  12814. var deallocateTexture = function ( texture ) {
  12815. if ( texture.image && texture.image.__webglTextureCube ) {
  12816. // cube texture
  12817. _gl.deleteTexture( texture.image.__webglTextureCube );
  12818. } else {
  12819. // 2D texture
  12820. if ( ! texture.__webglInit ) return;
  12821. texture.__webglInit = false;
  12822. _gl.deleteTexture( texture.__webglTexture );
  12823. }
  12824. };
  12825. var deallocateRenderTarget = function ( renderTarget ) {
  12826. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  12827. _gl.deleteTexture( renderTarget.__webglTexture );
  12828. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  12829. for ( var i = 0; i < 6; i ++ ) {
  12830. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  12831. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  12832. }
  12833. } else {
  12834. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  12835. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  12836. }
  12837. };
  12838. var deallocateMaterial = function ( material ) {
  12839. var program = material.program;
  12840. if ( program === undefined ) return;
  12841. material.program = undefined;
  12842. // only deallocate GL program if this was the last use of shared program
  12843. // assumed there is only single copy of any program in the _programs list
  12844. // (that's how it's constructed)
  12845. var i, il, programInfo;
  12846. var deleteProgram = false;
  12847. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12848. programInfo = _programs[ i ];
  12849. if ( programInfo.program === program ) {
  12850. programInfo.usedTimes --;
  12851. if ( programInfo.usedTimes === 0 ) {
  12852. deleteProgram = true;
  12853. }
  12854. break;
  12855. }
  12856. }
  12857. if ( deleteProgram === true ) {
  12858. // avoid using array.splice, this is costlier than creating new array from scratch
  12859. var newPrograms = [];
  12860. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  12861. programInfo = _programs[ i ];
  12862. if ( programInfo.program !== program ) {
  12863. newPrograms.push( programInfo );
  12864. }
  12865. }
  12866. _programs = newPrograms;
  12867. _gl.deleteProgram( program );
  12868. _this.info.memory.programs --;
  12869. }
  12870. };
  12871. // Buffer initialization
  12872. function initCustomAttributes ( geometry, object ) {
  12873. var nvertices = geometry.vertices.length;
  12874. var material = object.material;
  12875. if ( material.attributes ) {
  12876. if ( geometry.__webglCustomAttributesList === undefined ) {
  12877. geometry.__webglCustomAttributesList = [];
  12878. }
  12879. for ( var a in material.attributes ) {
  12880. var attribute = material.attributes[ a ];
  12881. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12882. attribute.__webglInitialized = true;
  12883. var size = 1; // "f" and "i"
  12884. if ( attribute.type === "v2" ) size = 2;
  12885. else if ( attribute.type === "v3" ) size = 3;
  12886. else if ( attribute.type === "v4" ) size = 4;
  12887. else if ( attribute.type === "c" ) size = 3;
  12888. attribute.size = size;
  12889. attribute.array = new Float32Array( nvertices * size );
  12890. attribute.buffer = _gl.createBuffer();
  12891. attribute.buffer.belongsToAttribute = a;
  12892. attribute.needsUpdate = true;
  12893. }
  12894. geometry.__webglCustomAttributesList.push( attribute );
  12895. }
  12896. }
  12897. };
  12898. function initParticleBuffers ( geometry, object ) {
  12899. var nvertices = geometry.vertices.length;
  12900. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12901. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12902. geometry.__sortArray = [];
  12903. geometry.__webglParticleCount = nvertices;
  12904. initCustomAttributes ( geometry, object );
  12905. };
  12906. function initLineBuffers ( geometry, object ) {
  12907. var nvertices = geometry.vertices.length;
  12908. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  12909. geometry.__colorArray = new Float32Array( nvertices * 3 );
  12910. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  12911. geometry.__webglLineCount = nvertices;
  12912. initCustomAttributes ( geometry, object );
  12913. };
  12914. function initMeshBuffers ( geometryGroup, object ) {
  12915. var geometry = object.geometry,
  12916. faces3 = geometryGroup.faces3,
  12917. nvertices = faces3.length * 3,
  12918. ntris = faces3.length * 1,
  12919. nlines = faces3.length * 3,
  12920. material = getBufferMaterial( object, geometryGroup ),
  12921. uvType = bufferGuessUVType( material ),
  12922. normalType = bufferGuessNormalType( material ),
  12923. vertexColorType = bufferGuessVertexColorType( material );
  12924. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  12925. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  12926. if ( normalType ) {
  12927. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  12928. }
  12929. if ( geometry.hasTangents ) {
  12930. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  12931. }
  12932. if ( vertexColorType ) {
  12933. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  12934. }
  12935. if ( uvType ) {
  12936. if ( geometry.faceVertexUvs.length > 0 ) {
  12937. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  12938. }
  12939. if ( geometry.faceVertexUvs.length > 1 ) {
  12940. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  12941. }
  12942. }
  12943. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  12944. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  12945. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  12946. }
  12947. var UintArray = _glExtensionElementIndexUint !== null && ntris > 21845 ? Uint32Array : Uint16Array; // 65535 / 3
  12948. geometryGroup.__typeArray = UintArray;
  12949. geometryGroup.__faceArray = new UintArray( ntris * 3 );
  12950. geometryGroup.__lineArray = new UintArray( nlines * 2 );
  12951. var m, ml;
  12952. if ( geometryGroup.numMorphTargets ) {
  12953. geometryGroup.__morphTargetsArrays = [];
  12954. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  12955. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  12956. }
  12957. }
  12958. if ( geometryGroup.numMorphNormals ) {
  12959. geometryGroup.__morphNormalsArrays = [];
  12960. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  12961. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  12962. }
  12963. }
  12964. geometryGroup.__webglFaceCount = ntris * 3;
  12965. geometryGroup.__webglLineCount = nlines * 2;
  12966. // custom attributes
  12967. if ( material.attributes ) {
  12968. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  12969. geometryGroup.__webglCustomAttributesList = [];
  12970. }
  12971. for ( var a in material.attributes ) {
  12972. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  12973. // attribute buffers which are correctly indexed in the setMeshBuffers function
  12974. var originalAttribute = material.attributes[ a ];
  12975. var attribute = {};
  12976. for ( var property in originalAttribute ) {
  12977. attribute[ property ] = originalAttribute[ property ];
  12978. }
  12979. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  12980. attribute.__webglInitialized = true;
  12981. var size = 1; // "f" and "i"
  12982. if( attribute.type === "v2" ) size = 2;
  12983. else if( attribute.type === "v3" ) size = 3;
  12984. else if( attribute.type === "v4" ) size = 4;
  12985. else if( attribute.type === "c" ) size = 3;
  12986. attribute.size = size;
  12987. attribute.array = new Float32Array( nvertices * size );
  12988. attribute.buffer = _gl.createBuffer();
  12989. attribute.buffer.belongsToAttribute = a;
  12990. originalAttribute.needsUpdate = true;
  12991. attribute.__original = originalAttribute;
  12992. }
  12993. geometryGroup.__webglCustomAttributesList.push( attribute );
  12994. }
  12995. }
  12996. geometryGroup.__inittedArrays = true;
  12997. };
  12998. function getBufferMaterial( object, geometryGroup ) {
  12999. return object.material instanceof THREE.MeshFaceMaterial
  13000. ? object.material.materials[ geometryGroup.materialIndex ]
  13001. : object.material;
  13002. };
  13003. function materialNeedsSmoothNormals ( material ) {
  13004. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  13005. };
  13006. function bufferGuessNormalType ( material ) {
  13007. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  13008. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  13009. return false;
  13010. }
  13011. if ( materialNeedsSmoothNormals( material ) ) {
  13012. return THREE.SmoothShading;
  13013. } else {
  13014. return THREE.FlatShading;
  13015. }
  13016. };
  13017. function bufferGuessVertexColorType( material ) {
  13018. if ( material.vertexColors ) {
  13019. return material.vertexColors;
  13020. }
  13021. return false;
  13022. };
  13023. function bufferGuessUVType( material ) {
  13024. // material must use some texture to require uvs
  13025. if ( material.map ||
  13026. material.lightMap ||
  13027. material.bumpMap ||
  13028. material.normalMap ||
  13029. material.specularMap ||
  13030. material instanceof THREE.ShaderMaterial ) {
  13031. return true;
  13032. }
  13033. return false;
  13034. };
  13035. //
  13036. function initDirectBuffers( geometry ) {
  13037. for ( var name in geometry.attributes ) {
  13038. var bufferType = ( name === "index" ) ? _gl.ELEMENT_ARRAY_BUFFER : _gl.ARRAY_BUFFER;
  13039. var attribute = geometry.attributes[ name ];
  13040. attribute.buffer = _gl.createBuffer();
  13041. _gl.bindBuffer( bufferType, attribute.buffer );
  13042. _gl.bufferData( bufferType, attribute.array, _gl.STATIC_DRAW );
  13043. }
  13044. }
  13045. // Buffer setting
  13046. function setParticleBuffers ( geometry, hint, object ) {
  13047. var v, c, vertex, offset, index, color,
  13048. vertices = geometry.vertices,
  13049. vl = vertices.length,
  13050. colors = geometry.colors,
  13051. cl = colors.length,
  13052. vertexArray = geometry.__vertexArray,
  13053. colorArray = geometry.__colorArray,
  13054. sortArray = geometry.__sortArray,
  13055. dirtyVertices = geometry.verticesNeedUpdate,
  13056. dirtyElements = geometry.elementsNeedUpdate,
  13057. dirtyColors = geometry.colorsNeedUpdate,
  13058. customAttributes = geometry.__webglCustomAttributesList,
  13059. i, il,
  13060. a, ca, cal, value,
  13061. customAttribute;
  13062. if ( object.sortParticles ) {
  13063. _projScreenMatrixPS.copy( _projScreenMatrix );
  13064. _projScreenMatrixPS.multiply( object.matrixWorld );
  13065. for ( v = 0; v < vl; v ++ ) {
  13066. vertex = vertices[ v ];
  13067. _vector3.copy( vertex );
  13068. _vector3.applyProjection( _projScreenMatrixPS );
  13069. sortArray[ v ] = [ _vector3.z, v ];
  13070. }
  13071. sortArray.sort( numericalSort );
  13072. for ( v = 0; v < vl; v ++ ) {
  13073. vertex = vertices[ sortArray[v][1] ];
  13074. offset = v * 3;
  13075. vertexArray[ offset ] = vertex.x;
  13076. vertexArray[ offset + 1 ] = vertex.y;
  13077. vertexArray[ offset + 2 ] = vertex.z;
  13078. }
  13079. for ( c = 0; c < cl; c ++ ) {
  13080. offset = c * 3;
  13081. color = colors[ sortArray[c][1] ];
  13082. colorArray[ offset ] = color.r;
  13083. colorArray[ offset + 1 ] = color.g;
  13084. colorArray[ offset + 2 ] = color.b;
  13085. }
  13086. if ( customAttributes ) {
  13087. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13088. customAttribute = customAttributes[ i ];
  13089. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  13090. offset = 0;
  13091. cal = customAttribute.value.length;
  13092. if ( customAttribute.size === 1 ) {
  13093. for ( ca = 0; ca < cal; ca ++ ) {
  13094. index = sortArray[ ca ][ 1 ];
  13095. customAttribute.array[ ca ] = customAttribute.value[ index ];
  13096. }
  13097. } else if ( customAttribute.size === 2 ) {
  13098. for ( ca = 0; ca < cal; ca ++ ) {
  13099. index = sortArray[ ca ][ 1 ];
  13100. value = customAttribute.value[ index ];
  13101. customAttribute.array[ offset ] = value.x;
  13102. customAttribute.array[ offset + 1 ] = value.y;
  13103. offset += 2;
  13104. }
  13105. } else if ( customAttribute.size === 3 ) {
  13106. if ( customAttribute.type === "c" ) {
  13107. for ( ca = 0; ca < cal; ca ++ ) {
  13108. index = sortArray[ ca ][ 1 ];
  13109. value = customAttribute.value[ index ];
  13110. customAttribute.array[ offset ] = value.r;
  13111. customAttribute.array[ offset + 1 ] = value.g;
  13112. customAttribute.array[ offset + 2 ] = value.b;
  13113. offset += 3;
  13114. }
  13115. } else {
  13116. for ( ca = 0; ca < cal; ca ++ ) {
  13117. index = sortArray[ ca ][ 1 ];
  13118. value = customAttribute.value[ index ];
  13119. customAttribute.array[ offset ] = value.x;
  13120. customAttribute.array[ offset + 1 ] = value.y;
  13121. customAttribute.array[ offset + 2 ] = value.z;
  13122. offset += 3;
  13123. }
  13124. }
  13125. } else if ( customAttribute.size === 4 ) {
  13126. for ( ca = 0; ca < cal; ca ++ ) {
  13127. index = sortArray[ ca ][ 1 ];
  13128. value = customAttribute.value[ index ];
  13129. customAttribute.array[ offset ] = value.x;
  13130. customAttribute.array[ offset + 1 ] = value.y;
  13131. customAttribute.array[ offset + 2 ] = value.z;
  13132. customAttribute.array[ offset + 3 ] = value.w;
  13133. offset += 4;
  13134. }
  13135. }
  13136. }
  13137. }
  13138. } else {
  13139. if ( dirtyVertices ) {
  13140. for ( v = 0; v < vl; v ++ ) {
  13141. vertex = vertices[ v ];
  13142. offset = v * 3;
  13143. vertexArray[ offset ] = vertex.x;
  13144. vertexArray[ offset + 1 ] = vertex.y;
  13145. vertexArray[ offset + 2 ] = vertex.z;
  13146. }
  13147. }
  13148. if ( dirtyColors ) {
  13149. for ( c = 0; c < cl; c ++ ) {
  13150. color = colors[ c ];
  13151. offset = c * 3;
  13152. colorArray[ offset ] = color.r;
  13153. colorArray[ offset + 1 ] = color.g;
  13154. colorArray[ offset + 2 ] = color.b;
  13155. }
  13156. }
  13157. if ( customAttributes ) {
  13158. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13159. customAttribute = customAttributes[ i ];
  13160. if ( customAttribute.needsUpdate &&
  13161. ( customAttribute.boundTo === undefined ||
  13162. customAttribute.boundTo === "vertices") ) {
  13163. cal = customAttribute.value.length;
  13164. offset = 0;
  13165. if ( customAttribute.size === 1 ) {
  13166. for ( ca = 0; ca < cal; ca ++ ) {
  13167. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  13168. }
  13169. } else if ( customAttribute.size === 2 ) {
  13170. for ( ca = 0; ca < cal; ca ++ ) {
  13171. value = customAttribute.value[ ca ];
  13172. customAttribute.array[ offset ] = value.x;
  13173. customAttribute.array[ offset + 1 ] = value.y;
  13174. offset += 2;
  13175. }
  13176. } else if ( customAttribute.size === 3 ) {
  13177. if ( customAttribute.type === "c" ) {
  13178. for ( ca = 0; ca < cal; ca ++ ) {
  13179. value = customAttribute.value[ ca ];
  13180. customAttribute.array[ offset ] = value.r;
  13181. customAttribute.array[ offset + 1 ] = value.g;
  13182. customAttribute.array[ offset + 2 ] = value.b;
  13183. offset += 3;
  13184. }
  13185. } else {
  13186. for ( ca = 0; ca < cal; ca ++ ) {
  13187. value = customAttribute.value[ ca ];
  13188. customAttribute.array[ offset ] = value.x;
  13189. customAttribute.array[ offset + 1 ] = value.y;
  13190. customAttribute.array[ offset + 2 ] = value.z;
  13191. offset += 3;
  13192. }
  13193. }
  13194. } else if ( customAttribute.size === 4 ) {
  13195. for ( ca = 0; ca < cal; ca ++ ) {
  13196. value = customAttribute.value[ ca ];
  13197. customAttribute.array[ offset ] = value.x;
  13198. customAttribute.array[ offset + 1 ] = value.y;
  13199. customAttribute.array[ offset + 2 ] = value.z;
  13200. customAttribute.array[ offset + 3 ] = value.w;
  13201. offset += 4;
  13202. }
  13203. }
  13204. }
  13205. }
  13206. }
  13207. }
  13208. if ( dirtyVertices || object.sortParticles ) {
  13209. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  13210. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13211. }
  13212. if ( dirtyColors || object.sortParticles ) {
  13213. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  13214. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13215. }
  13216. if ( customAttributes ) {
  13217. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13218. customAttribute = customAttributes[ i ];
  13219. if ( customAttribute.needsUpdate || object.sortParticles ) {
  13220. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13221. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13222. }
  13223. }
  13224. }
  13225. }
  13226. function setLineBuffers ( geometry, hint ) {
  13227. var v, c, d, vertex, offset, color,
  13228. vertices = geometry.vertices,
  13229. colors = geometry.colors,
  13230. lineDistances = geometry.lineDistances,
  13231. vl = vertices.length,
  13232. cl = colors.length,
  13233. dl = lineDistances.length,
  13234. vertexArray = geometry.__vertexArray,
  13235. colorArray = geometry.__colorArray,
  13236. lineDistanceArray = geometry.__lineDistanceArray,
  13237. dirtyVertices = geometry.verticesNeedUpdate,
  13238. dirtyColors = geometry.colorsNeedUpdate,
  13239. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  13240. customAttributes = geometry.__webglCustomAttributesList,
  13241. i, il,
  13242. a, ca, cal, value,
  13243. customAttribute;
  13244. if ( dirtyVertices ) {
  13245. for ( v = 0; v < vl; v ++ ) {
  13246. vertex = vertices[ v ];
  13247. offset = v * 3;
  13248. vertexArray[ offset ] = vertex.x;
  13249. vertexArray[ offset + 1 ] = vertex.y;
  13250. vertexArray[ offset + 2 ] = vertex.z;
  13251. }
  13252. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  13253. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13254. }
  13255. if ( dirtyColors ) {
  13256. for ( c = 0; c < cl; c ++ ) {
  13257. color = colors[ c ];
  13258. offset = c * 3;
  13259. colorArray[ offset ] = color.r;
  13260. colorArray[ offset + 1 ] = color.g;
  13261. colorArray[ offset + 2 ] = color.b;
  13262. }
  13263. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  13264. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13265. }
  13266. if ( dirtyLineDistances ) {
  13267. for ( d = 0; d < dl; d ++ ) {
  13268. lineDistanceArray[ d ] = lineDistances[ d ];
  13269. }
  13270. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  13271. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  13272. }
  13273. if ( customAttributes ) {
  13274. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13275. customAttribute = customAttributes[ i ];
  13276. if ( customAttribute.needsUpdate &&
  13277. ( customAttribute.boundTo === undefined ||
  13278. customAttribute.boundTo === "vertices" ) ) {
  13279. offset = 0;
  13280. cal = customAttribute.value.length;
  13281. if ( customAttribute.size === 1 ) {
  13282. for ( ca = 0; ca < cal; ca ++ ) {
  13283. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  13284. }
  13285. } else if ( customAttribute.size === 2 ) {
  13286. for ( ca = 0; ca < cal; ca ++ ) {
  13287. value = customAttribute.value[ ca ];
  13288. customAttribute.array[ offset ] = value.x;
  13289. customAttribute.array[ offset + 1 ] = value.y;
  13290. offset += 2;
  13291. }
  13292. } else if ( customAttribute.size === 3 ) {
  13293. if ( customAttribute.type === "c" ) {
  13294. for ( ca = 0; ca < cal; ca ++ ) {
  13295. value = customAttribute.value[ ca ];
  13296. customAttribute.array[ offset ] = value.r;
  13297. customAttribute.array[ offset + 1 ] = value.g;
  13298. customAttribute.array[ offset + 2 ] = value.b;
  13299. offset += 3;
  13300. }
  13301. } else {
  13302. for ( ca = 0; ca < cal; ca ++ ) {
  13303. value = customAttribute.value[ ca ];
  13304. customAttribute.array[ offset ] = value.x;
  13305. customAttribute.array[ offset + 1 ] = value.y;
  13306. customAttribute.array[ offset + 2 ] = value.z;
  13307. offset += 3;
  13308. }
  13309. }
  13310. } else if ( customAttribute.size === 4 ) {
  13311. for ( ca = 0; ca < cal; ca ++ ) {
  13312. value = customAttribute.value[ ca ];
  13313. customAttribute.array[ offset ] = value.x;
  13314. customAttribute.array[ offset + 1 ] = value.y;
  13315. customAttribute.array[ offset + 2 ] = value.z;
  13316. customAttribute.array[ offset + 3 ] = value.w;
  13317. offset += 4;
  13318. }
  13319. }
  13320. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13321. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13322. }
  13323. }
  13324. }
  13325. }
  13326. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  13327. if ( ! geometryGroup.__inittedArrays ) {
  13328. return;
  13329. }
  13330. var normalType = bufferGuessNormalType( material ),
  13331. vertexColorType = bufferGuessVertexColorType( material ),
  13332. uvType = bufferGuessUVType( material ),
  13333. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  13334. var f, fl, fi, face,
  13335. vertexNormals, faceNormal, normal,
  13336. vertexColors, faceColor,
  13337. vertexTangents,
  13338. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  13339. c1, c2, c3, c4,
  13340. sw1, sw2, sw3, sw4,
  13341. si1, si2, si3, si4,
  13342. sa1, sa2, sa3, sa4,
  13343. sb1, sb2, sb3, sb4,
  13344. m, ml, i, il,
  13345. vn, uvi, uv2i,
  13346. vk, vkl, vka,
  13347. nka, chf, faceVertexNormals,
  13348. a,
  13349. vertexIndex = 0,
  13350. offset = 0,
  13351. offset_uv = 0,
  13352. offset_uv2 = 0,
  13353. offset_face = 0,
  13354. offset_normal = 0,
  13355. offset_tangent = 0,
  13356. offset_line = 0,
  13357. offset_color = 0,
  13358. offset_skin = 0,
  13359. offset_morphTarget = 0,
  13360. offset_custom = 0,
  13361. offset_customSrc = 0,
  13362. value,
  13363. vertexArray = geometryGroup.__vertexArray,
  13364. uvArray = geometryGroup.__uvArray,
  13365. uv2Array = geometryGroup.__uv2Array,
  13366. normalArray = geometryGroup.__normalArray,
  13367. tangentArray = geometryGroup.__tangentArray,
  13368. colorArray = geometryGroup.__colorArray,
  13369. skinIndexArray = geometryGroup.__skinIndexArray,
  13370. skinWeightArray = geometryGroup.__skinWeightArray,
  13371. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  13372. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  13373. customAttributes = geometryGroup.__webglCustomAttributesList,
  13374. customAttribute,
  13375. faceArray = geometryGroup.__faceArray,
  13376. lineArray = geometryGroup.__lineArray,
  13377. geometry = object.geometry, // this is shared for all chunks
  13378. dirtyVertices = geometry.verticesNeedUpdate,
  13379. dirtyElements = geometry.elementsNeedUpdate,
  13380. dirtyUvs = geometry.uvsNeedUpdate,
  13381. dirtyNormals = geometry.normalsNeedUpdate,
  13382. dirtyTangents = geometry.tangentsNeedUpdate,
  13383. dirtyColors = geometry.colorsNeedUpdate,
  13384. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  13385. vertices = geometry.vertices,
  13386. chunk_faces3 = geometryGroup.faces3,
  13387. obj_faces = geometry.faces,
  13388. obj_uvs = geometry.faceVertexUvs[ 0 ],
  13389. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  13390. obj_colors = geometry.colors,
  13391. obj_skinIndices = geometry.skinIndices,
  13392. obj_skinWeights = geometry.skinWeights,
  13393. morphTargets = geometry.morphTargets,
  13394. morphNormals = geometry.morphNormals;
  13395. if ( dirtyVertices ) {
  13396. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13397. face = obj_faces[ chunk_faces3[ f ] ];
  13398. v1 = vertices[ face.a ];
  13399. v2 = vertices[ face.b ];
  13400. v3 = vertices[ face.c ];
  13401. vertexArray[ offset ] = v1.x;
  13402. vertexArray[ offset + 1 ] = v1.y;
  13403. vertexArray[ offset + 2 ] = v1.z;
  13404. vertexArray[ offset + 3 ] = v2.x;
  13405. vertexArray[ offset + 4 ] = v2.y;
  13406. vertexArray[ offset + 5 ] = v2.z;
  13407. vertexArray[ offset + 6 ] = v3.x;
  13408. vertexArray[ offset + 7 ] = v3.y;
  13409. vertexArray[ offset + 8 ] = v3.z;
  13410. offset += 9;
  13411. }
  13412. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13413. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  13414. }
  13415. if ( dirtyMorphTargets ) {
  13416. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  13417. offset_morphTarget = 0;
  13418. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13419. chf = chunk_faces3[ f ];
  13420. face = obj_faces[ chf ];
  13421. // morph positions
  13422. v1 = morphTargets[ vk ].vertices[ face.a ];
  13423. v2 = morphTargets[ vk ].vertices[ face.b ];
  13424. v3 = morphTargets[ vk ].vertices[ face.c ];
  13425. vka = morphTargetsArrays[ vk ];
  13426. vka[ offset_morphTarget ] = v1.x;
  13427. vka[ offset_morphTarget + 1 ] = v1.y;
  13428. vka[ offset_morphTarget + 2 ] = v1.z;
  13429. vka[ offset_morphTarget + 3 ] = v2.x;
  13430. vka[ offset_morphTarget + 4 ] = v2.y;
  13431. vka[ offset_morphTarget + 5 ] = v2.z;
  13432. vka[ offset_morphTarget + 6 ] = v3.x;
  13433. vka[ offset_morphTarget + 7 ] = v3.y;
  13434. vka[ offset_morphTarget + 8 ] = v3.z;
  13435. // morph normals
  13436. if ( material.morphNormals ) {
  13437. if ( needsSmoothNormals ) {
  13438. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  13439. n1 = faceVertexNormals.a;
  13440. n2 = faceVertexNormals.b;
  13441. n3 = faceVertexNormals.c;
  13442. } else {
  13443. n1 = morphNormals[ vk ].faceNormals[ chf ];
  13444. n2 = n1;
  13445. n3 = n1;
  13446. }
  13447. nka = morphNormalsArrays[ vk ];
  13448. nka[ offset_morphTarget ] = n1.x;
  13449. nka[ offset_morphTarget + 1 ] = n1.y;
  13450. nka[ offset_morphTarget + 2 ] = n1.z;
  13451. nka[ offset_morphTarget + 3 ] = n2.x;
  13452. nka[ offset_morphTarget + 4 ] = n2.y;
  13453. nka[ offset_morphTarget + 5 ] = n2.z;
  13454. nka[ offset_morphTarget + 6 ] = n3.x;
  13455. nka[ offset_morphTarget + 7 ] = n3.y;
  13456. nka[ offset_morphTarget + 8 ] = n3.z;
  13457. }
  13458. //
  13459. offset_morphTarget += 9;
  13460. }
  13461. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  13462. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  13463. if ( material.morphNormals ) {
  13464. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  13465. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  13466. }
  13467. }
  13468. }
  13469. if ( obj_skinWeights.length ) {
  13470. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13471. face = obj_faces[ chunk_faces3[ f ] ];
  13472. // weights
  13473. sw1 = obj_skinWeights[ face.a ];
  13474. sw2 = obj_skinWeights[ face.b ];
  13475. sw3 = obj_skinWeights[ face.c ];
  13476. skinWeightArray[ offset_skin ] = sw1.x;
  13477. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  13478. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  13479. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  13480. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  13481. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  13482. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  13483. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  13484. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  13485. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  13486. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  13487. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  13488. // indices
  13489. si1 = obj_skinIndices[ face.a ];
  13490. si2 = obj_skinIndices[ face.b ];
  13491. si3 = obj_skinIndices[ face.c ];
  13492. skinIndexArray[ offset_skin ] = si1.x;
  13493. skinIndexArray[ offset_skin + 1 ] = si1.y;
  13494. skinIndexArray[ offset_skin + 2 ] = si1.z;
  13495. skinIndexArray[ offset_skin + 3 ] = si1.w;
  13496. skinIndexArray[ offset_skin + 4 ] = si2.x;
  13497. skinIndexArray[ offset_skin + 5 ] = si2.y;
  13498. skinIndexArray[ offset_skin + 6 ] = si2.z;
  13499. skinIndexArray[ offset_skin + 7 ] = si2.w;
  13500. skinIndexArray[ offset_skin + 8 ] = si3.x;
  13501. skinIndexArray[ offset_skin + 9 ] = si3.y;
  13502. skinIndexArray[ offset_skin + 10 ] = si3.z;
  13503. skinIndexArray[ offset_skin + 11 ] = si3.w;
  13504. offset_skin += 12;
  13505. }
  13506. if ( offset_skin > 0 ) {
  13507. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13508. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  13509. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13510. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  13511. }
  13512. }
  13513. if ( dirtyColors && vertexColorType ) {
  13514. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13515. face = obj_faces[ chunk_faces3[ f ] ];
  13516. vertexColors = face.vertexColors;
  13517. faceColor = face.color;
  13518. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  13519. c1 = vertexColors[ 0 ];
  13520. c2 = vertexColors[ 1 ];
  13521. c3 = vertexColors[ 2 ];
  13522. } else {
  13523. c1 = faceColor;
  13524. c2 = faceColor;
  13525. c3 = faceColor;
  13526. }
  13527. colorArray[ offset_color ] = c1.r;
  13528. colorArray[ offset_color + 1 ] = c1.g;
  13529. colorArray[ offset_color + 2 ] = c1.b;
  13530. colorArray[ offset_color + 3 ] = c2.r;
  13531. colorArray[ offset_color + 4 ] = c2.g;
  13532. colorArray[ offset_color + 5 ] = c2.b;
  13533. colorArray[ offset_color + 6 ] = c3.r;
  13534. colorArray[ offset_color + 7 ] = c3.g;
  13535. colorArray[ offset_color + 8 ] = c3.b;
  13536. offset_color += 9;
  13537. }
  13538. if ( offset_color > 0 ) {
  13539. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13540. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  13541. }
  13542. }
  13543. if ( dirtyTangents && geometry.hasTangents ) {
  13544. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13545. face = obj_faces[ chunk_faces3[ f ] ];
  13546. vertexTangents = face.vertexTangents;
  13547. t1 = vertexTangents[ 0 ];
  13548. t2 = vertexTangents[ 1 ];
  13549. t3 = vertexTangents[ 2 ];
  13550. tangentArray[ offset_tangent ] = t1.x;
  13551. tangentArray[ offset_tangent + 1 ] = t1.y;
  13552. tangentArray[ offset_tangent + 2 ] = t1.z;
  13553. tangentArray[ offset_tangent + 3 ] = t1.w;
  13554. tangentArray[ offset_tangent + 4 ] = t2.x;
  13555. tangentArray[ offset_tangent + 5 ] = t2.y;
  13556. tangentArray[ offset_tangent + 6 ] = t2.z;
  13557. tangentArray[ offset_tangent + 7 ] = t2.w;
  13558. tangentArray[ offset_tangent + 8 ] = t3.x;
  13559. tangentArray[ offset_tangent + 9 ] = t3.y;
  13560. tangentArray[ offset_tangent + 10 ] = t3.z;
  13561. tangentArray[ offset_tangent + 11 ] = t3.w;
  13562. offset_tangent += 12;
  13563. }
  13564. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13565. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  13566. }
  13567. if ( dirtyNormals && normalType ) {
  13568. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13569. face = obj_faces[ chunk_faces3[ f ] ];
  13570. vertexNormals = face.vertexNormals;
  13571. faceNormal = face.normal;
  13572. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  13573. for ( i = 0; i < 3; i ++ ) {
  13574. vn = vertexNormals[ i ];
  13575. normalArray[ offset_normal ] = vn.x;
  13576. normalArray[ offset_normal + 1 ] = vn.y;
  13577. normalArray[ offset_normal + 2 ] = vn.z;
  13578. offset_normal += 3;
  13579. }
  13580. } else {
  13581. for ( i = 0; i < 3; i ++ ) {
  13582. normalArray[ offset_normal ] = faceNormal.x;
  13583. normalArray[ offset_normal + 1 ] = faceNormal.y;
  13584. normalArray[ offset_normal + 2 ] = faceNormal.z;
  13585. offset_normal += 3;
  13586. }
  13587. }
  13588. }
  13589. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13590. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  13591. }
  13592. if ( dirtyUvs && obj_uvs && uvType ) {
  13593. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13594. fi = chunk_faces3[ f ];
  13595. uv = obj_uvs[ fi ];
  13596. if ( uv === undefined ) continue;
  13597. for ( i = 0; i < 3; i ++ ) {
  13598. uvi = uv[ i ];
  13599. uvArray[ offset_uv ] = uvi.x;
  13600. uvArray[ offset_uv + 1 ] = uvi.y;
  13601. offset_uv += 2;
  13602. }
  13603. }
  13604. if ( offset_uv > 0 ) {
  13605. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13606. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  13607. }
  13608. }
  13609. if ( dirtyUvs && obj_uvs2 && uvType ) {
  13610. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13611. fi = chunk_faces3[ f ];
  13612. uv2 = obj_uvs2[ fi ];
  13613. if ( uv2 === undefined ) continue;
  13614. for ( i = 0; i < 3; i ++ ) {
  13615. uv2i = uv2[ i ];
  13616. uv2Array[ offset_uv2 ] = uv2i.x;
  13617. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  13618. offset_uv2 += 2;
  13619. }
  13620. }
  13621. if ( offset_uv2 > 0 ) {
  13622. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13623. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  13624. }
  13625. }
  13626. if ( dirtyElements ) {
  13627. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13628. faceArray[ offset_face ] = vertexIndex;
  13629. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  13630. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  13631. offset_face += 3;
  13632. lineArray[ offset_line ] = vertexIndex;
  13633. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  13634. lineArray[ offset_line + 2 ] = vertexIndex;
  13635. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  13636. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  13637. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  13638. offset_line += 6;
  13639. vertexIndex += 3;
  13640. }
  13641. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13642. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  13643. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13644. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  13645. }
  13646. if ( customAttributes ) {
  13647. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  13648. customAttribute = customAttributes[ i ];
  13649. if ( ! customAttribute.__original.needsUpdate ) continue;
  13650. offset_custom = 0;
  13651. offset_customSrc = 0;
  13652. if ( customAttribute.size === 1 ) {
  13653. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13654. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13655. face = obj_faces[ chunk_faces3[ f ] ];
  13656. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13657. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13658. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13659. offset_custom += 3;
  13660. }
  13661. } else if ( customAttribute.boundTo === "faces" ) {
  13662. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13663. value = customAttribute.value[ chunk_faces3[ f ] ];
  13664. customAttribute.array[ offset_custom ] = value;
  13665. customAttribute.array[ offset_custom + 1 ] = value;
  13666. customAttribute.array[ offset_custom + 2 ] = value;
  13667. offset_custom += 3;
  13668. }
  13669. }
  13670. } else if ( customAttribute.size === 2 ) {
  13671. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13672. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13673. face = obj_faces[ chunk_faces3[ f ] ];
  13674. v1 = customAttribute.value[ face.a ];
  13675. v2 = customAttribute.value[ face.b ];
  13676. v3 = customAttribute.value[ face.c ];
  13677. customAttribute.array[ offset_custom ] = v1.x;
  13678. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13679. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13680. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13681. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13682. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13683. offset_custom += 6;
  13684. }
  13685. } else if ( customAttribute.boundTo === "faces" ) {
  13686. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13687. value = customAttribute.value[ chunk_faces3[ f ] ];
  13688. v1 = value;
  13689. v2 = value;
  13690. v3 = value;
  13691. customAttribute.array[ offset_custom ] = v1.x;
  13692. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13693. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13694. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13695. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13696. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13697. offset_custom += 6;
  13698. }
  13699. }
  13700. } else if ( customAttribute.size === 3 ) {
  13701. var pp;
  13702. if ( customAttribute.type === "c" ) {
  13703. pp = [ "r", "g", "b" ];
  13704. } else {
  13705. pp = [ "x", "y", "z" ];
  13706. }
  13707. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13708. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13709. face = obj_faces[ chunk_faces3[ f ] ];
  13710. v1 = customAttribute.value[ face.a ];
  13711. v2 = customAttribute.value[ face.b ];
  13712. v3 = customAttribute.value[ face.c ];
  13713. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13714. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13715. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13716. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13717. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13718. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13719. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13720. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13721. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13722. offset_custom += 9;
  13723. }
  13724. } else if ( customAttribute.boundTo === "faces" ) {
  13725. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13726. value = customAttribute.value[ chunk_faces3[ f ] ];
  13727. v1 = value;
  13728. v2 = value;
  13729. v3 = value;
  13730. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13731. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13732. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13733. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13734. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13735. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13736. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13737. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13738. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13739. offset_custom += 9;
  13740. }
  13741. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13742. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13743. value = customAttribute.value[ chunk_faces3[ f ] ];
  13744. v1 = value[ 0 ];
  13745. v2 = value[ 1 ];
  13746. v3 = value[ 2 ];
  13747. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13748. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13749. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13750. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13751. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13752. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13753. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13754. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13755. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13756. offset_custom += 9;
  13757. }
  13758. }
  13759. } else if ( customAttribute.size === 4 ) {
  13760. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13761. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13762. face = obj_faces[ chunk_faces3[ f ] ];
  13763. v1 = customAttribute.value[ face.a ];
  13764. v2 = customAttribute.value[ face.b ];
  13765. v3 = customAttribute.value[ face.c ];
  13766. customAttribute.array[ offset_custom ] = v1.x;
  13767. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13768. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13769. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13770. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13771. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13772. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13773. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13774. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13775. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13776. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13777. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13778. offset_custom += 12;
  13779. }
  13780. } else if ( customAttribute.boundTo === "faces" ) {
  13781. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13782. value = customAttribute.value[ chunk_faces3[ f ] ];
  13783. v1 = value;
  13784. v2 = value;
  13785. v3 = value;
  13786. customAttribute.array[ offset_custom ] = v1.x;
  13787. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13788. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13789. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13790. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13791. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13792. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13793. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13794. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13795. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13796. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13797. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13798. offset_custom += 12;
  13799. }
  13800. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13801. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13802. value = customAttribute.value[ chunk_faces3[ f ] ];
  13803. v1 = value[ 0 ];
  13804. v2 = value[ 1 ];
  13805. v3 = value[ 2 ];
  13806. customAttribute.array[ offset_custom ] = v1.x;
  13807. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13808. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13809. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13810. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13811. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13812. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13813. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13814. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13815. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13816. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13817. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13818. offset_custom += 12;
  13819. }
  13820. }
  13821. }
  13822. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13823. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13824. }
  13825. }
  13826. if ( dispose ) {
  13827. delete geometryGroup.__inittedArrays;
  13828. delete geometryGroup.__colorArray;
  13829. delete geometryGroup.__normalArray;
  13830. delete geometryGroup.__tangentArray;
  13831. delete geometryGroup.__uvArray;
  13832. delete geometryGroup.__uv2Array;
  13833. delete geometryGroup.__faceArray;
  13834. delete geometryGroup.__vertexArray;
  13835. delete geometryGroup.__lineArray;
  13836. delete geometryGroup.__skinIndexArray;
  13837. delete geometryGroup.__skinWeightArray;
  13838. }
  13839. };
  13840. function setDirectBuffers( geometry, hint ) {
  13841. var attributes = geometry.attributes;
  13842. var attributeName, attributeItem;
  13843. for ( attributeName in attributes ) {
  13844. attributeItem = attributes[ attributeName ];
  13845. if ( attributeItem.needsUpdate ) {
  13846. if ( attributeName === 'index' ) {
  13847. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13848. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13849. } else {
  13850. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13851. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13852. }
  13853. attributeItem.needsUpdate = false;
  13854. }
  13855. }
  13856. }
  13857. // Buffer rendering
  13858. this.renderBufferImmediate = function ( object, program, material ) {
  13859. initAttributes();
  13860. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13861. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13862. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13863. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13864. if ( object.hasPositions ) {
  13865. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13866. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13867. enableAttribute( program.attributes.position );
  13868. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13869. }
  13870. if ( object.hasNormals ) {
  13871. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13872. if ( material.shading === THREE.FlatShading ) {
  13873. var nx, ny, nz,
  13874. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13875. normalArray,
  13876. i, il = object.count * 3;
  13877. for( i = 0; i < il; i += 9 ) {
  13878. normalArray = object.normalArray;
  13879. nax = normalArray[ i ];
  13880. nay = normalArray[ i + 1 ];
  13881. naz = normalArray[ i + 2 ];
  13882. nbx = normalArray[ i + 3 ];
  13883. nby = normalArray[ i + 4 ];
  13884. nbz = normalArray[ i + 5 ];
  13885. ncx = normalArray[ i + 6 ];
  13886. ncy = normalArray[ i + 7 ];
  13887. ncz = normalArray[ i + 8 ];
  13888. nx = ( nax + nbx + ncx ) / 3;
  13889. ny = ( nay + nby + ncy ) / 3;
  13890. nz = ( naz + nbz + ncz ) / 3;
  13891. normalArray[ i ] = nx;
  13892. normalArray[ i + 1 ] = ny;
  13893. normalArray[ i + 2 ] = nz;
  13894. normalArray[ i + 3 ] = nx;
  13895. normalArray[ i + 4 ] = ny;
  13896. normalArray[ i + 5 ] = nz;
  13897. normalArray[ i + 6 ] = nx;
  13898. normalArray[ i + 7 ] = ny;
  13899. normalArray[ i + 8 ] = nz;
  13900. }
  13901. }
  13902. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13903. enableAttribute( program.attributes.normal );
  13904. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13905. }
  13906. if ( object.hasUvs && material.map ) {
  13907. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13908. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13909. enableAttribute( program.attributes.uv );
  13910. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13911. }
  13912. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13913. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13914. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13915. enableAttribute( program.attributes.color );
  13916. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13917. }
  13918. disableUnusedAttributes();
  13919. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13920. object.count = 0;
  13921. };
  13922. function setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex ) {
  13923. for ( var attributeName in programAttributes ) {
  13924. var attributePointer = programAttributes[ attributeName ];
  13925. var attributeItem = geometryAttributes[ attributeName ];
  13926. if ( attributePointer >= 0 ) {
  13927. if ( attributeItem ) {
  13928. var attributeSize = attributeItem.itemSize;
  13929. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13930. enableAttribute( attributePointer );
  13931. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13932. } else if ( material.defaultAttributeValues ) {
  13933. if ( material.defaultAttributeValues[ attributeName ].length === 2 ) {
  13934. _gl.vertexAttrib2fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13935. } else if ( material.defaultAttributeValues[ attributeName ].length === 3 ) {
  13936. _gl.vertexAttrib3fv( attributePointer, material.defaultAttributeValues[ attributeName ] );
  13937. }
  13938. }
  13939. }
  13940. }
  13941. disableUnusedAttributes();
  13942. }
  13943. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13944. if ( material.visible === false ) return;
  13945. var linewidth, a, attribute;
  13946. var attributeItem, attributeName, attributePointer, attributeSize;
  13947. var program = setProgram( camera, lights, fog, material, object );
  13948. var programAttributes = program.attributes;
  13949. var geometryAttributes = geometry.attributes;
  13950. var updateBuffers = false,
  13951. wireframeBit = material.wireframe ? 1 : 0,
  13952. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13953. if ( geometryHash !== _currentGeometryGroupHash ) {
  13954. _currentGeometryGroupHash = geometryHash;
  13955. updateBuffers = true;
  13956. }
  13957. if ( updateBuffers ) {
  13958. initAttributes();
  13959. }
  13960. // render mesh
  13961. if ( object instanceof THREE.Mesh ) {
  13962. var index = geometryAttributes[ "index" ];
  13963. if ( index ) {
  13964. // indexed triangles
  13965. var type, size;
  13966. if ( index.array instanceof Uint32Array ) {
  13967. type = _gl.UNSIGNED_INT;
  13968. size = 4;
  13969. } else {
  13970. type = _gl.UNSIGNED_SHORT;
  13971. size = 2;
  13972. }
  13973. var offsets = geometry.offsets;
  13974. if ( offsets.length === 0 ) {
  13975. if ( updateBuffers ) {
  13976. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  13977. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13978. }
  13979. _gl.drawElements( _gl.TRIANGLES, index.array.length, type, 0 );
  13980. _this.info.render.calls ++;
  13981. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  13982. _this.info.render.faces += index.array.length / 3;
  13983. } else {
  13984. // if there is more than 1 chunk
  13985. // must set attribute pointers to use new offsets for each chunk
  13986. // even if geometry and materials didn't change
  13987. updateBuffers = true;
  13988. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13989. var startIndex = offsets[ i ].index;
  13990. if ( updateBuffers ) {
  13991. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  13992. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13993. }
  13994. // render indexed triangles
  13995. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, type, offsets[ i ].start * size );
  13996. _this.info.render.calls ++;
  13997. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13998. _this.info.render.faces += offsets[ i ].count / 3;
  13999. }
  14000. }
  14001. } else {
  14002. // non-indexed triangles
  14003. if ( updateBuffers ) {
  14004. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14005. }
  14006. var position = geometry.attributes[ "position" ];
  14007. // render non-indexed triangles
  14008. _gl.drawArrays( _gl.TRIANGLES, 0, position.array.length / 3 );
  14009. _this.info.render.calls ++;
  14010. _this.info.render.vertices += position.array.length / 3;
  14011. _this.info.render.faces += position.array.length / 9;
  14012. }
  14013. } else if ( object instanceof THREE.ParticleSystem ) {
  14014. // render particles
  14015. if ( updateBuffers ) {
  14016. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14017. }
  14018. var position = geometryAttributes[ "position" ];
  14019. // render particles
  14020. _gl.drawArrays( _gl.POINTS, 0, position.array.length / 3 );
  14021. _this.info.render.calls ++;
  14022. _this.info.render.points += position.array.length / 3;
  14023. } else if ( object instanceof THREE.Line ) {
  14024. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  14025. setLineWidth( material.linewidth );
  14026. var index = geometryAttributes[ "index" ];
  14027. if ( index ) {
  14028. // indexed lines
  14029. var type, size;
  14030. if ( index.array instanceof Uint32Array ){
  14031. type = _gl.UNSIGNED_INT;
  14032. size = 4;
  14033. } else {
  14034. type = _gl.UNSIGNED_SHORT;
  14035. size = 2;
  14036. }
  14037. var offsets = geometry.offsets;
  14038. if ( offsets.length === 0 ) {
  14039. if ( updateBuffers ) {
  14040. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14041. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14042. }
  14043. _gl.drawElements( _gl.LINES, index.array.length, type, 0 ); // 2 bytes per Uint16Array
  14044. _this.info.render.calls ++;
  14045. _this.info.render.vertices += index.array.length; // not really true, here vertices can be shared
  14046. } else {
  14047. // if there is more than 1 chunk
  14048. // must set attribute pointers to use new offsets for each chunk
  14049. // even if geometry and materials didn't change
  14050. if ( offsets.length > 1 ) updateBuffers = true;
  14051. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  14052. var startIndex = offsets[ i ].index;
  14053. if ( updateBuffers ) {
  14054. setupVertexAttributes( material, programAttributes, geometryAttributes, startIndex );
  14055. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  14056. }
  14057. // render indexed lines
  14058. _gl.drawElements( _gl.LINES, offsets[ i ].count, type, offsets[ i ].start * size ); // 2 bytes per Uint16Array
  14059. _this.info.render.calls ++;
  14060. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  14061. }
  14062. }
  14063. } else {
  14064. // non-indexed lines
  14065. if ( updateBuffers ) {
  14066. setupVertexAttributes( material, programAttributes, geometryAttributes, 0 );
  14067. }
  14068. var position = geometryAttributes[ "position" ];
  14069. _gl.drawArrays( mode, 0, position.array.length / 3 );
  14070. _this.info.render.calls ++;
  14071. _this.info.render.points += position.array.length / 3;
  14072. }
  14073. }
  14074. };
  14075. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  14076. if ( material.visible === false ) return;
  14077. var linewidth, a, attribute, i, il;
  14078. var program = setProgram( camera, lights, fog, material, object );
  14079. var attributes = program.attributes;
  14080. var updateBuffers = false,
  14081. wireframeBit = material.wireframe ? 1 : 0,
  14082. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  14083. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  14084. _currentGeometryGroupHash = geometryGroupHash;
  14085. updateBuffers = true;
  14086. }
  14087. if ( updateBuffers ) {
  14088. initAttributes();
  14089. }
  14090. // vertices
  14091. if ( !material.morphTargets && attributes.position >= 0 ) {
  14092. if ( updateBuffers ) {
  14093. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  14094. enableAttribute( attributes.position );
  14095. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14096. }
  14097. } else {
  14098. if ( object.morphTargetBase ) {
  14099. setupMorphTargets( material, geometryGroup, object );
  14100. }
  14101. }
  14102. if ( updateBuffers ) {
  14103. // custom attributes
  14104. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  14105. if ( geometryGroup.__webglCustomAttributesList ) {
  14106. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  14107. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  14108. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  14109. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  14110. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  14111. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  14112. }
  14113. }
  14114. }
  14115. // colors
  14116. if ( attributes.color >= 0 ) {
  14117. if ( object.geometry.colors.length > 0 || object.geometry.faces.length > 0 ) {
  14118. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  14119. enableAttribute( attributes.color );
  14120. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  14121. } else if ( material.defaultAttributeValues ) {
  14122. _gl.vertexAttrib3fv( attributes.color, material.defaultAttributeValues.color );
  14123. }
  14124. }
  14125. // normals
  14126. if ( attributes.normal >= 0 ) {
  14127. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  14128. enableAttribute( attributes.normal );
  14129. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  14130. }
  14131. // tangents
  14132. if ( attributes.tangent >= 0 ) {
  14133. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  14134. enableAttribute( attributes.tangent );
  14135. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  14136. }
  14137. // uvs
  14138. if ( attributes.uv >= 0 ) {
  14139. if ( object.geometry.faceVertexUvs[0] ) {
  14140. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  14141. enableAttribute( attributes.uv );
  14142. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  14143. } else if ( material.defaultAttributeValues ) {
  14144. _gl.vertexAttrib2fv( attributes.uv, material.defaultAttributeValues.uv );
  14145. }
  14146. }
  14147. if ( attributes.uv2 >= 0 ) {
  14148. if ( object.geometry.faceVertexUvs[1] ) {
  14149. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  14150. enableAttribute( attributes.uv2 );
  14151. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  14152. } else if ( material.defaultAttributeValues ) {
  14153. _gl.vertexAttrib2fv( attributes.uv2, material.defaultAttributeValues.uv2 );
  14154. }
  14155. }
  14156. if ( material.skinning &&
  14157. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  14158. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  14159. enableAttribute( attributes.skinIndex );
  14160. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  14161. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  14162. enableAttribute( attributes.skinWeight );
  14163. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  14164. }
  14165. // line distances
  14166. if ( attributes.lineDistance >= 0 ) {
  14167. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  14168. enableAttribute( attributes.lineDistance );
  14169. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  14170. }
  14171. }
  14172. disableUnusedAttributes();
  14173. // render mesh
  14174. if ( object instanceof THREE.Mesh ) {
  14175. var type = geometryGroup.__typeArray === Uint32Array ? _gl.UNSIGNED_INT : _gl.UNSIGNED_SHORT;
  14176. // wireframe
  14177. if ( material.wireframe ) {
  14178. setLineWidth( material.wireframeLinewidth );
  14179. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  14180. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, type, 0 );
  14181. // triangles
  14182. } else {
  14183. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  14184. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, type, 0 );
  14185. }
  14186. _this.info.render.calls ++;
  14187. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  14188. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  14189. // render lines
  14190. } else if ( object instanceof THREE.Line ) {
  14191. var mode = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  14192. setLineWidth( material.linewidth );
  14193. _gl.drawArrays( mode, 0, geometryGroup.__webglLineCount );
  14194. _this.info.render.calls ++;
  14195. // render particles
  14196. } else if ( object instanceof THREE.ParticleSystem ) {
  14197. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  14198. _this.info.render.calls ++;
  14199. _this.info.render.points += geometryGroup.__webglParticleCount;
  14200. }
  14201. };
  14202. function initAttributes() {
  14203. for ( var i = 0, l = _newAttributes.length; i < l; i ++ ) {
  14204. _newAttributes[ i ] = 0;
  14205. }
  14206. }
  14207. function enableAttribute( attribute ) {
  14208. _newAttributes[ attribute ] = 1;
  14209. if ( _enabledAttributes[ attribute ] === 0 ) {
  14210. _gl.enableVertexAttribArray( attribute );
  14211. _enabledAttributes[ attribute ] = 1;
  14212. }
  14213. }
  14214. function disableUnusedAttributes() {
  14215. for ( var i = 0, l = _enabledAttributes.length; i < l; i ++ ) {
  14216. if ( _enabledAttributes[ i ] !== _newAttributes[ i ] ) {
  14217. _gl.disableVertexAttribArray( i );
  14218. _enabledAttributes[ i ] = 0;
  14219. }
  14220. }
  14221. }
  14222. function setupMorphTargets ( material, geometryGroup, object ) {
  14223. // set base
  14224. var attributes = material.program.attributes;
  14225. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  14226. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  14227. enableAttribute( attributes.position );
  14228. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14229. } else if ( attributes.position >= 0 ) {
  14230. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  14231. enableAttribute( attributes.position );
  14232. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  14233. }
  14234. if ( object.morphTargetForcedOrder.length ) {
  14235. // set forced order
  14236. var m = 0;
  14237. var order = object.morphTargetForcedOrder;
  14238. var influences = object.morphTargetInfluences;
  14239. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  14240. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  14241. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  14242. enableAttribute( attributes[ "morphTarget" + m ] );
  14243. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14244. }
  14245. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  14246. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  14247. enableAttribute( attributes[ "morphNormal" + m ] );
  14248. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14249. }
  14250. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  14251. m ++;
  14252. }
  14253. } else {
  14254. // find the most influencing
  14255. var influence, activeInfluenceIndices = [];
  14256. var influences = object.morphTargetInfluences;
  14257. var i, il = influences.length;
  14258. for ( i = 0; i < il; i ++ ) {
  14259. influence = influences[ i ];
  14260. if ( influence > 0 ) {
  14261. activeInfluenceIndices.push( [ influence, i ] );
  14262. }
  14263. }
  14264. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  14265. activeInfluenceIndices.sort( numericalSort );
  14266. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  14267. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  14268. activeInfluenceIndices.sort( numericalSort );
  14269. } else if ( activeInfluenceIndices.length === 0 ) {
  14270. activeInfluenceIndices.push( [ 0, 0 ] );
  14271. };
  14272. var influenceIndex, m = 0;
  14273. while ( m < material.numSupportedMorphTargets ) {
  14274. if ( activeInfluenceIndices[ m ] ) {
  14275. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  14276. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  14277. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  14278. enableAttribute( attributes[ "morphTarget" + m ] );
  14279. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14280. }
  14281. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  14282. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  14283. enableAttribute( attributes[ "morphNormal" + m ] );
  14284. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14285. }
  14286. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  14287. } else {
  14288. /*
  14289. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14290. if ( material.morphNormals ) {
  14291. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  14292. }
  14293. */
  14294. object.__webglMorphTargetInfluences[ m ] = 0;
  14295. }
  14296. m ++;
  14297. }
  14298. }
  14299. // load updated influences uniform
  14300. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  14301. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  14302. }
  14303. };
  14304. // Sorting
  14305. function painterSortStable ( a, b ) {
  14306. if ( a.z !== b.z ) {
  14307. return b.z - a.z;
  14308. } else {
  14309. return a.id - b.id;
  14310. }
  14311. };
  14312. function numericalSort ( a, b ) {
  14313. return b[ 0 ] - a[ 0 ];
  14314. };
  14315. // Rendering
  14316. this.render = function ( scene, camera, renderTarget, forceClear ) {
  14317. if ( camera instanceof THREE.Camera === false ) {
  14318. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  14319. return;
  14320. }
  14321. var i, il,
  14322. webglObject, object,
  14323. renderList,
  14324. lights = scene.__lights,
  14325. fog = scene.fog;
  14326. // reset caching for this frame
  14327. _currentMaterialId = -1;
  14328. _lightsNeedUpdate = true;
  14329. // update scene graph
  14330. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  14331. // update camera matrices and frustum
  14332. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  14333. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  14334. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  14335. _frustum.setFromMatrix( _projScreenMatrix );
  14336. // update WebGL objects
  14337. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  14338. // custom render plugins (pre pass)
  14339. renderPlugins( this.renderPluginsPre, scene, camera );
  14340. //
  14341. _this.info.render.calls = 0;
  14342. _this.info.render.vertices = 0;
  14343. _this.info.render.faces = 0;
  14344. _this.info.render.points = 0;
  14345. this.setRenderTarget( renderTarget );
  14346. if ( this.autoClear || forceClear ) {
  14347. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  14348. }
  14349. // set matrices for regular objects (frustum culled)
  14350. renderList = scene.__webglObjects;
  14351. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14352. webglObject = renderList[ i ];
  14353. object = webglObject.object;
  14354. webglObject.id = i;
  14355. webglObject.render = false;
  14356. if ( object.visible ) {
  14357. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  14358. setupMatrices( object, camera );
  14359. unrollBufferMaterial( webglObject );
  14360. webglObject.render = true;
  14361. if ( this.sortObjects === true ) {
  14362. if ( object.renderDepth !== null ) {
  14363. webglObject.z = object.renderDepth;
  14364. } else {
  14365. _vector3.setFromMatrixPosition( object.matrixWorld );
  14366. _vector3.applyProjection( _projScreenMatrix );
  14367. webglObject.z = _vector3.z;
  14368. }
  14369. }
  14370. }
  14371. }
  14372. }
  14373. if ( this.sortObjects ) {
  14374. renderList.sort( painterSortStable );
  14375. }
  14376. // set matrices for immediate objects
  14377. renderList = scene.__webglObjectsImmediate;
  14378. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  14379. webglObject = renderList[ i ];
  14380. object = webglObject.object;
  14381. if ( object.visible ) {
  14382. setupMatrices( object, camera );
  14383. unrollImmediateBufferMaterial( webglObject );
  14384. }
  14385. }
  14386. if ( scene.overrideMaterial ) {
  14387. var material = scene.overrideMaterial;
  14388. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14389. this.setDepthTest( material.depthTest );
  14390. this.setDepthWrite( material.depthWrite );
  14391. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14392. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  14393. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  14394. } else {
  14395. var material = null;
  14396. // opaque pass (front-to-back order)
  14397. this.setBlending( THREE.NoBlending );
  14398. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  14399. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  14400. // transparent pass (back-to-front order)
  14401. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  14402. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  14403. }
  14404. // custom render plugins (post pass)
  14405. renderPlugins( this.renderPluginsPost, scene, camera );
  14406. // Generate mipmap if we're using any kind of mipmap filtering
  14407. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  14408. updateRenderTargetMipmap( renderTarget );
  14409. }
  14410. // Ensure depth buffer writing is enabled so it can be cleared on next render
  14411. this.setDepthTest( true );
  14412. this.setDepthWrite( true );
  14413. // _gl.finish();
  14414. };
  14415. function renderPlugins( plugins, scene, camera ) {
  14416. if ( ! plugins.length ) return;
  14417. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  14418. // reset state for plugin (to start from clean slate)
  14419. _currentProgram = null;
  14420. _currentCamera = null;
  14421. _oldBlending = -1;
  14422. _oldDepthTest = -1;
  14423. _oldDepthWrite = -1;
  14424. _oldDoubleSided = -1;
  14425. _oldFlipSided = -1;
  14426. _currentGeometryGroupHash = -1;
  14427. _currentMaterialId = -1;
  14428. _lightsNeedUpdate = true;
  14429. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  14430. // reset state after plugin (anything could have changed)
  14431. _currentProgram = null;
  14432. _currentCamera = null;
  14433. _oldBlending = -1;
  14434. _oldDepthTest = -1;
  14435. _oldDepthWrite = -1;
  14436. _oldDoubleSided = -1;
  14437. _oldFlipSided = -1;
  14438. _currentGeometryGroupHash = -1;
  14439. _currentMaterialId = -1;
  14440. _lightsNeedUpdate = true;
  14441. }
  14442. };
  14443. function renderObjects( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14444. var webglObject, object, buffer, material, start, end, delta;
  14445. if ( reverse ) {
  14446. start = renderList.length - 1;
  14447. end = -1;
  14448. delta = -1;
  14449. } else {
  14450. start = 0;
  14451. end = renderList.length;
  14452. delta = 1;
  14453. }
  14454. for ( var i = start; i !== end; i += delta ) {
  14455. webglObject = renderList[ i ];
  14456. if ( webglObject.render ) {
  14457. object = webglObject.object;
  14458. buffer = webglObject.buffer;
  14459. if ( overrideMaterial ) {
  14460. material = overrideMaterial;
  14461. } else {
  14462. material = webglObject[ materialType ];
  14463. if ( ! material ) continue;
  14464. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14465. _this.setDepthTest( material.depthTest );
  14466. _this.setDepthWrite( material.depthWrite );
  14467. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14468. }
  14469. _this.setMaterialFaces( material );
  14470. if ( buffer instanceof THREE.BufferGeometry ) {
  14471. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  14472. } else {
  14473. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  14474. }
  14475. }
  14476. }
  14477. };
  14478. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  14479. var webglObject, object, material, program;
  14480. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  14481. webglObject = renderList[ i ];
  14482. object = webglObject.object;
  14483. if ( object.visible ) {
  14484. if ( overrideMaterial ) {
  14485. material = overrideMaterial;
  14486. } else {
  14487. material = webglObject[ materialType ];
  14488. if ( ! material ) continue;
  14489. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  14490. _this.setDepthTest( material.depthTest );
  14491. _this.setDepthWrite( material.depthWrite );
  14492. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  14493. }
  14494. _this.renderImmediateObject( camera, lights, fog, material, object );
  14495. }
  14496. }
  14497. };
  14498. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  14499. var program = setProgram( camera, lights, fog, material, object );
  14500. _currentGeometryGroupHash = -1;
  14501. _this.setMaterialFaces( material );
  14502. if ( object.immediateRenderCallback ) {
  14503. object.immediateRenderCallback( program, _gl, _frustum );
  14504. } else {
  14505. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  14506. }
  14507. };
  14508. function unrollImmediateBufferMaterial ( globject ) {
  14509. var object = globject.object,
  14510. material = object.material;
  14511. if ( material.transparent ) {
  14512. globject.transparent = material;
  14513. globject.opaque = null;
  14514. } else {
  14515. globject.opaque = material;
  14516. globject.transparent = null;
  14517. }
  14518. };
  14519. function unrollBufferMaterial ( globject ) {
  14520. var object = globject.object;
  14521. var buffer = globject.buffer;
  14522. var geometry = object.geometry;
  14523. var material = object.material;
  14524. if ( material instanceof THREE.MeshFaceMaterial ) {
  14525. var materialIndex = geometry instanceof THREE.BufferGeometry ? 0 : buffer.materialIndex;
  14526. material = material.materials[ materialIndex ];
  14527. if ( material.transparent ) {
  14528. globject.transparent = material;
  14529. globject.opaque = null;
  14530. } else {
  14531. globject.opaque = material;
  14532. globject.transparent = null;
  14533. }
  14534. } else {
  14535. if ( material ) {
  14536. if ( material.transparent ) {
  14537. globject.transparent = material;
  14538. globject.opaque = null;
  14539. } else {
  14540. globject.opaque = material;
  14541. globject.transparent = null;
  14542. }
  14543. }
  14544. }
  14545. };
  14546. // Objects refresh
  14547. this.initWebGLObjects = function ( scene ) {
  14548. if ( !scene.__webglObjects ) {
  14549. scene.__webglObjects = [];
  14550. scene.__webglObjectsImmediate = [];
  14551. scene.__webglSprites = [];
  14552. scene.__webglFlares = [];
  14553. }
  14554. while ( scene.__objectsAdded.length ) {
  14555. addObject( scene.__objectsAdded[ 0 ], scene );
  14556. scene.__objectsAdded.splice( 0, 1 );
  14557. }
  14558. while ( scene.__objectsRemoved.length ) {
  14559. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14560. scene.__objectsRemoved.splice( 0, 1 );
  14561. }
  14562. // update must be called after objects adding / removal
  14563. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14564. var object = scene.__webglObjects[ o ].object;
  14565. // TODO: Remove this hack (WebGLRenderer refactoring)
  14566. if ( object.__webglInit === undefined ) {
  14567. if ( object.__webglActive !== undefined ) {
  14568. removeObject( object, scene );
  14569. }
  14570. addObject( object, scene );
  14571. }
  14572. updateObject( object );
  14573. }
  14574. };
  14575. // Objects adding
  14576. function addObject( object, scene ) {
  14577. var g, geometry, material, geometryGroup;
  14578. if ( object.__webglInit === undefined ) {
  14579. object.__webglInit = true;
  14580. object._modelViewMatrix = new THREE.Matrix4();
  14581. object._normalMatrix = new THREE.Matrix3();
  14582. geometry = object.geometry;
  14583. if ( geometry === undefined ) {
  14584. // ImmediateRenderObject
  14585. } else if ( geometry.__webglInit === undefined ) {
  14586. geometry.__webglInit = true;
  14587. geometry.addEventListener( 'dispose', onGeometryDispose );
  14588. if ( geometry instanceof THREE.BufferGeometry ) {
  14589. initDirectBuffers( geometry );
  14590. } else if ( object instanceof THREE.Mesh ) {
  14591. material = object.material;
  14592. if ( geometry.geometryGroups === undefined ) {
  14593. geometry.makeGroups( material instanceof THREE.MeshFaceMaterial, _glExtensionElementIndexUint ? 4294967296 : 65535 );
  14594. }
  14595. // create separate VBOs per geometry chunk
  14596. for ( g in geometry.geometryGroups ) {
  14597. geometryGroup = geometry.geometryGroups[ g ];
  14598. // initialise VBO on the first access
  14599. if ( ! geometryGroup.__webglVertexBuffer ) {
  14600. createMeshBuffers( geometryGroup );
  14601. initMeshBuffers( geometryGroup, object );
  14602. geometry.verticesNeedUpdate = true;
  14603. geometry.morphTargetsNeedUpdate = true;
  14604. geometry.elementsNeedUpdate = true;
  14605. geometry.uvsNeedUpdate = true;
  14606. geometry.normalsNeedUpdate = true;
  14607. geometry.tangentsNeedUpdate = true;
  14608. geometry.colorsNeedUpdate = true;
  14609. }
  14610. }
  14611. } else if ( object instanceof THREE.Line ) {
  14612. if ( ! geometry.__webglVertexBuffer ) {
  14613. createLineBuffers( geometry );
  14614. initLineBuffers( geometry, object );
  14615. geometry.verticesNeedUpdate = true;
  14616. geometry.colorsNeedUpdate = true;
  14617. geometry.lineDistancesNeedUpdate = true;
  14618. }
  14619. } else if ( object instanceof THREE.ParticleSystem ) {
  14620. if ( ! geometry.__webglVertexBuffer ) {
  14621. createParticleBuffers( geometry );
  14622. initParticleBuffers( geometry, object );
  14623. geometry.verticesNeedUpdate = true;
  14624. geometry.colorsNeedUpdate = true;
  14625. }
  14626. }
  14627. }
  14628. }
  14629. if ( object.__webglActive === undefined ) {
  14630. if ( object instanceof THREE.Mesh ) {
  14631. geometry = object.geometry;
  14632. if ( geometry instanceof THREE.BufferGeometry ) {
  14633. addBuffer( scene.__webglObjects, geometry, object );
  14634. } else if ( geometry instanceof THREE.Geometry ) {
  14635. for ( g in geometry.geometryGroups ) {
  14636. geometryGroup = geometry.geometryGroups[ g ];
  14637. addBuffer( scene.__webglObjects, geometryGroup, object );
  14638. }
  14639. }
  14640. } else if ( object instanceof THREE.Line ||
  14641. object instanceof THREE.ParticleSystem ) {
  14642. geometry = object.geometry;
  14643. addBuffer( scene.__webglObjects, geometry, object );
  14644. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14645. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14646. } else if ( object instanceof THREE.Sprite ) {
  14647. scene.__webglSprites.push( object );
  14648. } else if ( object instanceof THREE.LensFlare ) {
  14649. scene.__webglFlares.push( object );
  14650. }
  14651. object.__webglActive = true;
  14652. }
  14653. };
  14654. function addBuffer( objlist, buffer, object ) {
  14655. objlist.push(
  14656. {
  14657. id: null,
  14658. buffer: buffer,
  14659. object: object,
  14660. opaque: null,
  14661. transparent: null,
  14662. z: 0
  14663. }
  14664. );
  14665. };
  14666. function addBufferImmediate( objlist, object ) {
  14667. objlist.push(
  14668. {
  14669. id: null,
  14670. object: object,
  14671. opaque: null,
  14672. transparent: null,
  14673. z: 0
  14674. }
  14675. );
  14676. };
  14677. // Objects updates
  14678. function updateObject( object ) {
  14679. var geometry = object.geometry,
  14680. geometryGroup, customAttributesDirty, material;
  14681. if ( geometry instanceof THREE.BufferGeometry ) {
  14682. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW );
  14683. } else if ( object instanceof THREE.Mesh ) {
  14684. // check all geometry groups
  14685. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14686. geometryGroup = geometry.geometryGroupsList[ i ];
  14687. material = getBufferMaterial( object, geometryGroup );
  14688. if ( geometry.buffersNeedUpdate ) {
  14689. initMeshBuffers( geometryGroup, object );
  14690. }
  14691. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14692. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14693. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14694. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14695. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14696. }
  14697. }
  14698. geometry.verticesNeedUpdate = false;
  14699. geometry.morphTargetsNeedUpdate = false;
  14700. geometry.elementsNeedUpdate = false;
  14701. geometry.uvsNeedUpdate = false;
  14702. geometry.normalsNeedUpdate = false;
  14703. geometry.colorsNeedUpdate = false;
  14704. geometry.tangentsNeedUpdate = false;
  14705. geometry.buffersNeedUpdate = false;
  14706. material.attributes && clearCustomAttributes( material );
  14707. } else if ( object instanceof THREE.Line ) {
  14708. material = getBufferMaterial( object, geometry );
  14709. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14710. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14711. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14712. }
  14713. geometry.verticesNeedUpdate = false;
  14714. geometry.colorsNeedUpdate = false;
  14715. geometry.lineDistancesNeedUpdate = false;
  14716. material.attributes && clearCustomAttributes( material );
  14717. } else if ( object instanceof THREE.ParticleSystem ) {
  14718. material = getBufferMaterial( object, geometry );
  14719. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14720. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14721. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14722. }
  14723. geometry.verticesNeedUpdate = false;
  14724. geometry.colorsNeedUpdate = false;
  14725. material.attributes && clearCustomAttributes( material );
  14726. }
  14727. };
  14728. // Objects updates - custom attributes check
  14729. function areCustomAttributesDirty( material ) {
  14730. for ( var a in material.attributes ) {
  14731. if ( material.attributes[ a ].needsUpdate ) return true;
  14732. }
  14733. return false;
  14734. };
  14735. function clearCustomAttributes( material ) {
  14736. for ( var a in material.attributes ) {
  14737. material.attributes[ a ].needsUpdate = false;
  14738. }
  14739. };
  14740. // Objects removal
  14741. function removeObject( object, scene ) {
  14742. if ( object instanceof THREE.Mesh ||
  14743. object instanceof THREE.ParticleSystem ||
  14744. object instanceof THREE.Line ) {
  14745. removeInstances( scene.__webglObjects, object );
  14746. } else if ( object instanceof THREE.Sprite ) {
  14747. removeInstancesDirect( scene.__webglSprites, object );
  14748. } else if ( object instanceof THREE.LensFlare ) {
  14749. removeInstancesDirect( scene.__webglFlares, object );
  14750. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14751. removeInstances( scene.__webglObjectsImmediate, object );
  14752. }
  14753. delete object.__webglActive;
  14754. };
  14755. function removeInstances( objlist, object ) {
  14756. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14757. if ( objlist[ o ].object === object ) {
  14758. objlist.splice( o, 1 );
  14759. }
  14760. }
  14761. };
  14762. function removeInstancesDirect( objlist, object ) {
  14763. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14764. if ( objlist[ o ] === object ) {
  14765. objlist.splice( o, 1 );
  14766. }
  14767. }
  14768. };
  14769. // Materials
  14770. this.initMaterial = function ( material, lights, fog, object ) {
  14771. material.addEventListener( 'dispose', onMaterialDispose );
  14772. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14773. if ( material instanceof THREE.MeshDepthMaterial ) {
  14774. shaderID = 'depth';
  14775. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14776. shaderID = 'normal';
  14777. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14778. shaderID = 'basic';
  14779. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14780. shaderID = 'lambert';
  14781. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14782. shaderID = 'phong';
  14783. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14784. shaderID = 'basic';
  14785. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14786. shaderID = 'dashed';
  14787. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14788. shaderID = 'particle_basic';
  14789. }
  14790. if ( shaderID ) {
  14791. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14792. }
  14793. // heuristics to create shader parameters according to lights in the scene
  14794. // (not to blow over maxLights budget)
  14795. maxLightCount = allocateLights( lights );
  14796. maxShadows = allocateShadows( lights );
  14797. maxBones = allocateBones( object );
  14798. parameters = {
  14799. precision: _precision,
  14800. supportsVertexTextures: _supportsVertexTextures,
  14801. map: !!material.map,
  14802. envMap: !!material.envMap,
  14803. lightMap: !!material.lightMap,
  14804. bumpMap: !!material.bumpMap,
  14805. normalMap: !!material.normalMap,
  14806. specularMap: !!material.specularMap,
  14807. vertexColors: material.vertexColors,
  14808. fog: fog,
  14809. useFog: material.fog,
  14810. fogExp: fog instanceof THREE.FogExp2,
  14811. sizeAttenuation: material.sizeAttenuation,
  14812. logarithmicDepthBuffer: _logarithmicDepthBuffer,
  14813. skinning: material.skinning,
  14814. maxBones: maxBones,
  14815. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14816. morphTargets: material.morphTargets,
  14817. morphNormals: material.morphNormals,
  14818. maxMorphTargets: this.maxMorphTargets,
  14819. maxMorphNormals: this.maxMorphNormals,
  14820. maxDirLights: maxLightCount.directional,
  14821. maxPointLights: maxLightCount.point,
  14822. maxSpotLights: maxLightCount.spot,
  14823. maxHemiLights: maxLightCount.hemi,
  14824. maxShadows: maxShadows,
  14825. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow && maxShadows > 0,
  14826. shadowMapType: this.shadowMapType,
  14827. shadowMapDebug: this.shadowMapDebug,
  14828. shadowMapCascade: this.shadowMapCascade,
  14829. alphaTest: material.alphaTest,
  14830. metal: material.metal,
  14831. wrapAround: material.wrapAround,
  14832. doubleSided: material.side === THREE.DoubleSide,
  14833. flipSided: material.side === THREE.BackSide
  14834. };
  14835. // Generate code
  14836. var chunks = [];
  14837. if ( shaderID ) {
  14838. chunks.push( shaderID );
  14839. } else {
  14840. chunks.push( material.fragmentShader );
  14841. chunks.push( material.vertexShader );
  14842. }
  14843. for ( var d in material.defines ) {
  14844. chunks.push( d );
  14845. chunks.push( material.defines[ d ] );
  14846. }
  14847. for ( var p in parameters ) {
  14848. chunks.push( p );
  14849. chunks.push( parameters[ p ] );
  14850. }
  14851. var code = chunks.join();
  14852. var program;
  14853. // Check if code has been already compiled
  14854. for ( var p = 0, pl = _programs.length; p < pl; p ++ ) {
  14855. var programInfo = _programs[ p ];
  14856. if ( programInfo.code === code ) {
  14857. program = programInfo;
  14858. program.usedTimes ++;
  14859. break;
  14860. }
  14861. }
  14862. if ( program === undefined ) {
  14863. program = new THREE.WebGLProgram( this, code, material, parameters );
  14864. _programs.push( program );
  14865. _this.info.memory.programs = _programs.length;
  14866. }
  14867. material.program = program;
  14868. var attributes = material.program.attributes;
  14869. if ( material.morphTargets ) {
  14870. material.numSupportedMorphTargets = 0;
  14871. var id, base = "morphTarget";
  14872. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14873. id = base + i;
  14874. if ( attributes[ id ] >= 0 ) {
  14875. material.numSupportedMorphTargets ++;
  14876. }
  14877. }
  14878. }
  14879. if ( material.morphNormals ) {
  14880. material.numSupportedMorphNormals = 0;
  14881. var id, base = "morphNormal";
  14882. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14883. id = base + i;
  14884. if ( attributes[ id ] >= 0 ) {
  14885. material.numSupportedMorphNormals ++;
  14886. }
  14887. }
  14888. }
  14889. material.uniformsList = [];
  14890. for ( u in material.uniforms ) {
  14891. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14892. }
  14893. };
  14894. function setMaterialShaders( material, shaders ) {
  14895. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14896. material.vertexShader = shaders.vertexShader;
  14897. material.fragmentShader = shaders.fragmentShader;
  14898. };
  14899. function setProgram( camera, lights, fog, material, object ) {
  14900. _usedTextureUnits = 0;
  14901. if ( material.needsUpdate ) {
  14902. if ( material.program ) deallocateMaterial( material );
  14903. _this.initMaterial( material, lights, fog, object );
  14904. material.needsUpdate = false;
  14905. }
  14906. if ( material.morphTargets ) {
  14907. if ( ! object.__webglMorphTargetInfluences ) {
  14908. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14909. }
  14910. }
  14911. var refreshMaterial = false;
  14912. var program = material.program,
  14913. p_uniforms = program.uniforms,
  14914. m_uniforms = material.uniforms;
  14915. if ( program.id !== _currentProgram ) {
  14916. _gl.useProgram( program.program );
  14917. _currentProgram = program.id;
  14918. refreshMaterial = true;
  14919. }
  14920. if ( material.id !== _currentMaterialId ) {
  14921. _currentMaterialId = material.id;
  14922. refreshMaterial = true;
  14923. }
  14924. if ( refreshMaterial || camera !== _currentCamera ) {
  14925. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14926. if ( _logarithmicDepthBuffer ) {
  14927. _gl.uniform1f(p_uniforms.logDepthBufFC, 2.0 / (Math.log(camera.far + 1.0) / Math.LN2));
  14928. }
  14929. if ( camera !== _currentCamera ) _currentCamera = camera;
  14930. }
  14931. // skinning uniforms must be set even if material didn't change
  14932. // auto-setting of texture unit for bone texture must go before other textures
  14933. // not sure why, but otherwise weird things happen
  14934. if ( material.skinning ) {
  14935. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14936. if ( p_uniforms.boneTexture !== null ) {
  14937. var textureUnit = getTextureUnit();
  14938. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14939. _this.setTexture( object.boneTexture, textureUnit );
  14940. }
  14941. if ( p_uniforms.boneTextureWidth !== null ) {
  14942. _gl.uniform1i( p_uniforms.boneTextureWidth, object.boneTextureWidth );
  14943. }
  14944. if ( p_uniforms.boneTextureHeight !== null ) {
  14945. _gl.uniform1i( p_uniforms.boneTextureHeight, object.boneTextureHeight );
  14946. }
  14947. } else {
  14948. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14949. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14950. }
  14951. }
  14952. }
  14953. if ( refreshMaterial ) {
  14954. // refresh uniforms common to several materials
  14955. if ( fog && material.fog ) {
  14956. refreshUniformsFog( m_uniforms, fog );
  14957. }
  14958. if ( material instanceof THREE.MeshPhongMaterial ||
  14959. material instanceof THREE.MeshLambertMaterial ||
  14960. material.lights ) {
  14961. if ( _lightsNeedUpdate ) {
  14962. setupLights( program, lights );
  14963. _lightsNeedUpdate = false;
  14964. }
  14965. refreshUniformsLights( m_uniforms, _lights );
  14966. }
  14967. if ( material instanceof THREE.MeshBasicMaterial ||
  14968. material instanceof THREE.MeshLambertMaterial ||
  14969. material instanceof THREE.MeshPhongMaterial ) {
  14970. refreshUniformsCommon( m_uniforms, material );
  14971. }
  14972. // refresh single material specific uniforms
  14973. if ( material instanceof THREE.LineBasicMaterial ) {
  14974. refreshUniformsLine( m_uniforms, material );
  14975. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14976. refreshUniformsLine( m_uniforms, material );
  14977. refreshUniformsDash( m_uniforms, material );
  14978. } else if ( material instanceof THREE.ParticleSystemMaterial ) {
  14979. refreshUniformsParticle( m_uniforms, material );
  14980. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14981. refreshUniformsPhong( m_uniforms, material );
  14982. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14983. refreshUniformsLambert( m_uniforms, material );
  14984. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14985. m_uniforms.mNear.value = camera.near;
  14986. m_uniforms.mFar.value = camera.far;
  14987. m_uniforms.opacity.value = material.opacity;
  14988. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14989. m_uniforms.opacity.value = material.opacity;
  14990. }
  14991. if ( object.receiveShadow && ! material._shadowPass ) {
  14992. refreshUniformsShadow( m_uniforms, lights );
  14993. }
  14994. // load common uniforms
  14995. loadUniformsGeneric( program, material.uniformsList );
  14996. // load material specific uniforms
  14997. // (shader material also gets them for the sake of genericity)
  14998. if ( material instanceof THREE.ShaderMaterial ||
  14999. material instanceof THREE.MeshPhongMaterial ||
  15000. material.envMap ) {
  15001. if ( p_uniforms.cameraPosition !== null ) {
  15002. _vector3.setFromMatrixPosition( camera.matrixWorld );
  15003. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  15004. }
  15005. }
  15006. if ( material instanceof THREE.MeshPhongMaterial ||
  15007. material instanceof THREE.MeshLambertMaterial ||
  15008. material instanceof THREE.ShaderMaterial ||
  15009. material.skinning ) {
  15010. if ( p_uniforms.viewMatrix !== null ) {
  15011. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  15012. }
  15013. }
  15014. }
  15015. loadUniformsMatrices( p_uniforms, object );
  15016. if ( p_uniforms.modelMatrix !== null ) {
  15017. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  15018. }
  15019. return program;
  15020. };
  15021. // Uniforms (refresh uniforms objects)
  15022. function refreshUniformsCommon ( uniforms, material ) {
  15023. uniforms.opacity.value = material.opacity;
  15024. if ( _this.gammaInput ) {
  15025. uniforms.diffuse.value.copyGammaToLinear( material.color );
  15026. } else {
  15027. uniforms.diffuse.value = material.color;
  15028. }
  15029. uniforms.map.value = material.map;
  15030. uniforms.lightMap.value = material.lightMap;
  15031. uniforms.specularMap.value = material.specularMap;
  15032. if ( material.bumpMap ) {
  15033. uniforms.bumpMap.value = material.bumpMap;
  15034. uniforms.bumpScale.value = material.bumpScale;
  15035. }
  15036. if ( material.normalMap ) {
  15037. uniforms.normalMap.value = material.normalMap;
  15038. uniforms.normalScale.value.copy( material.normalScale );
  15039. }
  15040. // uv repeat and offset setting priorities
  15041. // 1. color map
  15042. // 2. specular map
  15043. // 3. normal map
  15044. // 4. bump map
  15045. var uvScaleMap;
  15046. if ( material.map ) {
  15047. uvScaleMap = material.map;
  15048. } else if ( material.specularMap ) {
  15049. uvScaleMap = material.specularMap;
  15050. } else if ( material.normalMap ) {
  15051. uvScaleMap = material.normalMap;
  15052. } else if ( material.bumpMap ) {
  15053. uvScaleMap = material.bumpMap;
  15054. }
  15055. if ( uvScaleMap !== undefined ) {
  15056. var offset = uvScaleMap.offset;
  15057. var repeat = uvScaleMap.repeat;
  15058. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  15059. }
  15060. uniforms.envMap.value = material.envMap;
  15061. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  15062. if ( _this.gammaInput ) {
  15063. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  15064. uniforms.reflectivity.value = material.reflectivity;
  15065. } else {
  15066. uniforms.reflectivity.value = material.reflectivity;
  15067. }
  15068. uniforms.refractionRatio.value = material.refractionRatio;
  15069. uniforms.combine.value = material.combine;
  15070. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  15071. };
  15072. function refreshUniformsLine ( uniforms, material ) {
  15073. uniforms.diffuse.value = material.color;
  15074. uniforms.opacity.value = material.opacity;
  15075. };
  15076. function refreshUniformsDash ( uniforms, material ) {
  15077. uniforms.dashSize.value = material.dashSize;
  15078. uniforms.totalSize.value = material.dashSize + material.gapSize;
  15079. uniforms.scale.value = material.scale;
  15080. };
  15081. function refreshUniformsParticle ( uniforms, material ) {
  15082. uniforms.psColor.value = material.color;
  15083. uniforms.opacity.value = material.opacity;
  15084. uniforms.size.value = material.size;
  15085. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  15086. uniforms.map.value = material.map;
  15087. };
  15088. function refreshUniformsFog ( uniforms, fog ) {
  15089. uniforms.fogColor.value = fog.color;
  15090. if ( fog instanceof THREE.Fog ) {
  15091. uniforms.fogNear.value = fog.near;
  15092. uniforms.fogFar.value = fog.far;
  15093. } else if ( fog instanceof THREE.FogExp2 ) {
  15094. uniforms.fogDensity.value = fog.density;
  15095. }
  15096. };
  15097. function refreshUniformsPhong ( uniforms, material ) {
  15098. uniforms.shininess.value = material.shininess;
  15099. if ( _this.gammaInput ) {
  15100. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  15101. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  15102. uniforms.specular.value.copyGammaToLinear( material.specular );
  15103. } else {
  15104. uniforms.ambient.value = material.ambient;
  15105. uniforms.emissive.value = material.emissive;
  15106. uniforms.specular.value = material.specular;
  15107. }
  15108. if ( material.wrapAround ) {
  15109. uniforms.wrapRGB.value.copy( material.wrapRGB );
  15110. }
  15111. };
  15112. function refreshUniformsLambert ( uniforms, material ) {
  15113. if ( _this.gammaInput ) {
  15114. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  15115. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  15116. } else {
  15117. uniforms.ambient.value = material.ambient;
  15118. uniforms.emissive.value = material.emissive;
  15119. }
  15120. if ( material.wrapAround ) {
  15121. uniforms.wrapRGB.value.copy( material.wrapRGB );
  15122. }
  15123. };
  15124. function refreshUniformsLights ( uniforms, lights ) {
  15125. uniforms.ambientLightColor.value = lights.ambient;
  15126. uniforms.directionalLightColor.value = lights.directional.colors;
  15127. uniforms.directionalLightDirection.value = lights.directional.positions;
  15128. uniforms.pointLightColor.value = lights.point.colors;
  15129. uniforms.pointLightPosition.value = lights.point.positions;
  15130. uniforms.pointLightDistance.value = lights.point.distances;
  15131. uniforms.spotLightColor.value = lights.spot.colors;
  15132. uniforms.spotLightPosition.value = lights.spot.positions;
  15133. uniforms.spotLightDistance.value = lights.spot.distances;
  15134. uniforms.spotLightDirection.value = lights.spot.directions;
  15135. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  15136. uniforms.spotLightExponent.value = lights.spot.exponents;
  15137. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  15138. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  15139. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  15140. };
  15141. function refreshUniformsShadow ( uniforms, lights ) {
  15142. if ( uniforms.shadowMatrix ) {
  15143. var j = 0;
  15144. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  15145. var light = lights[ i ];
  15146. if ( ! light.castShadow ) continue;
  15147. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  15148. uniforms.shadowMap.value[ j ] = light.shadowMap;
  15149. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  15150. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  15151. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  15152. uniforms.shadowBias.value[ j ] = light.shadowBias;
  15153. j ++;
  15154. }
  15155. }
  15156. }
  15157. };
  15158. // Uniforms (load to GPU)
  15159. function loadUniformsMatrices ( uniforms, object ) {
  15160. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  15161. if ( uniforms.normalMatrix ) {
  15162. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  15163. }
  15164. };
  15165. function getTextureUnit() {
  15166. var textureUnit = _usedTextureUnits;
  15167. if ( textureUnit >= _maxTextures ) {
  15168. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  15169. }
  15170. _usedTextureUnits += 1;
  15171. return textureUnit;
  15172. };
  15173. function loadUniformsGeneric ( program, uniforms ) {
  15174. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  15175. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  15176. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  15177. if ( !location ) continue;
  15178. uniform = uniforms[ j ][ 0 ];
  15179. type = uniform.type;
  15180. value = uniform.value;
  15181. if ( type === "i" ) { // single integer
  15182. _gl.uniform1i( location, value );
  15183. } else if ( type === "f" ) { // single float
  15184. _gl.uniform1f( location, value );
  15185. } else if ( type === "v2" ) { // single THREE.Vector2
  15186. _gl.uniform2f( location, value.x, value.y );
  15187. } else if ( type === "v3" ) { // single THREE.Vector3
  15188. _gl.uniform3f( location, value.x, value.y, value.z );
  15189. } else if ( type === "v4" ) { // single THREE.Vector4
  15190. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  15191. } else if ( type === "c" ) { // single THREE.Color
  15192. _gl.uniform3f( location, value.r, value.g, value.b );
  15193. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  15194. _gl.uniform1iv( location, value );
  15195. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  15196. _gl.uniform3iv( location, value );
  15197. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  15198. _gl.uniform1fv( location, value );
  15199. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  15200. _gl.uniform3fv( location, value );
  15201. } else if ( type === "v2v" ) { // array of THREE.Vector2
  15202. if ( uniform._array === undefined ) {
  15203. uniform._array = new Float32Array( 2 * value.length );
  15204. }
  15205. for ( i = 0, il = value.length; i < il; i ++ ) {
  15206. offset = i * 2;
  15207. uniform._array[ offset ] = value[ i ].x;
  15208. uniform._array[ offset + 1 ] = value[ i ].y;
  15209. }
  15210. _gl.uniform2fv( location, uniform._array );
  15211. } else if ( type === "v3v" ) { // array of THREE.Vector3
  15212. if ( uniform._array === undefined ) {
  15213. uniform._array = new Float32Array( 3 * value.length );
  15214. }
  15215. for ( i = 0, il = value.length; i < il; i ++ ) {
  15216. offset = i * 3;
  15217. uniform._array[ offset ] = value[ i ].x;
  15218. uniform._array[ offset + 1 ] = value[ i ].y;
  15219. uniform._array[ offset + 2 ] = value[ i ].z;
  15220. }
  15221. _gl.uniform3fv( location, uniform._array );
  15222. } else if ( type === "v4v" ) { // array of THREE.Vector4
  15223. if ( uniform._array === undefined ) {
  15224. uniform._array = new Float32Array( 4 * value.length );
  15225. }
  15226. for ( i = 0, il = value.length; i < il; i ++ ) {
  15227. offset = i * 4;
  15228. uniform._array[ offset ] = value[ i ].x;
  15229. uniform._array[ offset + 1 ] = value[ i ].y;
  15230. uniform._array[ offset + 2 ] = value[ i ].z;
  15231. uniform._array[ offset + 3 ] = value[ i ].w;
  15232. }
  15233. _gl.uniform4fv( location, uniform._array );
  15234. } else if ( type === "m4") { // single THREE.Matrix4
  15235. if ( uniform._array === undefined ) {
  15236. uniform._array = new Float32Array( 16 );
  15237. }
  15238. value.flattenToArray( uniform._array );
  15239. _gl.uniformMatrix4fv( location, false, uniform._array );
  15240. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  15241. if ( uniform._array === undefined ) {
  15242. uniform._array = new Float32Array( 16 * value.length );
  15243. }
  15244. for ( i = 0, il = value.length; i < il; i ++ ) {
  15245. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  15246. }
  15247. _gl.uniformMatrix4fv( location, false, uniform._array );
  15248. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  15249. texture = value;
  15250. textureUnit = getTextureUnit();
  15251. _gl.uniform1i( location, textureUnit );
  15252. if ( !texture ) continue;
  15253. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  15254. setCubeTexture( texture, textureUnit );
  15255. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  15256. setCubeTextureDynamic( texture, textureUnit );
  15257. } else {
  15258. _this.setTexture( texture, textureUnit );
  15259. }
  15260. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  15261. if ( uniform._array === undefined ) {
  15262. uniform._array = [];
  15263. }
  15264. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  15265. uniform._array[ i ] = getTextureUnit();
  15266. }
  15267. _gl.uniform1iv( location, uniform._array );
  15268. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  15269. texture = uniform.value[ i ];
  15270. textureUnit = uniform._array[ i ];
  15271. if ( !texture ) continue;
  15272. _this.setTexture( texture, textureUnit );
  15273. }
  15274. } else {
  15275. console.warn( 'THREE.WebGLRenderer: Unknown uniform type: ' + type );
  15276. }
  15277. }
  15278. };
  15279. function setupMatrices ( object, camera ) {
  15280. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  15281. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  15282. };
  15283. //
  15284. function setColorGamma( array, offset, color, intensitySq ) {
  15285. array[ offset ] = color.r * color.r * intensitySq;
  15286. array[ offset + 1 ] = color.g * color.g * intensitySq;
  15287. array[ offset + 2 ] = color.b * color.b * intensitySq;
  15288. };
  15289. function setColorLinear( array, offset, color, intensity ) {
  15290. array[ offset ] = color.r * intensity;
  15291. array[ offset + 1 ] = color.g * intensity;
  15292. array[ offset + 2 ] = color.b * intensity;
  15293. };
  15294. function setupLights ( program, lights ) {
  15295. var l, ll, light, n,
  15296. r = 0, g = 0, b = 0,
  15297. color, skyColor, groundColor,
  15298. intensity, intensitySq,
  15299. position,
  15300. distance,
  15301. zlights = _lights,
  15302. dirColors = zlights.directional.colors,
  15303. dirPositions = zlights.directional.positions,
  15304. pointColors = zlights.point.colors,
  15305. pointPositions = zlights.point.positions,
  15306. pointDistances = zlights.point.distances,
  15307. spotColors = zlights.spot.colors,
  15308. spotPositions = zlights.spot.positions,
  15309. spotDistances = zlights.spot.distances,
  15310. spotDirections = zlights.spot.directions,
  15311. spotAnglesCos = zlights.spot.anglesCos,
  15312. spotExponents = zlights.spot.exponents,
  15313. hemiSkyColors = zlights.hemi.skyColors,
  15314. hemiGroundColors = zlights.hemi.groundColors,
  15315. hemiPositions = zlights.hemi.positions,
  15316. dirLength = 0,
  15317. pointLength = 0,
  15318. spotLength = 0,
  15319. hemiLength = 0,
  15320. dirCount = 0,
  15321. pointCount = 0,
  15322. spotCount = 0,
  15323. hemiCount = 0,
  15324. dirOffset = 0,
  15325. pointOffset = 0,
  15326. spotOffset = 0,
  15327. hemiOffset = 0;
  15328. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  15329. light = lights[ l ];
  15330. if ( light.onlyShadow ) continue;
  15331. color = light.color;
  15332. intensity = light.intensity;
  15333. distance = light.distance;
  15334. if ( light instanceof THREE.AmbientLight ) {
  15335. if ( ! light.visible ) continue;
  15336. if ( _this.gammaInput ) {
  15337. r += color.r * color.r;
  15338. g += color.g * color.g;
  15339. b += color.b * color.b;
  15340. } else {
  15341. r += color.r;
  15342. g += color.g;
  15343. b += color.b;
  15344. }
  15345. } else if ( light instanceof THREE.DirectionalLight ) {
  15346. dirCount += 1;
  15347. if ( ! light.visible ) continue;
  15348. _direction.setFromMatrixPosition( light.matrixWorld );
  15349. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15350. _direction.sub( _vector3 );
  15351. _direction.normalize();
  15352. // skip lights with undefined direction
  15353. // these create troubles in OpenGL (making pixel black)
  15354. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15355. dirOffset = dirLength * 3;
  15356. dirPositions[ dirOffset ] = _direction.x;
  15357. dirPositions[ dirOffset + 1 ] = _direction.y;
  15358. dirPositions[ dirOffset + 2 ] = _direction.z;
  15359. if ( _this.gammaInput ) {
  15360. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  15361. } else {
  15362. setColorLinear( dirColors, dirOffset, color, intensity );
  15363. }
  15364. dirLength += 1;
  15365. } else if ( light instanceof THREE.PointLight ) {
  15366. pointCount += 1;
  15367. if ( ! light.visible ) continue;
  15368. pointOffset = pointLength * 3;
  15369. if ( _this.gammaInput ) {
  15370. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  15371. } else {
  15372. setColorLinear( pointColors, pointOffset, color, intensity );
  15373. }
  15374. _vector3.setFromMatrixPosition( light.matrixWorld );
  15375. pointPositions[ pointOffset ] = _vector3.x;
  15376. pointPositions[ pointOffset + 1 ] = _vector3.y;
  15377. pointPositions[ pointOffset + 2 ] = _vector3.z;
  15378. pointDistances[ pointLength ] = distance;
  15379. pointLength += 1;
  15380. } else if ( light instanceof THREE.SpotLight ) {
  15381. spotCount += 1;
  15382. if ( ! light.visible ) continue;
  15383. spotOffset = spotLength * 3;
  15384. if ( _this.gammaInput ) {
  15385. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  15386. } else {
  15387. setColorLinear( spotColors, spotOffset, color, intensity );
  15388. }
  15389. _vector3.setFromMatrixPosition( light.matrixWorld );
  15390. spotPositions[ spotOffset ] = _vector3.x;
  15391. spotPositions[ spotOffset + 1 ] = _vector3.y;
  15392. spotPositions[ spotOffset + 2 ] = _vector3.z;
  15393. spotDistances[ spotLength ] = distance;
  15394. _direction.copy( _vector3 );
  15395. _vector3.setFromMatrixPosition( light.target.matrixWorld );
  15396. _direction.sub( _vector3 );
  15397. _direction.normalize();
  15398. spotDirections[ spotOffset ] = _direction.x;
  15399. spotDirections[ spotOffset + 1 ] = _direction.y;
  15400. spotDirections[ spotOffset + 2 ] = _direction.z;
  15401. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  15402. spotExponents[ spotLength ] = light.exponent;
  15403. spotLength += 1;
  15404. } else if ( light instanceof THREE.HemisphereLight ) {
  15405. hemiCount += 1;
  15406. if ( ! light.visible ) continue;
  15407. _direction.setFromMatrixPosition( light.matrixWorld );
  15408. _direction.normalize();
  15409. // skip lights with undefined direction
  15410. // these create troubles in OpenGL (making pixel black)
  15411. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  15412. hemiOffset = hemiLength * 3;
  15413. hemiPositions[ hemiOffset ] = _direction.x;
  15414. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  15415. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  15416. skyColor = light.color;
  15417. groundColor = light.groundColor;
  15418. if ( _this.gammaInput ) {
  15419. intensitySq = intensity * intensity;
  15420. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  15421. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  15422. } else {
  15423. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  15424. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  15425. }
  15426. hemiLength += 1;
  15427. }
  15428. }
  15429. // null eventual remains from removed lights
  15430. // (this is to avoid if in shader)
  15431. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  15432. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  15433. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  15434. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  15435. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  15436. zlights.directional.length = dirLength;
  15437. zlights.point.length = pointLength;
  15438. zlights.spot.length = spotLength;
  15439. zlights.hemi.length = hemiLength;
  15440. zlights.ambient[ 0 ] = r;
  15441. zlights.ambient[ 1 ] = g;
  15442. zlights.ambient[ 2 ] = b;
  15443. };
  15444. // GL state setting
  15445. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  15446. if ( cullFace === THREE.CullFaceNone ) {
  15447. _gl.disable( _gl.CULL_FACE );
  15448. } else {
  15449. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  15450. _gl.frontFace( _gl.CW );
  15451. } else {
  15452. _gl.frontFace( _gl.CCW );
  15453. }
  15454. if ( cullFace === THREE.CullFaceBack ) {
  15455. _gl.cullFace( _gl.BACK );
  15456. } else if ( cullFace === THREE.CullFaceFront ) {
  15457. _gl.cullFace( _gl.FRONT );
  15458. } else {
  15459. _gl.cullFace( _gl.FRONT_AND_BACK );
  15460. }
  15461. _gl.enable( _gl.CULL_FACE );
  15462. }
  15463. };
  15464. this.setMaterialFaces = function ( material ) {
  15465. var doubleSided = material.side === THREE.DoubleSide;
  15466. var flipSided = material.side === THREE.BackSide;
  15467. if ( _oldDoubleSided !== doubleSided ) {
  15468. if ( doubleSided ) {
  15469. _gl.disable( _gl.CULL_FACE );
  15470. } else {
  15471. _gl.enable( _gl.CULL_FACE );
  15472. }
  15473. _oldDoubleSided = doubleSided;
  15474. }
  15475. if ( _oldFlipSided !== flipSided ) {
  15476. if ( flipSided ) {
  15477. _gl.frontFace( _gl.CW );
  15478. } else {
  15479. _gl.frontFace( _gl.CCW );
  15480. }
  15481. _oldFlipSided = flipSided;
  15482. }
  15483. };
  15484. this.setDepthTest = function ( depthTest ) {
  15485. if ( _oldDepthTest !== depthTest ) {
  15486. if ( depthTest ) {
  15487. _gl.enable( _gl.DEPTH_TEST );
  15488. } else {
  15489. _gl.disable( _gl.DEPTH_TEST );
  15490. }
  15491. _oldDepthTest = depthTest;
  15492. }
  15493. };
  15494. this.setDepthWrite = function ( depthWrite ) {
  15495. if ( _oldDepthWrite !== depthWrite ) {
  15496. _gl.depthMask( depthWrite );
  15497. _oldDepthWrite = depthWrite;
  15498. }
  15499. };
  15500. function setLineWidth ( width ) {
  15501. if ( width !== _oldLineWidth ) {
  15502. _gl.lineWidth( width );
  15503. _oldLineWidth = width;
  15504. }
  15505. };
  15506. function setPolygonOffset ( polygonoffset, factor, units ) {
  15507. if ( _oldPolygonOffset !== polygonoffset ) {
  15508. if ( polygonoffset ) {
  15509. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  15510. } else {
  15511. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  15512. }
  15513. _oldPolygonOffset = polygonoffset;
  15514. }
  15515. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15516. _gl.polygonOffset( factor, units );
  15517. _oldPolygonOffsetFactor = factor;
  15518. _oldPolygonOffsetUnits = units;
  15519. }
  15520. };
  15521. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15522. if ( blending !== _oldBlending ) {
  15523. if ( blending === THREE.NoBlending ) {
  15524. _gl.disable( _gl.BLEND );
  15525. } else if ( blending === THREE.AdditiveBlending ) {
  15526. _gl.enable( _gl.BLEND );
  15527. _gl.blendEquation( _gl.FUNC_ADD );
  15528. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15529. } else if ( blending === THREE.SubtractiveBlending ) {
  15530. // TODO: Find blendFuncSeparate() combination
  15531. _gl.enable( _gl.BLEND );
  15532. _gl.blendEquation( _gl.FUNC_ADD );
  15533. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15534. } else if ( blending === THREE.MultiplyBlending ) {
  15535. // TODO: Find blendFuncSeparate() combination
  15536. _gl.enable( _gl.BLEND );
  15537. _gl.blendEquation( _gl.FUNC_ADD );
  15538. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15539. } else if ( blending === THREE.CustomBlending ) {
  15540. _gl.enable( _gl.BLEND );
  15541. } else {
  15542. _gl.enable( _gl.BLEND );
  15543. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15544. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15545. }
  15546. _oldBlending = blending;
  15547. }
  15548. if ( blending === THREE.CustomBlending ) {
  15549. if ( blendEquation !== _oldBlendEquation ) {
  15550. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15551. _oldBlendEquation = blendEquation;
  15552. }
  15553. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15554. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15555. _oldBlendSrc = blendSrc;
  15556. _oldBlendDst = blendDst;
  15557. }
  15558. } else {
  15559. _oldBlendEquation = null;
  15560. _oldBlendSrc = null;
  15561. _oldBlendDst = null;
  15562. }
  15563. };
  15564. // Textures
  15565. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15566. if ( isImagePowerOfTwo ) {
  15567. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15568. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15569. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15570. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15571. } else {
  15572. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15573. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15574. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15575. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15576. }
  15577. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15578. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15579. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15580. texture.__oldAnisotropy = texture.anisotropy;
  15581. }
  15582. }
  15583. };
  15584. this.setTexture = function ( texture, slot ) {
  15585. if ( texture.needsUpdate ) {
  15586. if ( ! texture.__webglInit ) {
  15587. texture.__webglInit = true;
  15588. texture.addEventListener( 'dispose', onTextureDispose );
  15589. texture.__webglTexture = _gl.createTexture();
  15590. _this.info.memory.textures ++;
  15591. }
  15592. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15593. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15594. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15595. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15596. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15597. var image = texture.image,
  15598. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15599. glFormat = paramThreeToGL( texture.format ),
  15600. glType = paramThreeToGL( texture.type );
  15601. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15602. var mipmap, mipmaps = texture.mipmaps;
  15603. if ( texture instanceof THREE.DataTexture ) {
  15604. // use manually created mipmaps if available
  15605. // if there are no manual mipmaps
  15606. // set 0 level mipmap and then use GL to generate other mipmap levels
  15607. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15608. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15609. mipmap = mipmaps[ i ];
  15610. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15611. }
  15612. texture.generateMipmaps = false;
  15613. } else {
  15614. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15615. }
  15616. } else if ( texture instanceof THREE.CompressedTexture ) {
  15617. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15618. mipmap = mipmaps[ i ];
  15619. if ( texture.format!==THREE.RGBAFormat ) {
  15620. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15621. } else {
  15622. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15623. }
  15624. }
  15625. } else { // regular Texture (image, video, canvas)
  15626. // use manually created mipmaps if available
  15627. // if there are no manual mipmaps
  15628. // set 0 level mipmap and then use GL to generate other mipmap levels
  15629. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15630. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15631. mipmap = mipmaps[ i ];
  15632. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15633. }
  15634. texture.generateMipmaps = false;
  15635. } else {
  15636. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15637. }
  15638. }
  15639. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15640. texture.needsUpdate = false;
  15641. if ( texture.onUpdate ) texture.onUpdate();
  15642. } else {
  15643. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15644. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15645. }
  15646. };
  15647. function clampToMaxSize ( image, maxSize ) {
  15648. if ( image.width <= maxSize && image.height <= maxSize ) {
  15649. return image;
  15650. }
  15651. // Warning: Scaling through the canvas will only work with images that use
  15652. // premultiplied alpha.
  15653. var maxDimension = Math.max( image.width, image.height );
  15654. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15655. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15656. var canvas = document.createElement( 'canvas' );
  15657. canvas.width = newWidth;
  15658. canvas.height = newHeight;
  15659. var ctx = canvas.getContext( "2d" );
  15660. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15661. return canvas;
  15662. }
  15663. function setCubeTexture ( texture, slot ) {
  15664. if ( texture.image.length === 6 ) {
  15665. if ( texture.needsUpdate ) {
  15666. if ( ! texture.image.__webglTextureCube ) {
  15667. texture.addEventListener( 'dispose', onTextureDispose );
  15668. texture.image.__webglTextureCube = _gl.createTexture();
  15669. _this.info.memory.textures ++;
  15670. }
  15671. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15672. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15673. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15674. var isCompressed = texture instanceof THREE.CompressedTexture;
  15675. var cubeImage = [];
  15676. for ( var i = 0; i < 6; i ++ ) {
  15677. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15678. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15679. } else {
  15680. cubeImage[ i ] = texture.image[ i ];
  15681. }
  15682. }
  15683. var image = cubeImage[ 0 ],
  15684. isImagePowerOfTwo = THREE.Math.isPowerOfTwo( image.width ) && THREE.Math.isPowerOfTwo( image.height ),
  15685. glFormat = paramThreeToGL( texture.format ),
  15686. glType = paramThreeToGL( texture.type );
  15687. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15688. for ( var i = 0; i < 6; i ++ ) {
  15689. if( !isCompressed ) {
  15690. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15691. } else {
  15692. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15693. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15694. mipmap = mipmaps[ j ];
  15695. if ( texture.format!==THREE.RGBAFormat ) {
  15696. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15697. } else {
  15698. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15699. }
  15700. }
  15701. }
  15702. }
  15703. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15704. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15705. }
  15706. texture.needsUpdate = false;
  15707. if ( texture.onUpdate ) texture.onUpdate();
  15708. } else {
  15709. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15710. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15711. }
  15712. }
  15713. };
  15714. function setCubeTextureDynamic ( texture, slot ) {
  15715. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15716. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15717. };
  15718. // Render targets
  15719. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15720. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15721. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15722. };
  15723. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15724. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15725. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15726. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15727. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15728. /* For some reason this is not working. Defaulting to RGBA4.
  15729. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15730. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15731. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15732. */
  15733. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15734. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15735. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15736. } else {
  15737. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15738. }
  15739. };
  15740. this.setRenderTarget = function ( renderTarget ) {
  15741. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15742. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15743. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15744. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15745. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15746. renderTarget.__webglTexture = _gl.createTexture();
  15747. _this.info.memory.textures ++;
  15748. // Setup texture, create render and frame buffers
  15749. var isTargetPowerOfTwo = THREE.Math.isPowerOfTwo( renderTarget.width ) && THREE.Math.isPowerOfTwo( renderTarget.height ),
  15750. glFormat = paramThreeToGL( renderTarget.format ),
  15751. glType = paramThreeToGL( renderTarget.type );
  15752. if ( isCube ) {
  15753. renderTarget.__webglFramebuffer = [];
  15754. renderTarget.__webglRenderbuffer = [];
  15755. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15756. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15757. for ( var i = 0; i < 6; i ++ ) {
  15758. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15759. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15760. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15761. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15762. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15763. }
  15764. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15765. } else {
  15766. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15767. if ( renderTarget.shareDepthFrom ) {
  15768. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15769. } else {
  15770. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15771. }
  15772. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15773. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15774. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15775. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15776. if ( renderTarget.shareDepthFrom ) {
  15777. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15778. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15779. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15780. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15781. }
  15782. } else {
  15783. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15784. }
  15785. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15786. }
  15787. // Release everything
  15788. if ( isCube ) {
  15789. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15790. } else {
  15791. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15792. }
  15793. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15794. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15795. }
  15796. var framebuffer, width, height, vx, vy;
  15797. if ( renderTarget ) {
  15798. if ( isCube ) {
  15799. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15800. } else {
  15801. framebuffer = renderTarget.__webglFramebuffer;
  15802. }
  15803. width = renderTarget.width;
  15804. height = renderTarget.height;
  15805. vx = 0;
  15806. vy = 0;
  15807. } else {
  15808. framebuffer = null;
  15809. width = _viewportWidth;
  15810. height = _viewportHeight;
  15811. vx = _viewportX;
  15812. vy = _viewportY;
  15813. }
  15814. if ( framebuffer !== _currentFramebuffer ) {
  15815. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15816. _gl.viewport( vx, vy, width, height );
  15817. _currentFramebuffer = framebuffer;
  15818. }
  15819. _currentWidth = width;
  15820. _currentHeight = height;
  15821. };
  15822. function updateRenderTargetMipmap ( renderTarget ) {
  15823. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15824. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15825. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15826. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15827. } else {
  15828. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15829. _gl.generateMipmap( _gl.TEXTURE_2D );
  15830. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15831. }
  15832. };
  15833. // Fallback filters for non-power-of-2 textures
  15834. function filterFallback ( f ) {
  15835. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15836. return _gl.NEAREST;
  15837. }
  15838. return _gl.LINEAR;
  15839. };
  15840. // Map three.js constants to WebGL constants
  15841. function paramThreeToGL ( p ) {
  15842. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15843. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15844. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15845. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15846. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15847. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15848. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15849. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15850. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15851. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15852. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15853. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15854. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15855. if ( p === THREE.ByteType ) return _gl.BYTE;
  15856. if ( p === THREE.ShortType ) return _gl.SHORT;
  15857. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15858. if ( p === THREE.IntType ) return _gl.INT;
  15859. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15860. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15861. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15862. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15863. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15864. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15865. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15866. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15867. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15868. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15869. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15870. if ( p === THREE.OneFactor ) return _gl.ONE;
  15871. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15872. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15873. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15874. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15875. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15876. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15877. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15878. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15879. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15880. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15881. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15882. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15883. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15884. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15885. }
  15886. return 0;
  15887. };
  15888. // Allocations
  15889. function allocateBones ( object ) {
  15890. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15891. return 1024;
  15892. } else {
  15893. // default for when object is not specified
  15894. // ( for example when prebuilding shader
  15895. // to be used with multiple objects )
  15896. //
  15897. // - leave some extra space for other uniforms
  15898. // - limit here is ANGLE's 254 max uniform vectors
  15899. // (up to 54 should be safe)
  15900. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15901. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15902. var maxBones = nVertexMatrices;
  15903. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15904. maxBones = Math.min( object.bones.length, maxBones );
  15905. if ( maxBones < object.bones.length ) {
  15906. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15907. }
  15908. }
  15909. return maxBones;
  15910. }
  15911. };
  15912. function allocateLights( lights ) {
  15913. var dirLights = 0;
  15914. var pointLights = 0;
  15915. var spotLights = 0;
  15916. var hemiLights = 0;
  15917. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15918. var light = lights[ l ];
  15919. if ( light.onlyShadow || light.visible === false ) continue;
  15920. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15921. if ( light instanceof THREE.PointLight ) pointLights ++;
  15922. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15923. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15924. }
  15925. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15926. };
  15927. function allocateShadows( lights ) {
  15928. var maxShadows = 0;
  15929. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15930. var light = lights[ l ];
  15931. if ( ! light.castShadow ) continue;
  15932. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15933. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15934. }
  15935. return maxShadows;
  15936. };
  15937. // Initialization
  15938. function initGL() {
  15939. try {
  15940. var attributes = {
  15941. alpha: _alpha,
  15942. depth: _depth,
  15943. stencil: _stencil,
  15944. antialias: _antialias,
  15945. premultipliedAlpha: _premultipliedAlpha,
  15946. preserveDrawingBuffer: _preserveDrawingBuffer
  15947. };
  15948. _gl = _context || _canvas.getContext( 'webgl', attributes ) || _canvas.getContext( 'experimental-webgl', attributes );
  15949. if ( _gl === null ) {
  15950. throw 'Error creating WebGL context.';
  15951. }
  15952. } catch ( error ) {
  15953. console.error( error );
  15954. }
  15955. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15956. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15957. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15958. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15959. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15960. _glExtensionElementIndexUint = _gl.getExtension( 'OES_element_index_uint' );
  15961. if ( _glExtensionTextureFloat === null ) {
  15962. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15963. }
  15964. if ( _glExtensionStandardDerivatives === null ) {
  15965. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15966. }
  15967. if ( _glExtensionTextureFilterAnisotropic === null ) {
  15968. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15969. }
  15970. if ( _glExtensionCompressedTextureS3TC === null ) {
  15971. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15972. }
  15973. if ( _glExtensionElementIndexUint === null ) {
  15974. console.log( 'THREE.WebGLRenderer: elementindex as unsigned integer not supported.' );
  15975. }
  15976. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15977. _gl.getShaderPrecisionFormat = function() {
  15978. return {
  15979. "rangeMin" : 1,
  15980. "rangeMax" : 1,
  15981. "precision" : 1
  15982. };
  15983. }
  15984. }
  15985. if ( _logarithmicDepthBuffer ) {
  15986. _glExtensionFragDepth = _gl.getExtension( 'EXT_frag_depth' );
  15987. }
  15988. };
  15989. function setDefaultGLState () {
  15990. _gl.clearColor( 0, 0, 0, 1 );
  15991. _gl.clearDepth( 1 );
  15992. _gl.clearStencil( 0 );
  15993. _gl.enable( _gl.DEPTH_TEST );
  15994. _gl.depthFunc( _gl.LEQUAL );
  15995. _gl.frontFace( _gl.CCW );
  15996. _gl.cullFace( _gl.BACK );
  15997. _gl.enable( _gl.CULL_FACE );
  15998. _gl.enable( _gl.BLEND );
  15999. _gl.blendEquation( _gl.FUNC_ADD );
  16000. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  16001. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  16002. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  16003. };
  16004. // default plugins (order is important)
  16005. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  16006. this.addPrePlugin( this.shadowMapPlugin );
  16007. this.addPostPlugin( new THREE.SpritePlugin() );
  16008. this.addPostPlugin( new THREE.LensFlarePlugin() );
  16009. };
  16010. /**
  16011. * @author szimek / https://github.com/szimek/
  16012. * @author alteredq / http://alteredqualia.com/
  16013. */
  16014. THREE.WebGLRenderTarget = function ( width, height, options ) {
  16015. this.width = width;
  16016. this.height = height;
  16017. options = options || {};
  16018. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  16019. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  16020. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  16021. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  16022. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  16023. this.offset = new THREE.Vector2( 0, 0 );
  16024. this.repeat = new THREE.Vector2( 1, 1 );
  16025. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  16026. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  16027. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  16028. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  16029. this.generateMipmaps = true;
  16030. this.shareDepthFrom = null;
  16031. };
  16032. THREE.WebGLRenderTarget.prototype = {
  16033. constructor: THREE.WebGLRenderTarget,
  16034. setSize: function ( width, height ) {
  16035. this.width = width;
  16036. this.height = height;
  16037. },
  16038. clone: function () {
  16039. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  16040. tmp.wrapS = this.wrapS;
  16041. tmp.wrapT = this.wrapT;
  16042. tmp.magFilter = this.magFilter;
  16043. tmp.minFilter = this.minFilter;
  16044. tmp.anisotropy = this.anisotropy;
  16045. tmp.offset.copy( this.offset );
  16046. tmp.repeat.copy( this.repeat );
  16047. tmp.format = this.format;
  16048. tmp.type = this.type;
  16049. tmp.depthBuffer = this.depthBuffer;
  16050. tmp.stencilBuffer = this.stencilBuffer;
  16051. tmp.generateMipmaps = this.generateMipmaps;
  16052. tmp.shareDepthFrom = this.shareDepthFrom;
  16053. return tmp;
  16054. },
  16055. dispose: function () {
  16056. this.dispatchEvent( { type: 'dispose' } );
  16057. }
  16058. };
  16059. THREE.EventDispatcher.prototype.apply( THREE.WebGLRenderTarget.prototype );
  16060. /**
  16061. * @author alteredq / http://alteredqualia.com
  16062. */
  16063. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  16064. THREE.WebGLRenderTarget.call( this, width, height, options );
  16065. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  16066. };
  16067. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  16068. THREE.WebGLProgram = ( function () {
  16069. var programIdCount = 0;
  16070. var generateDefines = function ( defines ) {
  16071. var value, chunk, chunks = [];
  16072. for ( var d in defines ) {
  16073. value = defines[ d ];
  16074. if ( value === false ) continue;
  16075. chunk = "#define " + d + " " + value;
  16076. chunks.push( chunk );
  16077. }
  16078. return chunks.join( "\n" );
  16079. };
  16080. var cacheUniformLocations = function ( gl, program, identifiers ) {
  16081. var uniforms = {};
  16082. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  16083. var id = identifiers[ i ];
  16084. uniforms[ id ] = gl.getUniformLocation( program, id );
  16085. }
  16086. return uniforms;
  16087. };
  16088. var cacheAttributeLocations = function ( gl, program, identifiers ) {
  16089. var attributes = {};
  16090. for ( var i = 0, l = identifiers.length; i < l; i ++ ) {
  16091. var id = identifiers[ i ];
  16092. attributes[ id ] = gl.getAttribLocation( program, id );
  16093. }
  16094. return attributes;
  16095. };
  16096. return function ( renderer, code, material, parameters ) {
  16097. var _this = renderer;
  16098. var _gl = _this.context;
  16099. var fragmentShader = material.fragmentShader;
  16100. var vertexShader = material.vertexShader;
  16101. var uniforms = material.uniforms;
  16102. var attributes = material.attributes;
  16103. var defines = material.defines;
  16104. var index0AttributeName = material.index0AttributeName;
  16105. if ( index0AttributeName === undefined && parameters.morphTargets === true ) {
  16106. // programs with morphTargets displace position out of attribute 0
  16107. index0AttributeName = 'position';
  16108. }
  16109. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  16110. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  16111. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  16112. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  16113. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  16114. }
  16115. // console.log( "building new program " );
  16116. //
  16117. var customDefines = generateDefines( defines );
  16118. //
  16119. var program = _gl.createProgram();
  16120. var prefix_vertex, prefix_fragment;
  16121. if ( material instanceof THREE.RawShaderMaterial ) {
  16122. prefix_vertex = '';
  16123. prefix_fragment = '';
  16124. } else {
  16125. prefix_vertex = [
  16126. "precision " + parameters.precision + " float;",
  16127. "precision " + parameters.precision + " int;",
  16128. customDefines,
  16129. parameters.supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  16130. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  16131. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  16132. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  16133. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  16134. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  16135. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  16136. "#define MAX_SHADOWS " + parameters.maxShadows,
  16137. "#define MAX_BONES " + parameters.maxBones,
  16138. parameters.map ? "#define USE_MAP" : "",
  16139. parameters.envMap ? "#define USE_ENVMAP" : "",
  16140. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  16141. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  16142. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  16143. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  16144. parameters.vertexColors ? "#define USE_COLOR" : "",
  16145. parameters.skinning ? "#define USE_SKINNING" : "",
  16146. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  16147. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  16148. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  16149. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  16150. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  16151. parameters.flipSided ? "#define FLIP_SIDED" : "",
  16152. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  16153. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  16154. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  16155. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  16156. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  16157. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  16158. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  16159. "uniform mat4 modelMatrix;",
  16160. "uniform mat4 modelViewMatrix;",
  16161. "uniform mat4 projectionMatrix;",
  16162. "uniform mat4 viewMatrix;",
  16163. "uniform mat3 normalMatrix;",
  16164. "uniform vec3 cameraPosition;",
  16165. "attribute vec3 position;",
  16166. "attribute vec3 normal;",
  16167. "attribute vec2 uv;",
  16168. "attribute vec2 uv2;",
  16169. "#ifdef USE_COLOR",
  16170. " attribute vec3 color;",
  16171. "#endif",
  16172. "#ifdef USE_MORPHTARGETS",
  16173. " attribute vec3 morphTarget0;",
  16174. " attribute vec3 morphTarget1;",
  16175. " attribute vec3 morphTarget2;",
  16176. " attribute vec3 morphTarget3;",
  16177. " #ifdef USE_MORPHNORMALS",
  16178. " attribute vec3 morphNormal0;",
  16179. " attribute vec3 morphNormal1;",
  16180. " attribute vec3 morphNormal2;",
  16181. " attribute vec3 morphNormal3;",
  16182. " #else",
  16183. " attribute vec3 morphTarget4;",
  16184. " attribute vec3 morphTarget5;",
  16185. " attribute vec3 morphTarget6;",
  16186. " attribute vec3 morphTarget7;",
  16187. " #endif",
  16188. "#endif",
  16189. "#ifdef USE_SKINNING",
  16190. " attribute vec4 skinIndex;",
  16191. " attribute vec4 skinWeight;",
  16192. "#endif",
  16193. ""
  16194. ].join( '\n' );
  16195. prefix_fragment = [
  16196. "precision " + parameters.precision + " float;",
  16197. "precision " + parameters.precision + " int;",
  16198. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  16199. customDefines,
  16200. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  16201. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  16202. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  16203. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  16204. "#define MAX_SHADOWS " + parameters.maxShadows,
  16205. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  16206. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  16207. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  16208. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  16209. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  16210. parameters.map ? "#define USE_MAP" : "",
  16211. parameters.envMap ? "#define USE_ENVMAP" : "",
  16212. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  16213. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  16214. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  16215. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  16216. parameters.vertexColors ? "#define USE_COLOR" : "",
  16217. parameters.metal ? "#define METAL" : "",
  16218. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  16219. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  16220. parameters.flipSided ? "#define FLIP_SIDED" : "",
  16221. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  16222. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  16223. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  16224. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  16225. parameters.logarithmicDepthBuffer ? "#define USE_LOGDEPTHBUF" : "",
  16226. //_this._glExtensionFragDepth ? "#define USE_LOGDEPTHBUF_EXT" : "",
  16227. "uniform mat4 viewMatrix;",
  16228. "uniform vec3 cameraPosition;",
  16229. ""
  16230. ].join( '\n' );
  16231. }
  16232. var glVertexShader = new THREE.WebGLShader( _gl, _gl.VERTEX_SHADER, prefix_vertex + vertexShader );
  16233. var glFragmentShader = new THREE.WebGLShader( _gl, _gl.FRAGMENT_SHADER, prefix_fragment + fragmentShader );
  16234. _gl.attachShader( program, glVertexShader );
  16235. _gl.attachShader( program, glFragmentShader );
  16236. if ( index0AttributeName !== undefined ) {
  16237. // Force a particular attribute to index 0.
  16238. // because potentially expensive emulation is done by browser if attribute 0 is disabled.
  16239. // And, color, for example is often automatically bound to index 0 so disabling it
  16240. _gl.bindAttribLocation( program, 0, index0AttributeName );
  16241. }
  16242. _gl.linkProgram( program );
  16243. if ( _gl.getProgramParameter( program, _gl.LINK_STATUS ) === false ) {
  16244. console.error( 'Could not initialise shader' );
  16245. console.error( 'gl.VALIDATE_STATUS', _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) );
  16246. console.error( 'gl.getError()', _gl.getError() );
  16247. }
  16248. if ( _gl.getProgramInfoLog( program ) !== '' ) {
  16249. console.error( 'gl.getProgramInfoLog()', _gl.getProgramInfoLog( program ) );
  16250. }
  16251. // clean up
  16252. _gl.deleteShader( glVertexShader );
  16253. _gl.deleteShader( glFragmentShader );
  16254. // cache uniform locations
  16255. var identifiers = [
  16256. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  16257. 'morphTargetInfluences'
  16258. ];
  16259. if ( parameters.useVertexTexture ) {
  16260. identifiers.push( 'boneTexture' );
  16261. identifiers.push( 'boneTextureWidth' );
  16262. identifiers.push( 'boneTextureHeight' );
  16263. } else {
  16264. identifiers.push( 'boneGlobalMatrices' );
  16265. }
  16266. if ( parameters.logarithmicDepthBuffer ) {
  16267. identifiers.push('logDepthBufFC');
  16268. }
  16269. for ( var u in uniforms ) {
  16270. identifiers.push( u );
  16271. }
  16272. this.uniforms = cacheUniformLocations( _gl, program, identifiers );
  16273. // cache attributes locations
  16274. identifiers = [
  16275. "position", "normal", "uv", "uv2", "tangent", "color",
  16276. "skinIndex", "skinWeight", "lineDistance"
  16277. ];
  16278. for ( var i = 0; i < parameters.maxMorphTargets; i ++ ) {
  16279. identifiers.push( "morphTarget" + i );
  16280. }
  16281. for ( var i = 0; i < parameters.maxMorphNormals; i ++ ) {
  16282. identifiers.push( "morphNormal" + i );
  16283. }
  16284. for ( var a in attributes ) {
  16285. identifiers.push( a );
  16286. }
  16287. this.attributes = cacheAttributeLocations( _gl, program, identifiers );
  16288. //
  16289. this.id = programIdCount ++;
  16290. this.code = code;
  16291. this.usedTimes = 1;
  16292. this.program = program;
  16293. this.vertexShader = glVertexShader;
  16294. this.fragmentShader = glFragmentShader;
  16295. return this;
  16296. };
  16297. } )();
  16298. THREE.WebGLShader = ( function () {
  16299. var addLineNumbers = function ( string ) {
  16300. var lines = string.split( '\n' );
  16301. for ( var i = 0; i < lines.length; i ++ ) {
  16302. lines[ i ] = ( i + 1 ) + ': ' + lines[ i ];
  16303. }
  16304. return lines.join( '\n' );
  16305. };
  16306. return function ( gl, type, string ) {
  16307. var shader = gl.createShader( type );
  16308. gl.shaderSource( shader, string );
  16309. gl.compileShader( shader );
  16310. if ( gl.getShaderParameter( shader, gl.COMPILE_STATUS ) === false ) {
  16311. console.error( 'THREE.WebGLShader: Shader couldn\'t compile.' );
  16312. }
  16313. if ( gl.getShaderInfoLog( shader ) !== '' ) {
  16314. console.error( 'THREE.WebGLShader:', 'gl.getShaderInfoLog()', gl.getShaderInfoLog( shader ) );
  16315. console.error( addLineNumbers( string ) );
  16316. }
  16317. return shader;
  16318. };
  16319. } )();
  16320. /**
  16321. * @author mrdoob / http://mrdoob.com/
  16322. */
  16323. THREE.RenderableVertex = function () {
  16324. this.position = new THREE.Vector3();
  16325. this.positionWorld = new THREE.Vector3();
  16326. this.positionScreen = new THREE.Vector4();
  16327. this.visible = true;
  16328. };
  16329. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  16330. this.positionWorld.copy( vertex.positionWorld );
  16331. this.positionScreen.copy( vertex.positionScreen );
  16332. };
  16333. /**
  16334. * @author mrdoob / http://mrdoob.com/
  16335. */
  16336. THREE.RenderableFace = function () {
  16337. this.id = 0;
  16338. this.v1 = new THREE.RenderableVertex();
  16339. this.v2 = new THREE.RenderableVertex();
  16340. this.v3 = new THREE.RenderableVertex();
  16341. this.normalModel = new THREE.Vector3();
  16342. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  16343. this.vertexNormalsLength = 0;
  16344. this.color = null;
  16345. this.material = null;
  16346. this.uvs = [ new THREE.Vector2(), new THREE.Vector2(), new THREE.Vector2() ];
  16347. this.z = 0;
  16348. };
  16349. /**
  16350. * @author mrdoob / http://mrdoob.com/
  16351. */
  16352. THREE.RenderableObject = function () {
  16353. this.id = 0;
  16354. this.object = null;
  16355. this.z = 0;
  16356. };
  16357. /**
  16358. * @author mrdoob / http://mrdoob.com/
  16359. */
  16360. THREE.RenderableSprite = function () {
  16361. this.id = 0;
  16362. this.object = null;
  16363. this.x = 0;
  16364. this.y = 0;
  16365. this.z = 0;
  16366. this.rotation = 0;
  16367. this.scale = new THREE.Vector2();
  16368. this.material = null;
  16369. };
  16370. /**
  16371. * @author mrdoob / http://mrdoob.com/
  16372. */
  16373. THREE.RenderableLine = function () {
  16374. this.id = 0;
  16375. this.v1 = new THREE.RenderableVertex();
  16376. this.v2 = new THREE.RenderableVertex();
  16377. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  16378. this.material = null;
  16379. this.z = 0;
  16380. };
  16381. /**
  16382. * @author mrdoob / http://mrdoob.com/
  16383. * @author alteredq / http://alteredqualia.com/
  16384. */
  16385. THREE.GeometryUtils = {
  16386. // Merge two geometries or geometry and geometry from object (using object's transform)
  16387. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  16388. var matrix, normalMatrix,
  16389. vertexOffset = geometry1.vertices.length,
  16390. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  16391. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  16392. vertices1 = geometry1.vertices,
  16393. vertices2 = geometry2.vertices,
  16394. faces1 = geometry1.faces,
  16395. faces2 = geometry2.faces,
  16396. uvs1 = geometry1.faceVertexUvs[ 0 ],
  16397. uvs2 = geometry2.faceVertexUvs[ 0 ];
  16398. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  16399. if ( object2 instanceof THREE.Mesh ) {
  16400. object2.matrixAutoUpdate && object2.updateMatrix();
  16401. matrix = object2.matrix;
  16402. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  16403. }
  16404. // vertices
  16405. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  16406. var vertex = vertices2[ i ];
  16407. var vertexCopy = vertex.clone();
  16408. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  16409. vertices1.push( vertexCopy );
  16410. }
  16411. // faces
  16412. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  16413. var face = faces2[ i ], faceCopy, normal, color,
  16414. faceVertexNormals = face.vertexNormals,
  16415. faceVertexColors = face.vertexColors;
  16416. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  16417. faceCopy.normal.copy( face.normal );
  16418. if ( normalMatrix ) {
  16419. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  16420. }
  16421. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  16422. normal = faceVertexNormals[ j ].clone();
  16423. if ( normalMatrix ) {
  16424. normal.applyMatrix3( normalMatrix ).normalize();
  16425. }
  16426. faceCopy.vertexNormals.push( normal );
  16427. }
  16428. faceCopy.color.copy( face.color );
  16429. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  16430. color = faceVertexColors[ j ];
  16431. faceCopy.vertexColors.push( color.clone() );
  16432. }
  16433. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  16434. faces1.push( faceCopy );
  16435. }
  16436. // uvs
  16437. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  16438. var uv = uvs2[ i ], uvCopy = [];
  16439. if ( uv === undefined ) {
  16440. continue;
  16441. }
  16442. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  16443. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  16444. }
  16445. uvs1.push( uvCopy );
  16446. }
  16447. },
  16448. // Get random point in triangle (via barycentric coordinates)
  16449. // (uniform distribution)
  16450. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  16451. randomPointInTriangle: function () {
  16452. var vector = new THREE.Vector3();
  16453. return function ( vectorA, vectorB, vectorC ) {
  16454. var point = new THREE.Vector3();
  16455. var a = THREE.Math.random16();
  16456. var b = THREE.Math.random16();
  16457. if ( ( a + b ) > 1 ) {
  16458. a = 1 - a;
  16459. b = 1 - b;
  16460. }
  16461. var c = 1 - a - b;
  16462. point.copy( vectorA );
  16463. point.multiplyScalar( a );
  16464. vector.copy( vectorB );
  16465. vector.multiplyScalar( b );
  16466. point.add( vector );
  16467. vector.copy( vectorC );
  16468. vector.multiplyScalar( c );
  16469. point.add( vector );
  16470. return point;
  16471. };
  16472. }(),
  16473. // Get random point in face (triangle / quad)
  16474. // (uniform distribution)
  16475. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  16476. var vA, vB, vC, vD;
  16477. vA = geometry.vertices[ face.a ];
  16478. vB = geometry.vertices[ face.b ];
  16479. vC = geometry.vertices[ face.c ];
  16480. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  16481. },
  16482. // Get uniformly distributed random points in mesh
  16483. // - create array with cumulative sums of face areas
  16484. // - pick random number from 0 to total area
  16485. // - find corresponding place in area array by binary search
  16486. // - get random point in face
  16487. randomPointsInGeometry: function ( geometry, n ) {
  16488. var face, i,
  16489. faces = geometry.faces,
  16490. vertices = geometry.vertices,
  16491. il = faces.length,
  16492. totalArea = 0,
  16493. cumulativeAreas = [],
  16494. vA, vB, vC, vD;
  16495. // precompute face areas
  16496. for ( i = 0; i < il; i ++ ) {
  16497. face = faces[ i ];
  16498. vA = vertices[ face.a ];
  16499. vB = vertices[ face.b ];
  16500. vC = vertices[ face.c ];
  16501. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16502. totalArea += face._area;
  16503. cumulativeAreas[ i ] = totalArea;
  16504. }
  16505. // binary search cumulative areas array
  16506. function binarySearchIndices( value ) {
  16507. function binarySearch( start, end ) {
  16508. // return closest larger index
  16509. // if exact number is not found
  16510. if ( end < start )
  16511. return start;
  16512. var mid = start + Math.floor( ( end - start ) / 2 );
  16513. if ( cumulativeAreas[ mid ] > value ) {
  16514. return binarySearch( start, mid - 1 );
  16515. } else if ( cumulativeAreas[ mid ] < value ) {
  16516. return binarySearch( mid + 1, end );
  16517. } else {
  16518. return mid;
  16519. }
  16520. }
  16521. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16522. return result;
  16523. }
  16524. // pick random face weighted by face area
  16525. var r, index,
  16526. result = [];
  16527. var stats = {};
  16528. for ( i = 0; i < n; i ++ ) {
  16529. r = THREE.Math.random16() * totalArea;
  16530. index = binarySearchIndices( r );
  16531. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16532. if ( ! stats[ index ] ) {
  16533. stats[ index ] = 1;
  16534. } else {
  16535. stats[ index ] += 1;
  16536. }
  16537. }
  16538. return result;
  16539. },
  16540. // Get triangle area (half of parallelogram)
  16541. // http://mathworld.wolfram.com/TriangleArea.html
  16542. triangleArea: function () {
  16543. var vector1 = new THREE.Vector3();
  16544. var vector2 = new THREE.Vector3();
  16545. return function ( vectorA, vectorB, vectorC ) {
  16546. vector1.subVectors( vectorB, vectorA );
  16547. vector2.subVectors( vectorC, vectorA );
  16548. vector1.cross( vector2 );
  16549. return 0.5 * vector1.length();
  16550. };
  16551. }(),
  16552. // Center geometry so that 0,0,0 is in center of bounding box
  16553. center: function ( geometry ) {
  16554. geometry.computeBoundingBox();
  16555. var bb = geometry.boundingBox;
  16556. var offset = new THREE.Vector3();
  16557. offset.addVectors( bb.min, bb.max );
  16558. offset.multiplyScalar( -0.5 );
  16559. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16560. geometry.computeBoundingBox();
  16561. return offset;
  16562. }
  16563. };
  16564. /**
  16565. * @author alteredq / http://alteredqualia.com/
  16566. * @author mrdoob / http://mrdoob.com/
  16567. */
  16568. THREE.ImageUtils = {
  16569. crossOrigin: undefined,
  16570. loadTexture: function ( url, mapping, onLoad, onError ) {
  16571. var loader = new THREE.ImageLoader();
  16572. loader.crossOrigin = this.crossOrigin;
  16573. var texture = new THREE.Texture( undefined, mapping );
  16574. var image = loader.load( url, function () {
  16575. texture.needsUpdate = true;
  16576. if ( onLoad ) onLoad( texture );
  16577. }, undefined, function ( event ) {
  16578. if ( onError ) onError( event );
  16579. } );
  16580. texture.image = image;
  16581. texture.sourceFile = url;
  16582. return texture;
  16583. },
  16584. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16585. var texture = new THREE.CompressedTexture();
  16586. texture.mapping = mapping;
  16587. var request = new XMLHttpRequest();
  16588. request.onload = function () {
  16589. var buffer = request.response;
  16590. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16591. texture.format = dds.format;
  16592. texture.mipmaps = dds.mipmaps;
  16593. texture.image.width = dds.width;
  16594. texture.image.height = dds.height;
  16595. // gl.generateMipmap fails for compressed textures
  16596. // mipmaps must be embedded in the DDS file
  16597. // or texture filters must not use mipmapping
  16598. texture.generateMipmaps = false;
  16599. texture.needsUpdate = true;
  16600. if ( onLoad ) onLoad( texture );
  16601. }
  16602. request.onerror = onError;
  16603. request.open( 'GET', url, true );
  16604. request.responseType = "arraybuffer";
  16605. request.send( null );
  16606. return texture;
  16607. },
  16608. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16609. var images = [];
  16610. images.loadCount = 0;
  16611. var texture = new THREE.Texture();
  16612. texture.image = images;
  16613. if ( mapping !== undefined ) texture.mapping = mapping;
  16614. // no flipping needed for cube textures
  16615. texture.flipY = false;
  16616. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16617. var cubeImage = new Image();
  16618. images[ i ] = cubeImage;
  16619. cubeImage.onload = function () {
  16620. images.loadCount += 1;
  16621. if ( images.loadCount === 6 ) {
  16622. texture.needsUpdate = true;
  16623. if ( onLoad ) onLoad( texture );
  16624. }
  16625. };
  16626. cubeImage.onerror = onError;
  16627. cubeImage.crossOrigin = this.crossOrigin;
  16628. cubeImage.src = array[ i ];
  16629. }
  16630. return texture;
  16631. },
  16632. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16633. var images = [];
  16634. images.loadCount = 0;
  16635. var texture = new THREE.CompressedTexture();
  16636. texture.image = images;
  16637. if ( mapping !== undefined ) texture.mapping = mapping;
  16638. // no flipping for cube textures
  16639. // (also flipping doesn't work for compressed textures )
  16640. texture.flipY = false;
  16641. // can't generate mipmaps for compressed textures
  16642. // mips must be embedded in DDS files
  16643. texture.generateMipmaps = false;
  16644. var generateCubeFaceCallback = function ( rq, img ) {
  16645. return function () {
  16646. var buffer = rq.response;
  16647. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16648. img.format = dds.format;
  16649. img.mipmaps = dds.mipmaps;
  16650. img.width = dds.width;
  16651. img.height = dds.height;
  16652. images.loadCount += 1;
  16653. if ( images.loadCount === 6 ) {
  16654. texture.format = dds.format;
  16655. texture.needsUpdate = true;
  16656. if ( onLoad ) onLoad( texture );
  16657. }
  16658. }
  16659. }
  16660. // compressed cubemap textures as 6 separate DDS files
  16661. if ( array instanceof Array ) {
  16662. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16663. var cubeImage = {};
  16664. images[ i ] = cubeImage;
  16665. var request = new XMLHttpRequest();
  16666. request.onload = generateCubeFaceCallback( request, cubeImage );
  16667. request.onerror = onError;
  16668. var url = array[ i ];
  16669. request.open( 'GET', url, true );
  16670. request.responseType = "arraybuffer";
  16671. request.send( null );
  16672. }
  16673. // compressed cubemap texture stored in a single DDS file
  16674. } else {
  16675. var url = array;
  16676. var request = new XMLHttpRequest();
  16677. request.onload = function( ) {
  16678. var buffer = request.response;
  16679. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16680. if ( dds.isCubemap ) {
  16681. var faces = dds.mipmaps.length / dds.mipmapCount;
  16682. for ( var f = 0; f < faces; f ++ ) {
  16683. images[ f ] = { mipmaps : [] };
  16684. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16685. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16686. images[ f ].format = dds.format;
  16687. images[ f ].width = dds.width;
  16688. images[ f ].height = dds.height;
  16689. }
  16690. }
  16691. texture.format = dds.format;
  16692. texture.needsUpdate = true;
  16693. if ( onLoad ) onLoad( texture );
  16694. }
  16695. }
  16696. request.onerror = onError;
  16697. request.open( 'GET', url, true );
  16698. request.responseType = "arraybuffer";
  16699. request.send( null );
  16700. }
  16701. return texture;
  16702. },
  16703. loadDDSTexture: function ( url, mapping, onLoad, onError ) {
  16704. var images = [];
  16705. images.loadCount = 0;
  16706. var texture = new THREE.CompressedTexture();
  16707. texture.image = images;
  16708. if ( mapping !== undefined ) texture.mapping = mapping;
  16709. // no flipping for cube textures
  16710. // (also flipping doesn't work for compressed textures )
  16711. texture.flipY = false;
  16712. // can't generate mipmaps for compressed textures
  16713. // mips must be embedded in DDS files
  16714. texture.generateMipmaps = false;
  16715. {
  16716. var request = new XMLHttpRequest();
  16717. request.onload = function( ) {
  16718. var buffer = request.response;
  16719. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16720. if ( dds.isCubemap ) {
  16721. var faces = dds.mipmaps.length / dds.mipmapCount;
  16722. for ( var f = 0; f < faces; f ++ ) {
  16723. images[ f ] = { mipmaps : [] };
  16724. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16725. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16726. images[ f ].format = dds.format;
  16727. images[ f ].width = dds.width;
  16728. images[ f ].height = dds.height;
  16729. }
  16730. }
  16731. } else {
  16732. texture.image.width = dds.width;
  16733. texture.image.height = dds.height;
  16734. texture.mipmaps = dds.mipmaps;
  16735. }
  16736. texture.format = dds.format;
  16737. texture.needsUpdate = true;
  16738. if ( onLoad ) onLoad( texture );
  16739. }
  16740. request.onerror = onError;
  16741. request.open( 'GET', url, true );
  16742. request.responseType = "arraybuffer";
  16743. request.send( null );
  16744. }
  16745. return texture;
  16746. },
  16747. parseDDS: function ( buffer, loadMipmaps ) {
  16748. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16749. // Adapted from @toji's DDS utils
  16750. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16751. // All values and structures referenced from:
  16752. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16753. var DDS_MAGIC = 0x20534444;
  16754. var DDSD_CAPS = 0x1,
  16755. DDSD_HEIGHT = 0x2,
  16756. DDSD_WIDTH = 0x4,
  16757. DDSD_PITCH = 0x8,
  16758. DDSD_PIXELFORMAT = 0x1000,
  16759. DDSD_MIPMAPCOUNT = 0x20000,
  16760. DDSD_LINEARSIZE = 0x80000,
  16761. DDSD_DEPTH = 0x800000;
  16762. var DDSCAPS_COMPLEX = 0x8,
  16763. DDSCAPS_MIPMAP = 0x400000,
  16764. DDSCAPS_TEXTURE = 0x1000;
  16765. var DDSCAPS2_CUBEMAP = 0x200,
  16766. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16767. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16768. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16769. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16770. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16771. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16772. DDSCAPS2_VOLUME = 0x200000;
  16773. var DDPF_ALPHAPIXELS = 0x1,
  16774. DDPF_ALPHA = 0x2,
  16775. DDPF_FOURCC = 0x4,
  16776. DDPF_RGB = 0x40,
  16777. DDPF_YUV = 0x200,
  16778. DDPF_LUMINANCE = 0x20000;
  16779. function fourCCToInt32( value ) {
  16780. return value.charCodeAt(0) +
  16781. (value.charCodeAt(1) << 8) +
  16782. (value.charCodeAt(2) << 16) +
  16783. (value.charCodeAt(3) << 24);
  16784. }
  16785. function int32ToFourCC( value ) {
  16786. return String.fromCharCode(
  16787. value & 0xff,
  16788. (value >> 8) & 0xff,
  16789. (value >> 16) & 0xff,
  16790. (value >> 24) & 0xff
  16791. );
  16792. }
  16793. function loadARGBMip( buffer, dataOffset, width, height ) {
  16794. var dataLength = width*height*4;
  16795. var srcBuffer = new Uint8Array( buffer, dataOffset, dataLength );
  16796. var byteArray = new Uint8Array( dataLength );
  16797. var dst = 0;
  16798. var src = 0;
  16799. for ( var y = 0; y < height; y++ ) {
  16800. for ( var x = 0; x < width; x++ ) {
  16801. var b = srcBuffer[src]; src++;
  16802. var g = srcBuffer[src]; src++;
  16803. var r = srcBuffer[src]; src++;
  16804. var a = srcBuffer[src]; src++;
  16805. byteArray[dst] = r; dst++; //r
  16806. byteArray[dst] = g; dst++; //g
  16807. byteArray[dst] = b; dst++; //b
  16808. byteArray[dst] = a; dst++; //a
  16809. }
  16810. }
  16811. return byteArray;
  16812. }
  16813. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16814. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16815. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16816. var headerLengthInt = 31; // The header length in 32 bit ints
  16817. // Offsets into the header array
  16818. var off_magic = 0;
  16819. var off_size = 1;
  16820. var off_flags = 2;
  16821. var off_height = 3;
  16822. var off_width = 4;
  16823. var off_mipmapCount = 7;
  16824. var off_pfFlags = 20;
  16825. var off_pfFourCC = 21;
  16826. var off_RGBBitCount = 22;
  16827. var off_RBitMask = 23;
  16828. var off_GBitMask = 24;
  16829. var off_BBitMask = 25;
  16830. var off_ABitMask = 26;
  16831. var off_caps = 27;
  16832. var off_caps2 = 28;
  16833. var off_caps3 = 29;
  16834. var off_caps4 = 30;
  16835. // Parse header
  16836. var header = new Int32Array( buffer, 0, headerLengthInt );
  16837. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16838. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16839. return dds;
  16840. }
  16841. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16842. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16843. return dds;
  16844. }
  16845. var blockBytes;
  16846. var fourCC = header[ off_pfFourCC ];
  16847. var isRGBAUncompressed = false;
  16848. switch ( fourCC ) {
  16849. case FOURCC_DXT1:
  16850. blockBytes = 8;
  16851. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16852. break;
  16853. case FOURCC_DXT3:
  16854. blockBytes = 16;
  16855. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16856. break;
  16857. case FOURCC_DXT5:
  16858. blockBytes = 16;
  16859. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16860. break;
  16861. default:
  16862. if( header[off_RGBBitCount] ==32
  16863. && header[off_RBitMask]&0xff0000
  16864. && header[off_GBitMask]&0xff00
  16865. && header[off_BBitMask]&0xff
  16866. && header[off_ABitMask]&0xff000000 ) {
  16867. isRGBAUncompressed = true;
  16868. blockBytes = 64;
  16869. dds.format = THREE.RGBAFormat;
  16870. } else {
  16871. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16872. return dds;
  16873. }
  16874. }
  16875. dds.mipmapCount = 1;
  16876. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16877. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16878. }
  16879. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16880. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16881. dds.width = header[ off_width ];
  16882. dds.height = header[ off_height ];
  16883. var dataOffset = header[ off_size ] + 4;
  16884. // Extract mipmaps buffers
  16885. var width = dds.width;
  16886. var height = dds.height;
  16887. var faces = dds.isCubemap ? 6 : 1;
  16888. for ( var face = 0; face < faces; face ++ ) {
  16889. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16890. if( isRGBAUncompressed ) {
  16891. var byteArray = loadARGBMip( buffer, dataOffset, width, height );
  16892. var dataLength = byteArray.length;
  16893. } else {
  16894. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16895. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16896. }
  16897. var mipmap = { "data": byteArray, "width": width, "height": height };
  16898. dds.mipmaps.push( mipmap );
  16899. dataOffset += dataLength;
  16900. width = Math.max( width * 0.5, 1 );
  16901. height = Math.max( height * 0.5, 1 );
  16902. }
  16903. width = dds.width;
  16904. height = dds.height;
  16905. }
  16906. return dds;
  16907. },
  16908. getNormalMap: function ( image, depth ) {
  16909. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16910. var cross = function ( a, b ) {
  16911. 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 ] ];
  16912. }
  16913. var subtract = function ( a, b ) {
  16914. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16915. }
  16916. var normalize = function ( a ) {
  16917. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16918. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16919. }
  16920. depth = depth | 1;
  16921. var width = image.width;
  16922. var height = image.height;
  16923. var canvas = document.createElement( 'canvas' );
  16924. canvas.width = width;
  16925. canvas.height = height;
  16926. var context = canvas.getContext( '2d' );
  16927. context.drawImage( image, 0, 0 );
  16928. var data = context.getImageData( 0, 0, width, height ).data;
  16929. var imageData = context.createImageData( width, height );
  16930. var output = imageData.data;
  16931. for ( var x = 0; x < width; x ++ ) {
  16932. for ( var y = 0; y < height; y ++ ) {
  16933. var ly = y - 1 < 0 ? 0 : y - 1;
  16934. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16935. var lx = x - 1 < 0 ? 0 : x - 1;
  16936. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16937. var points = [];
  16938. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16939. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16940. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16941. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16942. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16943. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16944. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16945. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16946. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16947. var normals = [];
  16948. var num_points = points.length;
  16949. for ( var i = 0; i < num_points; i ++ ) {
  16950. var v1 = points[ i ];
  16951. var v2 = points[ ( i + 1 ) % num_points ];
  16952. v1 = subtract( v1, origin );
  16953. v2 = subtract( v2, origin );
  16954. normals.push( normalize( cross( v1, v2 ) ) );
  16955. }
  16956. var normal = [ 0, 0, 0 ];
  16957. for ( var i = 0; i < normals.length; i ++ ) {
  16958. normal[ 0 ] += normals[ i ][ 0 ];
  16959. normal[ 1 ] += normals[ i ][ 1 ];
  16960. normal[ 2 ] += normals[ i ][ 2 ];
  16961. }
  16962. normal[ 0 ] /= normals.length;
  16963. normal[ 1 ] /= normals.length;
  16964. normal[ 2 ] /= normals.length;
  16965. var idx = ( y * width + x ) * 4;
  16966. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16967. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16968. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16969. output[ idx + 3 ] = 255;
  16970. }
  16971. }
  16972. context.putImageData( imageData, 0, 0 );
  16973. return canvas;
  16974. },
  16975. generateDataTexture: function ( width, height, color ) {
  16976. var size = width * height;
  16977. var data = new Uint8Array( 3 * size );
  16978. var r = Math.floor( color.r * 255 );
  16979. var g = Math.floor( color.g * 255 );
  16980. var b = Math.floor( color.b * 255 );
  16981. for ( var i = 0; i < size; i ++ ) {
  16982. data[ i * 3 ] = r;
  16983. data[ i * 3 + 1 ] = g;
  16984. data[ i * 3 + 2 ] = b;
  16985. }
  16986. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16987. texture.needsUpdate = true;
  16988. return texture;
  16989. }
  16990. };
  16991. /**
  16992. * @author alteredq / http://alteredqualia.com/
  16993. */
  16994. THREE.SceneUtils = {
  16995. createMultiMaterialObject: function ( geometry, materials ) {
  16996. var group = new THREE.Object3D();
  16997. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16998. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16999. }
  17000. return group;
  17001. },
  17002. detach : function ( child, parent, scene ) {
  17003. child.applyMatrix( parent.matrixWorld );
  17004. parent.remove( child );
  17005. scene.add( child );
  17006. },
  17007. attach: function ( child, scene, parent ) {
  17008. var matrixWorldInverse = new THREE.Matrix4();
  17009. matrixWorldInverse.getInverse( parent.matrixWorld );
  17010. child.applyMatrix( matrixWorldInverse );
  17011. scene.remove( child );
  17012. parent.add( child );
  17013. }
  17014. };
  17015. /**
  17016. * @author zz85 / http://www.lab4games.net/zz85/blog
  17017. * @author alteredq / http://alteredqualia.com/
  17018. *
  17019. * For Text operations in three.js (See TextGeometry)
  17020. *
  17021. * It uses techniques used in:
  17022. *
  17023. * typeface.js and canvastext
  17024. * For converting fonts and rendering with javascript
  17025. * http://typeface.neocracy.org
  17026. *
  17027. * Triangulation ported from AS3
  17028. * Simple Polygon Triangulation
  17029. * http://actionsnippet.com/?p=1462
  17030. *
  17031. * A Method to triangulate shapes with holes
  17032. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  17033. *
  17034. */
  17035. THREE.FontUtils = {
  17036. faces : {},
  17037. // Just for now. face[weight][style]
  17038. face : "helvetiker",
  17039. weight: "normal",
  17040. style : "normal",
  17041. size : 150,
  17042. divisions : 10,
  17043. getFace : function() {
  17044. return this.faces[ this.face ][ this.weight ][ this.style ];
  17045. },
  17046. loadFace : function( data ) {
  17047. var family = data.familyName.toLowerCase();
  17048. var ThreeFont = this;
  17049. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  17050. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  17051. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  17052. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  17053. return data;
  17054. },
  17055. drawText : function( text ) {
  17056. var characterPts = [], allPts = [];
  17057. // RenderText
  17058. var i, p,
  17059. face = this.getFace(),
  17060. scale = this.size / face.resolution,
  17061. offset = 0,
  17062. chars = String( text ).split( '' ),
  17063. length = chars.length;
  17064. var fontPaths = [];
  17065. for ( i = 0; i < length; i ++ ) {
  17066. var path = new THREE.Path();
  17067. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  17068. offset += ret.offset;
  17069. fontPaths.push( ret.path );
  17070. }
  17071. // get the width
  17072. var width = offset / 2;
  17073. //
  17074. // for ( p = 0; p < allPts.length; p++ ) {
  17075. //
  17076. // allPts[ p ].x -= width;
  17077. //
  17078. // }
  17079. //var extract = this.extractPoints( allPts, characterPts );
  17080. //extract.contour = allPts;
  17081. //extract.paths = fontPaths;
  17082. //extract.offset = width;
  17083. return { paths : fontPaths, offset : width };
  17084. },
  17085. extractGlyphPoints : function( c, face, scale, offset, path ) {
  17086. var pts = [];
  17087. var i, i2, divisions,
  17088. outline, action, length,
  17089. scaleX, scaleY,
  17090. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  17091. laste,
  17092. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  17093. if ( !glyph ) return;
  17094. if ( glyph.o ) {
  17095. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  17096. length = outline.length;
  17097. scaleX = scale;
  17098. scaleY = scale;
  17099. for ( i = 0; i < length; ) {
  17100. action = outline[ i ++ ];
  17101. //console.log( action );
  17102. switch( action ) {
  17103. case 'm':
  17104. // Move To
  17105. x = outline[ i++ ] * scaleX + offset;
  17106. y = outline[ i++ ] * scaleY;
  17107. path.moveTo( x, y );
  17108. break;
  17109. case 'l':
  17110. // Line To
  17111. x = outline[ i++ ] * scaleX + offset;
  17112. y = outline[ i++ ] * scaleY;
  17113. path.lineTo(x,y);
  17114. break;
  17115. case 'q':
  17116. // QuadraticCurveTo
  17117. cpx = outline[ i++ ] * scaleX + offset;
  17118. cpy = outline[ i++ ] * scaleY;
  17119. cpx1 = outline[ i++ ] * scaleX + offset;
  17120. cpy1 = outline[ i++ ] * scaleY;
  17121. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  17122. laste = pts[ pts.length - 1 ];
  17123. if ( laste ) {
  17124. cpx0 = laste.x;
  17125. cpy0 = laste.y;
  17126. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  17127. var t = i2 / divisions;
  17128. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17129. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17130. }
  17131. }
  17132. break;
  17133. case 'b':
  17134. // Cubic Bezier Curve
  17135. cpx = outline[ i++ ] * scaleX + offset;
  17136. cpy = outline[ i++ ] * scaleY;
  17137. cpx1 = outline[ i++ ] * scaleX + offset;
  17138. cpy1 = outline[ i++ ] * -scaleY;
  17139. cpx2 = outline[ i++ ] * scaleX + offset;
  17140. cpy2 = outline[ i++ ] * -scaleY;
  17141. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  17142. laste = pts[ pts.length - 1 ];
  17143. if ( laste ) {
  17144. cpx0 = laste.x;
  17145. cpy0 = laste.y;
  17146. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  17147. var t = i2 / divisions;
  17148. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17149. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17150. }
  17151. }
  17152. break;
  17153. }
  17154. }
  17155. }
  17156. return { offset: glyph.ha*scale, path:path};
  17157. }
  17158. };
  17159. THREE.FontUtils.generateShapes = function( text, parameters ) {
  17160. // Parameters
  17161. parameters = parameters || {};
  17162. var size = parameters.size !== undefined ? parameters.size : 100;
  17163. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  17164. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  17165. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  17166. var style = parameters.style !== undefined ? parameters.style : "normal";
  17167. THREE.FontUtils.size = size;
  17168. THREE.FontUtils.divisions = curveSegments;
  17169. THREE.FontUtils.face = font;
  17170. THREE.FontUtils.weight = weight;
  17171. THREE.FontUtils.style = style;
  17172. // Get a Font data json object
  17173. var data = THREE.FontUtils.drawText( text );
  17174. var paths = data.paths;
  17175. var shapes = [];
  17176. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  17177. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  17178. }
  17179. return shapes;
  17180. };
  17181. /**
  17182. * This code is a quick port of code written in C++ which was submitted to
  17183. * flipcode.com by John W. Ratcliff // July 22, 2000
  17184. * See original code and more information here:
  17185. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  17186. *
  17187. * ported to actionscript by Zevan Rosser
  17188. * www.actionsnippet.com
  17189. *
  17190. * ported to javascript by Joshua Koo
  17191. * http://www.lab4games.net/zz85/blog
  17192. *
  17193. */
  17194. ( function( namespace ) {
  17195. var EPSILON = 0.0000000001;
  17196. // takes in an contour array and returns
  17197. var process = function( contour, indices ) {
  17198. var n = contour.length;
  17199. if ( n < 3 ) return null;
  17200. var result = [],
  17201. verts = [],
  17202. vertIndices = [];
  17203. /* we want a counter-clockwise polygon in verts */
  17204. var u, v, w;
  17205. if ( area( contour ) > 0.0 ) {
  17206. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  17207. } else {
  17208. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  17209. }
  17210. var nv = n;
  17211. /* remove nv - 2 vertices, creating 1 triangle every time */
  17212. var count = 2 * nv; /* error detection */
  17213. for( v = nv - 1; nv > 2; ) {
  17214. /* if we loop, it is probably a non-simple polygon */
  17215. if ( ( count-- ) <= 0 ) {
  17216. //** Triangulate: ERROR - probable bad polygon!
  17217. //throw ( "Warning, unable to triangulate polygon!" );
  17218. //return null;
  17219. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  17220. console.log( "Warning, unable to triangulate polygon!" );
  17221. if ( indices ) return vertIndices;
  17222. return result;
  17223. }
  17224. /* three consecutive vertices in current polygon, <u,v,w> */
  17225. u = v; if ( nv <= u ) u = 0; /* previous */
  17226. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  17227. w = v + 1; if ( nv <= w ) w = 0; /* next */
  17228. if ( snip( contour, u, v, w, nv, verts ) ) {
  17229. var a, b, c, s, t;
  17230. /* true names of the vertices */
  17231. a = verts[ u ];
  17232. b = verts[ v ];
  17233. c = verts[ w ];
  17234. /* output Triangle */
  17235. result.push( [ contour[ a ],
  17236. contour[ b ],
  17237. contour[ c ] ] );
  17238. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  17239. /* remove v from the remaining polygon */
  17240. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  17241. verts[ s ] = verts[ t ];
  17242. }
  17243. nv--;
  17244. /* reset error detection counter */
  17245. count = 2 * nv;
  17246. }
  17247. }
  17248. if ( indices ) return vertIndices;
  17249. return result;
  17250. };
  17251. // calculate area of the contour polygon
  17252. var area = function ( contour ) {
  17253. var n = contour.length;
  17254. var a = 0.0;
  17255. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  17256. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  17257. }
  17258. return a * 0.5;
  17259. };
  17260. var snip = function ( contour, u, v, w, n, verts ) {
  17261. var p;
  17262. var ax, ay, bx, by;
  17263. var cx, cy, px, py;
  17264. ax = contour[ verts[ u ] ].x;
  17265. ay = contour[ verts[ u ] ].y;
  17266. bx = contour[ verts[ v ] ].x;
  17267. by = contour[ verts[ v ] ].y;
  17268. cx = contour[ verts[ w ] ].x;
  17269. cy = contour[ verts[ w ] ].y;
  17270. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  17271. var aX, aY, bX, bY, cX, cY;
  17272. var apx, apy, bpx, bpy, cpx, cpy;
  17273. var cCROSSap, bCROSScp, aCROSSbp;
  17274. aX = cx - bx; aY = cy - by;
  17275. bX = ax - cx; bY = ay - cy;
  17276. cX = bx - ax; cY = by - ay;
  17277. for ( p = 0; p < n; p++ ) {
  17278. px = contour[ verts[ p ] ].x
  17279. py = contour[ verts[ p ] ].y
  17280. if ( ( (px === ax) && (py === ay) ) ||
  17281. ( (px === bx) && (py === by) ) ||
  17282. ( (px === cx) && (py === cy) ) ) continue;
  17283. apx = px - ax; apy = py - ay;
  17284. bpx = px - bx; bpy = py - by;
  17285. cpx = px - cx; cpy = py - cy;
  17286. // see if p is inside triangle abc
  17287. aCROSSbp = aX*bpy - aY*bpx;
  17288. cCROSSap = cX*apy - cY*apx;
  17289. bCROSScp = bX*cpy - bY*cpx;
  17290. if ( (aCROSSbp >= -EPSILON) && (bCROSScp >= -EPSILON) && (cCROSSap >= -EPSILON) ) return false;
  17291. }
  17292. return true;
  17293. };
  17294. namespace.Triangulate = process;
  17295. namespace.Triangulate.area = area;
  17296. return namespace;
  17297. })(THREE.FontUtils);
  17298. // To use the typeface.js face files, hook up the API
  17299. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  17300. THREE.typeface_js = self._typeface_js;
  17301. /**
  17302. * @author zz85 / http://www.lab4games.net/zz85/blog
  17303. * Extensible curve object
  17304. *
  17305. * Some common of Curve methods
  17306. * .getPoint(t), getTangent(t)
  17307. * .getPointAt(u), getTagentAt(u)
  17308. * .getPoints(), .getSpacedPoints()
  17309. * .getLength()
  17310. * .updateArcLengths()
  17311. *
  17312. * This following classes subclasses THREE.Curve:
  17313. *
  17314. * -- 2d classes --
  17315. * THREE.LineCurve
  17316. * THREE.QuadraticBezierCurve
  17317. * THREE.CubicBezierCurve
  17318. * THREE.SplineCurve
  17319. * THREE.ArcCurve
  17320. * THREE.EllipseCurve
  17321. *
  17322. * -- 3d classes --
  17323. * THREE.LineCurve3
  17324. * THREE.QuadraticBezierCurve3
  17325. * THREE.CubicBezierCurve3
  17326. * THREE.SplineCurve3
  17327. * THREE.ClosedSplineCurve3
  17328. *
  17329. * A series of curves can be represented as a THREE.CurvePath
  17330. *
  17331. **/
  17332. /**************************************************************
  17333. * Abstract Curve base class
  17334. **************************************************************/
  17335. THREE.Curve = function () {
  17336. };
  17337. // Virtual base class method to overwrite and implement in subclasses
  17338. // - t [0 .. 1]
  17339. THREE.Curve.prototype.getPoint = function ( t ) {
  17340. console.log( "Warning, getPoint() not implemented!" );
  17341. return null;
  17342. };
  17343. // Get point at relative position in curve according to arc length
  17344. // - u [0 .. 1]
  17345. THREE.Curve.prototype.getPointAt = function ( u ) {
  17346. var t = this.getUtoTmapping( u );
  17347. return this.getPoint( t );
  17348. };
  17349. // Get sequence of points using getPoint( t )
  17350. THREE.Curve.prototype.getPoints = function ( divisions ) {
  17351. if ( !divisions ) divisions = 5;
  17352. var d, pts = [];
  17353. for ( d = 0; d <= divisions; d ++ ) {
  17354. pts.push( this.getPoint( d / divisions ) );
  17355. }
  17356. return pts;
  17357. };
  17358. // Get sequence of points using getPointAt( u )
  17359. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  17360. if ( !divisions ) divisions = 5;
  17361. var d, pts = [];
  17362. for ( d = 0; d <= divisions; d ++ ) {
  17363. pts.push( this.getPointAt( d / divisions ) );
  17364. }
  17365. return pts;
  17366. };
  17367. // Get total curve arc length
  17368. THREE.Curve.prototype.getLength = function () {
  17369. var lengths = this.getLengths();
  17370. return lengths[ lengths.length - 1 ];
  17371. };
  17372. // Get list of cumulative segment lengths
  17373. THREE.Curve.prototype.getLengths = function ( divisions ) {
  17374. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  17375. if ( this.cacheArcLengths
  17376. && ( this.cacheArcLengths.length == divisions + 1 )
  17377. && !this.needsUpdate) {
  17378. //console.log( "cached", this.cacheArcLengths );
  17379. return this.cacheArcLengths;
  17380. }
  17381. this.needsUpdate = false;
  17382. var cache = [];
  17383. var current, last = this.getPoint( 0 );
  17384. var p, sum = 0;
  17385. cache.push( 0 );
  17386. for ( p = 1; p <= divisions; p ++ ) {
  17387. current = this.getPoint ( p / divisions );
  17388. sum += current.distanceTo( last );
  17389. cache.push( sum );
  17390. last = current;
  17391. }
  17392. this.cacheArcLengths = cache;
  17393. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  17394. };
  17395. THREE.Curve.prototype.updateArcLengths = function() {
  17396. this.needsUpdate = true;
  17397. this.getLengths();
  17398. };
  17399. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  17400. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  17401. var arcLengths = this.getLengths();
  17402. var i = 0, il = arcLengths.length;
  17403. var targetArcLength; // The targeted u distance value to get
  17404. if ( distance ) {
  17405. targetArcLength = distance;
  17406. } else {
  17407. targetArcLength = u * arcLengths[ il - 1 ];
  17408. }
  17409. //var time = Date.now();
  17410. // binary search for the index with largest value smaller than target u distance
  17411. var low = 0, high = il - 1, comparison;
  17412. while ( low <= high ) {
  17413. 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
  17414. comparison = arcLengths[ i ] - targetArcLength;
  17415. if ( comparison < 0 ) {
  17416. low = i + 1;
  17417. continue;
  17418. } else if ( comparison > 0 ) {
  17419. high = i - 1;
  17420. continue;
  17421. } else {
  17422. high = i;
  17423. break;
  17424. // DONE
  17425. }
  17426. }
  17427. i = high;
  17428. //console.log('b' , i, low, high, Date.now()- time);
  17429. if ( arcLengths[ i ] == targetArcLength ) {
  17430. var t = i / ( il - 1 );
  17431. return t;
  17432. }
  17433. // we could get finer grain at lengths, or use simple interpolatation between two points
  17434. var lengthBefore = arcLengths[ i ];
  17435. var lengthAfter = arcLengths[ i + 1 ];
  17436. var segmentLength = lengthAfter - lengthBefore;
  17437. // determine where we are between the 'before' and 'after' points
  17438. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  17439. // add that fractional amount to t
  17440. var t = ( i + segmentFraction ) / ( il -1 );
  17441. return t;
  17442. };
  17443. // Returns a unit vector tangent at t
  17444. // In case any sub curve does not implement its tangent derivation,
  17445. // 2 points a small delta apart will be used to find its gradient
  17446. // which seems to give a reasonable approximation
  17447. THREE.Curve.prototype.getTangent = function( t ) {
  17448. var delta = 0.0001;
  17449. var t1 = t - delta;
  17450. var t2 = t + delta;
  17451. // Capping in case of danger
  17452. if ( t1 < 0 ) t1 = 0;
  17453. if ( t2 > 1 ) t2 = 1;
  17454. var pt1 = this.getPoint( t1 );
  17455. var pt2 = this.getPoint( t2 );
  17456. var vec = pt2.clone().sub(pt1);
  17457. return vec.normalize();
  17458. };
  17459. THREE.Curve.prototype.getTangentAt = function ( u ) {
  17460. var t = this.getUtoTmapping( u );
  17461. return this.getTangent( t );
  17462. };
  17463. /**************************************************************
  17464. * Utils
  17465. **************************************************************/
  17466. THREE.Curve.Utils = {
  17467. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17468. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17469. },
  17470. // Puay Bing, thanks for helping with this derivative!
  17471. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17472. return -3 * p0 * (1 - t) * (1 - t) +
  17473. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17474. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17475. 3 * t * t * p3;
  17476. },
  17477. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17478. // To check if my formulas are correct
  17479. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17480. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17481. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17482. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17483. return h00 + h10 + h01 + h11;
  17484. },
  17485. // Catmull-Rom
  17486. interpolate: function( p0, p1, p2, p3, t ) {
  17487. var v0 = ( p2 - p0 ) * 0.5;
  17488. var v1 = ( p3 - p1 ) * 0.5;
  17489. var t2 = t * t;
  17490. var t3 = t * t2;
  17491. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17492. }
  17493. };
  17494. // TODO: Transformation for Curves?
  17495. /**************************************************************
  17496. * 3D Curves
  17497. **************************************************************/
  17498. // A Factory method for creating new curve subclasses
  17499. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17500. constructor.prototype = Object.create( THREE.Curve.prototype );
  17501. constructor.prototype.getPoint = getPointFunc;
  17502. return constructor;
  17503. };
  17504. /**
  17505. * @author zz85 / http://www.lab4games.net/zz85/blog
  17506. *
  17507. **/
  17508. /**************************************************************
  17509. * Curved Path - a curve path is simply a array of connected
  17510. * curves, but retains the api of a curve
  17511. **************************************************************/
  17512. THREE.CurvePath = function () {
  17513. this.curves = [];
  17514. this.bends = [];
  17515. this.autoClose = false; // Automatically closes the path
  17516. };
  17517. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17518. THREE.CurvePath.prototype.add = function ( curve ) {
  17519. this.curves.push( curve );
  17520. };
  17521. THREE.CurvePath.prototype.checkConnection = function() {
  17522. // TODO
  17523. // If the ending of curve is not connected to the starting
  17524. // or the next curve, then, this is not a real path
  17525. };
  17526. THREE.CurvePath.prototype.closePath = function() {
  17527. // TODO Test
  17528. // and verify for vector3 (needs to implement equals)
  17529. // Add a line curve if start and end of lines are not connected
  17530. var startPoint = this.curves[0].getPoint(0);
  17531. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17532. if (!startPoint.equals(endPoint)) {
  17533. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17534. }
  17535. };
  17536. // To get accurate point with reference to
  17537. // entire path distance at time t,
  17538. // following has to be done:
  17539. // 1. Length of each sub path have to be known
  17540. // 2. Locate and identify type of curve
  17541. // 3. Get t for the curve
  17542. // 4. Return curve.getPointAt(t')
  17543. THREE.CurvePath.prototype.getPoint = function( t ) {
  17544. var d = t * this.getLength();
  17545. var curveLengths = this.getCurveLengths();
  17546. var i = 0, diff, curve;
  17547. // To think about boundaries points.
  17548. while ( i < curveLengths.length ) {
  17549. if ( curveLengths[ i ] >= d ) {
  17550. diff = curveLengths[ i ] - d;
  17551. curve = this.curves[ i ];
  17552. var u = 1 - diff / curve.getLength();
  17553. return curve.getPointAt( u );
  17554. break;
  17555. }
  17556. i ++;
  17557. }
  17558. return null;
  17559. // loop where sum != 0, sum > d , sum+1 <d
  17560. };
  17561. /*
  17562. THREE.CurvePath.prototype.getTangent = function( t ) {
  17563. };*/
  17564. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17565. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17566. // getPoint() depends on getLength
  17567. THREE.CurvePath.prototype.getLength = function() {
  17568. var lens = this.getCurveLengths();
  17569. return lens[ lens.length - 1 ];
  17570. };
  17571. // Compute lengths and cache them
  17572. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17573. THREE.CurvePath.prototype.getCurveLengths = function() {
  17574. // We use cache values if curves and cache array are same length
  17575. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17576. return this.cacheLengths;
  17577. };
  17578. // Get length of subsurve
  17579. // Push sums into cached array
  17580. var lengths = [], sums = 0;
  17581. var i, il = this.curves.length;
  17582. for ( i = 0; i < il; i ++ ) {
  17583. sums += this.curves[ i ].getLength();
  17584. lengths.push( sums );
  17585. }
  17586. this.cacheLengths = lengths;
  17587. return lengths;
  17588. };
  17589. // Returns min and max coordinates
  17590. THREE.CurvePath.prototype.getBoundingBox = function () {
  17591. var points = this.getPoints();
  17592. var maxX, maxY, maxZ;
  17593. var minX, minY, minZ;
  17594. maxX = maxY = Number.NEGATIVE_INFINITY;
  17595. minX = minY = Number.POSITIVE_INFINITY;
  17596. var p, i, il, sum;
  17597. var v3 = points[0] instanceof THREE.Vector3;
  17598. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17599. for ( i = 0, il = points.length; i < il; i ++ ) {
  17600. p = points[ i ];
  17601. if ( p.x > maxX ) maxX = p.x;
  17602. else if ( p.x < minX ) minX = p.x;
  17603. if ( p.y > maxY ) maxY = p.y;
  17604. else if ( p.y < minY ) minY = p.y;
  17605. if ( v3 ) {
  17606. if ( p.z > maxZ ) maxZ = p.z;
  17607. else if ( p.z < minZ ) minZ = p.z;
  17608. }
  17609. sum.add( p );
  17610. }
  17611. var ret = {
  17612. minX: minX,
  17613. minY: minY,
  17614. maxX: maxX,
  17615. maxY: maxY
  17616. };
  17617. if ( v3 ) {
  17618. ret.maxZ = maxZ;
  17619. ret.minZ = minZ;
  17620. }
  17621. return ret;
  17622. };
  17623. /**************************************************************
  17624. * Create Geometries Helpers
  17625. **************************************************************/
  17626. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17627. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17628. var pts = this.getPoints( divisions, true );
  17629. return this.createGeometry( pts );
  17630. };
  17631. // Generate geometry from equidistance sampling along the path
  17632. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17633. var pts = this.getSpacedPoints( divisions, true );
  17634. return this.createGeometry( pts );
  17635. };
  17636. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17637. var geometry = new THREE.Geometry();
  17638. for ( var i = 0; i < points.length; i ++ ) {
  17639. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17640. }
  17641. return geometry;
  17642. };
  17643. /**************************************************************
  17644. * Bend / Wrap Helper Methods
  17645. **************************************************************/
  17646. // Wrap path / Bend modifiers?
  17647. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17648. this.bends.push( bendpath );
  17649. };
  17650. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17651. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17652. var i, il;
  17653. if ( !bends ) {
  17654. bends = this.bends;
  17655. }
  17656. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17657. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17658. }
  17659. return oldPts;
  17660. };
  17661. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17662. var oldPts = this.getSpacedPoints( segments );
  17663. var i, il;
  17664. if ( !bends ) {
  17665. bends = this.bends;
  17666. }
  17667. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17668. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17669. }
  17670. return oldPts;
  17671. };
  17672. // This returns getPoints() bend/wrapped around the contour of a path.
  17673. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17674. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17675. var bounds = this.getBoundingBox();
  17676. var i, il, p, oldX, oldY, xNorm;
  17677. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17678. p = oldPts[ i ];
  17679. oldX = p.x;
  17680. oldY = p.y;
  17681. xNorm = oldX / bounds.maxX;
  17682. // If using actual distance, for length > path, requires line extrusions
  17683. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17684. xNorm = path.getUtoTmapping( xNorm, oldX );
  17685. // check for out of bounds?
  17686. var pathPt = path.getPoint( xNorm );
  17687. var normal = path.getTangent( xNorm );
  17688. normal.set( -normal.y, normal.x ).multiplyScalar( oldY );
  17689. p.x = pathPt.x + normal.x;
  17690. p.y = pathPt.y + normal.y;
  17691. }
  17692. return oldPts;
  17693. };
  17694. /**
  17695. * @author alteredq / http://alteredqualia.com/
  17696. */
  17697. THREE.Gyroscope = function () {
  17698. THREE.Object3D.call( this );
  17699. };
  17700. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17701. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17702. this.matrixAutoUpdate && this.updateMatrix();
  17703. // update matrixWorld
  17704. if ( this.matrixWorldNeedsUpdate || force ) {
  17705. if ( this.parent ) {
  17706. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17707. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17708. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17709. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17710. } else {
  17711. this.matrixWorld.copy( this.matrix );
  17712. }
  17713. this.matrixWorldNeedsUpdate = false;
  17714. force = true;
  17715. }
  17716. // update children
  17717. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17718. this.children[ i ].updateMatrixWorld( force );
  17719. }
  17720. };
  17721. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17722. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17723. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17724. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17725. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17726. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17727. /**
  17728. * @author zz85 / http://www.lab4games.net/zz85/blog
  17729. * Creates free form 2d path using series of points, lines or curves.
  17730. *
  17731. **/
  17732. THREE.Path = function ( points ) {
  17733. THREE.CurvePath.call(this);
  17734. this.actions = [];
  17735. if ( points ) {
  17736. this.fromPoints( points );
  17737. }
  17738. };
  17739. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17740. THREE.PathActions = {
  17741. MOVE_TO: 'moveTo',
  17742. LINE_TO: 'lineTo',
  17743. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17744. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17745. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17746. ARC: 'arc', // Circle
  17747. ELLIPSE: 'ellipse'
  17748. };
  17749. // TODO Clean up PATH API
  17750. // Create path using straight lines to connect all points
  17751. // - vectors: array of Vector2
  17752. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17753. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17754. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17755. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17756. };
  17757. };
  17758. // startPath() endPath()?
  17759. THREE.Path.prototype.moveTo = function ( x, y ) {
  17760. var args = Array.prototype.slice.call( arguments );
  17761. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17762. };
  17763. THREE.Path.prototype.lineTo = function ( x, y ) {
  17764. var args = Array.prototype.slice.call( arguments );
  17765. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17766. var x0 = lastargs[ lastargs.length - 2 ];
  17767. var y0 = lastargs[ lastargs.length - 1 ];
  17768. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17769. this.curves.push( curve );
  17770. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17771. };
  17772. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17773. var args = Array.prototype.slice.call( arguments );
  17774. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17775. var x0 = lastargs[ lastargs.length - 2 ];
  17776. var y0 = lastargs[ lastargs.length - 1 ];
  17777. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17778. new THREE.Vector2( aCPx, aCPy ),
  17779. new THREE.Vector2( aX, aY ) );
  17780. this.curves.push( curve );
  17781. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17782. };
  17783. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17784. aCP2x, aCP2y,
  17785. aX, aY ) {
  17786. var args = Array.prototype.slice.call( arguments );
  17787. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17788. var x0 = lastargs[ lastargs.length - 2 ];
  17789. var y0 = lastargs[ lastargs.length - 1 ];
  17790. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17791. new THREE.Vector2( aCP1x, aCP1y ),
  17792. new THREE.Vector2( aCP2x, aCP2y ),
  17793. new THREE.Vector2( aX, aY ) );
  17794. this.curves.push( curve );
  17795. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17796. };
  17797. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17798. var args = Array.prototype.slice.call( arguments );
  17799. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17800. var x0 = lastargs[ lastargs.length - 2 ];
  17801. var y0 = lastargs[ lastargs.length - 1 ];
  17802. //---
  17803. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17804. Array.prototype.push.apply( npts, pts );
  17805. var curve = new THREE.SplineCurve( npts );
  17806. this.curves.push( curve );
  17807. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17808. };
  17809. // FUTURE: Change the API or follow canvas API?
  17810. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17811. aStartAngle, aEndAngle, aClockwise ) {
  17812. var lastargs = this.actions[ this.actions.length - 1].args;
  17813. var x0 = lastargs[ lastargs.length - 2 ];
  17814. var y0 = lastargs[ lastargs.length - 1 ];
  17815. this.absarc(aX + x0, aY + y0, aRadius,
  17816. aStartAngle, aEndAngle, aClockwise );
  17817. };
  17818. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17819. aStartAngle, aEndAngle, aClockwise ) {
  17820. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17821. };
  17822. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17823. aStartAngle, aEndAngle, aClockwise ) {
  17824. var lastargs = this.actions[ this.actions.length - 1].args;
  17825. var x0 = lastargs[ lastargs.length - 2 ];
  17826. var y0 = lastargs[ lastargs.length - 1 ];
  17827. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17828. aStartAngle, aEndAngle, aClockwise );
  17829. };
  17830. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17831. aStartAngle, aEndAngle, aClockwise ) {
  17832. var args = Array.prototype.slice.call( arguments );
  17833. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17834. aStartAngle, aEndAngle, aClockwise );
  17835. this.curves.push( curve );
  17836. var lastPoint = curve.getPoint(1);
  17837. args.push(lastPoint.x);
  17838. args.push(lastPoint.y);
  17839. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17840. };
  17841. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17842. if ( ! divisions ) divisions = 40;
  17843. var points = [];
  17844. for ( var i = 0; i < divisions; i ++ ) {
  17845. points.push( this.getPoint( i / divisions ) );
  17846. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17847. }
  17848. // if ( closedPath ) {
  17849. //
  17850. // points.push( points[ 0 ] );
  17851. //
  17852. // }
  17853. return points;
  17854. };
  17855. /* Return an array of vectors based on contour of the path */
  17856. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17857. if (this.useSpacedPoints) {
  17858. console.log('tata');
  17859. return this.getSpacedPoints( divisions, closedPath );
  17860. }
  17861. divisions = divisions || 12;
  17862. var points = [];
  17863. var i, il, item, action, args;
  17864. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17865. laste, j,
  17866. t, tx, ty;
  17867. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17868. item = this.actions[ i ];
  17869. action = item.action;
  17870. args = item.args;
  17871. switch( action ) {
  17872. case THREE.PathActions.MOVE_TO:
  17873. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17874. break;
  17875. case THREE.PathActions.LINE_TO:
  17876. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17877. break;
  17878. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17879. cpx = args[ 2 ];
  17880. cpy = args[ 3 ];
  17881. cpx1 = args[ 0 ];
  17882. cpy1 = args[ 1 ];
  17883. if ( points.length > 0 ) {
  17884. laste = points[ points.length - 1 ];
  17885. cpx0 = laste.x;
  17886. cpy0 = laste.y;
  17887. } else {
  17888. laste = this.actions[ i - 1 ].args;
  17889. cpx0 = laste[ laste.length - 2 ];
  17890. cpy0 = laste[ laste.length - 1 ];
  17891. }
  17892. for ( j = 1; j <= divisions; j ++ ) {
  17893. t = j / divisions;
  17894. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17895. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17896. points.push( new THREE.Vector2( tx, ty ) );
  17897. }
  17898. break;
  17899. case THREE.PathActions.BEZIER_CURVE_TO:
  17900. cpx = args[ 4 ];
  17901. cpy = args[ 5 ];
  17902. cpx1 = args[ 0 ];
  17903. cpy1 = args[ 1 ];
  17904. cpx2 = args[ 2 ];
  17905. cpy2 = args[ 3 ];
  17906. if ( points.length > 0 ) {
  17907. laste = points[ points.length - 1 ];
  17908. cpx0 = laste.x;
  17909. cpy0 = laste.y;
  17910. } else {
  17911. laste = this.actions[ i - 1 ].args;
  17912. cpx0 = laste[ laste.length - 2 ];
  17913. cpy0 = laste[ laste.length - 1 ];
  17914. }
  17915. for ( j = 1; j <= divisions; j ++ ) {
  17916. t = j / divisions;
  17917. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17918. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17919. points.push( new THREE.Vector2( tx, ty ) );
  17920. }
  17921. break;
  17922. case THREE.PathActions.CSPLINE_THRU:
  17923. laste = this.actions[ i - 1 ].args;
  17924. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17925. var spts = [ last ];
  17926. var n = divisions * args[ 0 ].length;
  17927. spts = spts.concat( args[ 0 ] );
  17928. var spline = new THREE.SplineCurve( spts );
  17929. for ( j = 1; j <= n; j ++ ) {
  17930. points.push( spline.getPointAt( j / n ) ) ;
  17931. }
  17932. break;
  17933. case THREE.PathActions.ARC:
  17934. var aX = args[ 0 ], aY = args[ 1 ],
  17935. aRadius = args[ 2 ],
  17936. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17937. aClockwise = !!args[ 5 ];
  17938. var deltaAngle = aEndAngle - aStartAngle;
  17939. var angle;
  17940. var tdivisions = divisions * 2;
  17941. for ( j = 1; j <= tdivisions; j ++ ) {
  17942. t = j / tdivisions;
  17943. if ( ! aClockwise ) {
  17944. t = 1 - t;
  17945. }
  17946. angle = aStartAngle + t * deltaAngle;
  17947. tx = aX + aRadius * Math.cos( angle );
  17948. ty = aY + aRadius * Math.sin( angle );
  17949. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17950. points.push( new THREE.Vector2( tx, ty ) );
  17951. }
  17952. //console.log(points);
  17953. break;
  17954. case THREE.PathActions.ELLIPSE:
  17955. var aX = args[ 0 ], aY = args[ 1 ],
  17956. xRadius = args[ 2 ],
  17957. yRadius = args[ 3 ],
  17958. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17959. aClockwise = !!args[ 6 ];
  17960. var deltaAngle = aEndAngle - aStartAngle;
  17961. var angle;
  17962. var tdivisions = divisions * 2;
  17963. for ( j = 1; j <= tdivisions; j ++ ) {
  17964. t = j / tdivisions;
  17965. if ( ! aClockwise ) {
  17966. t = 1 - t;
  17967. }
  17968. angle = aStartAngle + t * deltaAngle;
  17969. tx = aX + xRadius * Math.cos( angle );
  17970. ty = aY + yRadius * Math.sin( angle );
  17971. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17972. points.push( new THREE.Vector2( tx, ty ) );
  17973. }
  17974. //console.log(points);
  17975. break;
  17976. } // end switch
  17977. }
  17978. // Normalize to remove the closing point by default.
  17979. var lastPoint = points[ points.length - 1];
  17980. var EPSILON = 0.0000000001;
  17981. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17982. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17983. points.splice( points.length - 1, 1);
  17984. if ( closedPath ) {
  17985. points.push( points[ 0 ] );
  17986. }
  17987. return points;
  17988. };
  17989. // Breaks path into shapes
  17990. THREE.Path.prototype.toShapes = function( isCCW ) {
  17991. function isPointInsidePolygon( inPt, inPolygon ) {
  17992. var EPSILON = 0.0000000001;
  17993. var polyLen = inPolygon.length;
  17994. // inPt on polygon contour => immediate success or
  17995. // toggling of inside/outside at every single! intersection point of an edge
  17996. // with the horizontal line through inPt, left of inPt
  17997. // not counting lowerY endpoints of edges and whole edges on that line
  17998. var inside = false;
  17999. for( var p = polyLen - 1, q = 0; q < polyLen; p = q++ ) {
  18000. var edgeLowPt = inPolygon[ p ];
  18001. var edgeHighPt = inPolygon[ q ];
  18002. var edgeDx = edgeHighPt.x - edgeLowPt.x;
  18003. var edgeDy = edgeHighPt.y - edgeLowPt.y;
  18004. if ( Math.abs(edgeDy) > EPSILON ) { // not parallel
  18005. if ( edgeDy < 0 ) {
  18006. edgeLowPt = inPolygon[ q ]; edgeDx = -edgeDx;
  18007. edgeHighPt = inPolygon[ p ]; edgeDy = -edgeDy;
  18008. }
  18009. if ( ( inPt.y < edgeLowPt.y ) || ( inPt.y > edgeHighPt.y ) ) continue;
  18010. if ( inPt.y == edgeLowPt.y ) {
  18011. if ( inPt.x == edgeLowPt.x ) return true; // inPt is on contour ?
  18012. // continue; // no intersection or edgeLowPt => doesn't count !!!
  18013. } else {
  18014. var perpEdge = edgeDy * (inPt.x - edgeLowPt.x) - edgeDx * (inPt.y - edgeLowPt.y);
  18015. if ( perpEdge == 0 ) return true; // inPt is on contour ?
  18016. if ( perpEdge < 0 ) continue;
  18017. inside = !inside; // true intersection left of inPt
  18018. }
  18019. } else { // parallel or colinear
  18020. if ( inPt.y != edgeLowPt.y ) continue; // parallel
  18021. // egde lies on the same horizontal line as inPt
  18022. if ( ( ( edgeHighPt.x <= inPt.x ) && ( inPt.x <= edgeLowPt.x ) ) ||
  18023. ( ( edgeLowPt.x <= inPt.x ) && ( inPt.x <= edgeHighPt.x ) ) ) return true; // inPt: Point on contour !
  18024. // continue;
  18025. }
  18026. }
  18027. return inside;
  18028. }
  18029. var i, il, item, action, args;
  18030. var subPaths = [], lastPath = new THREE.Path();
  18031. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  18032. item = this.actions[ i ];
  18033. args = item.args;
  18034. action = item.action;
  18035. if ( action == THREE.PathActions.MOVE_TO ) {
  18036. if ( lastPath.actions.length != 0 ) {
  18037. subPaths.push( lastPath );
  18038. lastPath = new THREE.Path();
  18039. }
  18040. }
  18041. lastPath[ action ].apply( lastPath, args );
  18042. }
  18043. if ( lastPath.actions.length != 0 ) {
  18044. subPaths.push( lastPath );
  18045. }
  18046. // console.log(subPaths);
  18047. if ( subPaths.length == 0 ) return [];
  18048. var solid, tmpPath, tmpShape, shapes = [];
  18049. if ( subPaths.length == 1) {
  18050. tmpPath = subPaths[0];
  18051. tmpShape = new THREE.Shape();
  18052. tmpShape.actions = tmpPath.actions;
  18053. tmpShape.curves = tmpPath.curves;
  18054. shapes.push( tmpShape );
  18055. return shapes;
  18056. }
  18057. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  18058. holesFirst = isCCW ? !holesFirst : holesFirst;
  18059. // console.log("Holes first", holesFirst);
  18060. var betterShapeHoles = [];
  18061. var newShapes = [];
  18062. var newShapeHoles = [];
  18063. var mainIdx = 0;
  18064. var tmpPoints;
  18065. newShapes[mainIdx] = undefined;
  18066. newShapeHoles[mainIdx] = [];
  18067. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  18068. tmpPath = subPaths[ i ];
  18069. tmpPoints = tmpPath.getPoints();
  18070. solid = THREE.Shape.Utils.isClockWise( tmpPoints );
  18071. solid = isCCW ? !solid : solid;
  18072. if ( solid ) {
  18073. if ( (! holesFirst ) && ( newShapes[mainIdx] ) ) mainIdx++;
  18074. newShapes[mainIdx] = { s: new THREE.Shape(), p: tmpPoints };
  18075. newShapes[mainIdx].s.actions = tmpPath.actions;
  18076. newShapes[mainIdx].s.curves = tmpPath.curves;
  18077. if ( holesFirst ) mainIdx++;
  18078. newShapeHoles[mainIdx] = [];
  18079. //console.log('cw', i);
  18080. } else {
  18081. newShapeHoles[mainIdx].push( { h: tmpPath, p: tmpPoints[0] } );
  18082. //console.log('ccw', i);
  18083. }
  18084. }
  18085. if ( newShapes.length > 1 ) {
  18086. var ambigious = false;
  18087. var toChange = [];
  18088. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  18089. betterShapeHoles[sIdx] = [];
  18090. }
  18091. for (var sIdx = 0, sLen = newShapes.length; sIdx < sLen; sIdx++ ) {
  18092. var sh = newShapes[sIdx];
  18093. var sho = newShapeHoles[sIdx];
  18094. for (var hIdx = 0; hIdx < sho.length; hIdx++ ) {
  18095. var ho = sho[hIdx];
  18096. var hole_unassigned = true;
  18097. for (var s2Idx = 0; s2Idx < newShapes.length; s2Idx++ ) {
  18098. if ( isPointInsidePolygon( ho.p, newShapes[s2Idx].p ) ) {
  18099. if ( sIdx != s2Idx ) toChange.push( { froms: sIdx, tos: s2Idx, hole: hIdx } );
  18100. if ( hole_unassigned ) {
  18101. hole_unassigned = false;
  18102. betterShapeHoles[s2Idx].push( ho );
  18103. } else {
  18104. ambigious = true;
  18105. }
  18106. }
  18107. }
  18108. if ( hole_unassigned ) { betterShapeHoles[sIdx].push( ho ); }
  18109. }
  18110. }
  18111. // console.log("ambigious: ", ambigious);
  18112. if ( toChange.length > 0 ) {
  18113. // console.log("to change: ", toChange);
  18114. if (! ambigious) newShapeHoles = betterShapeHoles;
  18115. }
  18116. }
  18117. var tmpHoles, j, jl;
  18118. for ( i = 0, il = newShapes.length; i < il; i ++ ) {
  18119. tmpShape = newShapes[i].s;
  18120. shapes.push( tmpShape );
  18121. tmpHoles = newShapeHoles[i];
  18122. for ( j = 0, jl = tmpHoles.length; j < jl; j ++ ) {
  18123. tmpShape.holes.push( tmpHoles[j].h );
  18124. }
  18125. }
  18126. //console.log("shape", shapes);
  18127. return shapes;
  18128. };
  18129. /**
  18130. * @author zz85 / http://www.lab4games.net/zz85/blog
  18131. * Defines a 2d shape plane using paths.
  18132. **/
  18133. // STEP 1 Create a path.
  18134. // STEP 2 Turn path into shape.
  18135. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  18136. // STEP 3a - Extract points from each shape, turn to vertices
  18137. // STEP 3b - Triangulate each shape, add faces.
  18138. THREE.Shape = function () {
  18139. THREE.Path.apply( this, arguments );
  18140. this.holes = [];
  18141. };
  18142. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  18143. // Convenience method to return ExtrudeGeometry
  18144. THREE.Shape.prototype.extrude = function ( options ) {
  18145. var extruded = new THREE.ExtrudeGeometry( this, options );
  18146. return extruded;
  18147. };
  18148. // Convenience method to return ShapeGeometry
  18149. THREE.Shape.prototype.makeGeometry = function ( options ) {
  18150. var geometry = new THREE.ShapeGeometry( this, options );
  18151. return geometry;
  18152. };
  18153. // Get points of holes
  18154. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  18155. var i, il = this.holes.length, holesPts = [];
  18156. for ( i = 0; i < il; i ++ ) {
  18157. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  18158. }
  18159. return holesPts;
  18160. };
  18161. // Get points of holes (spaced by regular distance)
  18162. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  18163. var i, il = this.holes.length, holesPts = [];
  18164. for ( i = 0; i < il; i ++ ) {
  18165. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  18166. }
  18167. return holesPts;
  18168. };
  18169. // Get points of shape and holes (keypoints based on segments parameter)
  18170. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  18171. return {
  18172. shape: this.getTransformedPoints( divisions ),
  18173. holes: this.getPointsHoles( divisions )
  18174. };
  18175. };
  18176. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  18177. if (this.useSpacedPoints) {
  18178. return this.extractAllSpacedPoints(divisions);
  18179. }
  18180. return this.extractAllPoints(divisions);
  18181. };
  18182. //
  18183. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  18184. //
  18185. // return {
  18186. //
  18187. // shape: this.transform( bend, divisions ),
  18188. // holes: this.getPointsHoles( divisions, bend )
  18189. //
  18190. // };
  18191. //
  18192. // };
  18193. // Get points of shape and holes (spaced by regular distance)
  18194. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  18195. return {
  18196. shape: this.getTransformedSpacedPoints( divisions ),
  18197. holes: this.getSpacedPointsHoles( divisions )
  18198. };
  18199. };
  18200. /**************************************************************
  18201. * Utils
  18202. **************************************************************/
  18203. THREE.Shape.Utils = {
  18204. triangulateShape: function ( contour, holes ) {
  18205. function point_in_segment_2D_colin( inSegPt1, inSegPt2, inOtherPt ) {
  18206. // inOtherPt needs to be colinear to the inSegment
  18207. if ( inSegPt1.x != inSegPt2.x ) {
  18208. if ( inSegPt1.x < inSegPt2.x ) {
  18209. return ( ( inSegPt1.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt2.x ) );
  18210. } else {
  18211. return ( ( inSegPt2.x <= inOtherPt.x ) && ( inOtherPt.x <= inSegPt1.x ) );
  18212. }
  18213. } else {
  18214. if ( inSegPt1.y < inSegPt2.y ) {
  18215. return ( ( inSegPt1.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt2.y ) );
  18216. } else {
  18217. return ( ( inSegPt2.y <= inOtherPt.y ) && ( inOtherPt.y <= inSegPt1.y ) );
  18218. }
  18219. }
  18220. }
  18221. function intersect_segments_2D( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1, inSeg2Pt2, inExcludeAdjacentSegs ) {
  18222. var EPSILON = 0.0000000001;
  18223. var seg1dx = inSeg1Pt2.x - inSeg1Pt1.x, seg1dy = inSeg1Pt2.y - inSeg1Pt1.y;
  18224. var seg2dx = inSeg2Pt2.x - inSeg2Pt1.x, seg2dy = inSeg2Pt2.y - inSeg2Pt1.y;
  18225. var seg1seg2dx = inSeg1Pt1.x - inSeg2Pt1.x;
  18226. var seg1seg2dy = inSeg1Pt1.y - inSeg2Pt1.y;
  18227. var limit = seg1dy * seg2dx - seg1dx * seg2dy;
  18228. var perpSeg1 = seg1dy * seg1seg2dx - seg1dx * seg1seg2dy;
  18229. if ( Math.abs(limit) > EPSILON ) { // not parallel
  18230. var perpSeg2;
  18231. if ( limit > 0 ) {
  18232. if ( ( perpSeg1 < 0 ) || ( perpSeg1 > limit ) ) return [];
  18233. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  18234. if ( ( perpSeg2 < 0 ) || ( perpSeg2 > limit ) ) return [];
  18235. } else {
  18236. if ( ( perpSeg1 > 0 ) || ( perpSeg1 < limit ) ) return [];
  18237. perpSeg2 = seg2dy * seg1seg2dx - seg2dx * seg1seg2dy;
  18238. if ( ( perpSeg2 > 0 ) || ( perpSeg2 < limit ) ) return [];
  18239. }
  18240. // i.e. to reduce rounding errors
  18241. // intersection at endpoint of segment#1?
  18242. if ( perpSeg2 == 0 ) {
  18243. if ( ( inExcludeAdjacentSegs ) &&
  18244. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  18245. return [ inSeg1Pt1 ];
  18246. }
  18247. if ( perpSeg2 == limit ) {
  18248. if ( ( inExcludeAdjacentSegs ) &&
  18249. ( ( perpSeg1 == 0 ) || ( perpSeg1 == limit ) ) ) return [];
  18250. return [ inSeg1Pt2 ];
  18251. }
  18252. // intersection at endpoint of segment#2?
  18253. if ( perpSeg1 == 0 ) return [ inSeg2Pt1 ];
  18254. if ( perpSeg1 == limit ) return [ inSeg2Pt2 ];
  18255. // return real intersection point
  18256. var factorSeg1 = perpSeg2 / limit;
  18257. return [ { x: inSeg1Pt1.x + factorSeg1 * seg1dx,
  18258. y: inSeg1Pt1.y + factorSeg1 * seg1dy } ];
  18259. } else { // parallel or colinear
  18260. if ( ( perpSeg1 != 0 ) ||
  18261. ( seg2dy * seg1seg2dx != seg2dx * seg1seg2dy ) ) return [];
  18262. // they are collinear or degenerate
  18263. var seg1Pt = ( (seg1dx == 0) && (seg1dy == 0) ); // segment1 ist just a point?
  18264. var seg2Pt = ( (seg2dx == 0) && (seg2dy == 0) ); // segment2 ist just a point?
  18265. // both segments are points
  18266. if ( seg1Pt && seg2Pt ) {
  18267. if ( (inSeg1Pt1.x != inSeg2Pt1.x) ||
  18268. (inSeg1Pt1.y != inSeg2Pt1.y) ) return []; // they are distinct points
  18269. return [ inSeg1Pt1 ]; // they are the same point
  18270. }
  18271. // segment#1 is a single point
  18272. if ( seg1Pt ) {
  18273. if (! point_in_segment_2D_colin( inSeg2Pt1, inSeg2Pt2, inSeg1Pt1 ) ) return []; // but not in segment#2
  18274. return [ inSeg1Pt1 ];
  18275. }
  18276. // segment#2 is a single point
  18277. if ( seg2Pt ) {
  18278. if (! point_in_segment_2D_colin( inSeg1Pt1, inSeg1Pt2, inSeg2Pt1 ) ) return []; // but not in segment#1
  18279. return [ inSeg2Pt1 ];
  18280. }
  18281. // they are collinear segments, which might overlap
  18282. var seg1min, seg1max, seg1minVal, seg1maxVal;
  18283. var seg2min, seg2max, seg2minVal, seg2maxVal;
  18284. if (seg1dx != 0) { // the segments are NOT on a vertical line
  18285. if ( inSeg1Pt1.x < inSeg1Pt2.x ) {
  18286. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.x;
  18287. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.x;
  18288. } else {
  18289. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.x;
  18290. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.x;
  18291. }
  18292. if ( inSeg2Pt1.x < inSeg2Pt2.x ) {
  18293. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.x;
  18294. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.x;
  18295. } else {
  18296. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.x;
  18297. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.x;
  18298. }
  18299. } else { // the segments are on a vertical line
  18300. if ( inSeg1Pt1.y < inSeg1Pt2.y ) {
  18301. seg1min = inSeg1Pt1; seg1minVal = inSeg1Pt1.y;
  18302. seg1max = inSeg1Pt2; seg1maxVal = inSeg1Pt2.y;
  18303. } else {
  18304. seg1min = inSeg1Pt2; seg1minVal = inSeg1Pt2.y;
  18305. seg1max = inSeg1Pt1; seg1maxVal = inSeg1Pt1.y;
  18306. }
  18307. if ( inSeg2Pt1.y < inSeg2Pt2.y ) {
  18308. seg2min = inSeg2Pt1; seg2minVal = inSeg2Pt1.y;
  18309. seg2max = inSeg2Pt2; seg2maxVal = inSeg2Pt2.y;
  18310. } else {
  18311. seg2min = inSeg2Pt2; seg2minVal = inSeg2Pt2.y;
  18312. seg2max = inSeg2Pt1; seg2maxVal = inSeg2Pt1.y;
  18313. }
  18314. }
  18315. if ( seg1minVal <= seg2minVal ) {
  18316. if ( seg1maxVal < seg2minVal ) return [];
  18317. if ( seg1maxVal == seg2minVal ) {
  18318. if ( inExcludeAdjacentSegs ) return [];
  18319. return [ seg2min ];
  18320. }
  18321. if ( seg1maxVal <= seg2maxVal ) return [ seg2min, seg1max ];
  18322. return [ seg2min, seg2max ];
  18323. } else {
  18324. if ( seg1minVal > seg2maxVal ) return [];
  18325. if ( seg1minVal == seg2maxVal ) {
  18326. if ( inExcludeAdjacentSegs ) return [];
  18327. return [ seg1min ];
  18328. }
  18329. if ( seg1maxVal <= seg2maxVal ) return [ seg1min, seg1max ];
  18330. return [ seg1min, seg2max ];
  18331. }
  18332. }
  18333. }
  18334. function isPointInsideAngle( inVertex, inLegFromPt, inLegToPt, inOtherPt ) {
  18335. // The order of legs is important
  18336. var EPSILON = 0.0000000001;
  18337. // translation of all points, so that Vertex is at (0,0)
  18338. var legFromPtX = inLegFromPt.x - inVertex.x, legFromPtY = inLegFromPt.y - inVertex.y;
  18339. var legToPtX = inLegToPt.x - inVertex.x, legToPtY = inLegToPt.y - inVertex.y;
  18340. var otherPtX = inOtherPt.x - inVertex.x, otherPtY = inOtherPt.y - inVertex.y;
  18341. // main angle >0: < 180 deg.; 0: 180 deg.; <0: > 180 deg.
  18342. var from2toAngle = legFromPtX * legToPtY - legFromPtY * legToPtX;
  18343. var from2otherAngle = legFromPtX * otherPtY - legFromPtY * otherPtX;
  18344. if ( Math.abs(from2toAngle) > EPSILON ) { // angle != 180 deg.
  18345. var other2toAngle = otherPtX * legToPtY - otherPtY * legToPtX;
  18346. // console.log( "from2to: " + from2toAngle + ", from2other: " + from2otherAngle + ", other2to: " + other2toAngle );
  18347. if ( from2toAngle > 0 ) { // main angle < 180 deg.
  18348. return ( ( from2otherAngle >= 0 ) && ( other2toAngle >= 0 ) );
  18349. } else { // main angle > 180 deg.
  18350. return ( ( from2otherAngle >= 0 ) || ( other2toAngle >= 0 ) );
  18351. }
  18352. } else { // angle == 180 deg.
  18353. // console.log( "from2to: 180 deg., from2other: " + from2otherAngle );
  18354. return ( from2otherAngle > 0 );
  18355. }
  18356. }
  18357. function removeHoles( contour, holes ) {
  18358. var shape = contour.concat(); // work on this shape
  18359. var hole;
  18360. function isCutLineInsideAngles( inShapeIdx, inHoleIdx ) {
  18361. // Check if hole point lies within angle around shape point
  18362. var lastShapeIdx = shape.length - 1;
  18363. var prevShapeIdx = inShapeIdx - 1;
  18364. if ( prevShapeIdx < 0 ) prevShapeIdx = lastShapeIdx;
  18365. var nextShapeIdx = inShapeIdx + 1;
  18366. if ( nextShapeIdx > lastShapeIdx ) nextShapeIdx = 0;
  18367. var insideAngle = isPointInsideAngle( shape[inShapeIdx], shape[ prevShapeIdx ], shape[ nextShapeIdx ], hole[inHoleIdx] );
  18368. if (! insideAngle ) {
  18369. // console.log( "Vertex (Shape): " + inShapeIdx + ", Point: " + hole[inHoleIdx].x + "/" + hole[inHoleIdx].y );
  18370. return false;
  18371. }
  18372. // Check if shape point lies within angle around hole point
  18373. var lastHoleIdx = hole.length - 1;
  18374. var prevHoleIdx = inHoleIdx - 1;
  18375. if ( prevHoleIdx < 0 ) prevHoleIdx = lastHoleIdx;
  18376. var nextHoleIdx = inHoleIdx + 1;
  18377. if ( nextHoleIdx > lastHoleIdx ) nextHoleIdx = 0;
  18378. insideAngle = isPointInsideAngle( hole[inHoleIdx], hole[ prevHoleIdx ], hole[ nextHoleIdx ], shape[inShapeIdx] );
  18379. if (! insideAngle ) {
  18380. // console.log( "Vertex (Hole): " + inHoleIdx + ", Point: " + shape[inShapeIdx].x + "/" + shape[inShapeIdx].y );
  18381. return false;
  18382. }
  18383. return true;
  18384. }
  18385. function intersectsShapeEdge( inShapePt, inHolePt ) {
  18386. // checks for intersections with shape edges
  18387. var sIdx, nextIdx, intersection;
  18388. for ( sIdx = 0; sIdx < shape.length; sIdx++ ) {
  18389. nextIdx = sIdx+1; nextIdx %= shape.length;
  18390. intersection = intersect_segments_2D( inShapePt, inHolePt, shape[sIdx], shape[nextIdx], true );
  18391. if ( intersection.length > 0 ) return true;
  18392. }
  18393. return false;
  18394. }
  18395. var indepHoles = [];
  18396. function intersectsHoleEdge( inShapePt, inHolePt ) {
  18397. // checks for intersections with hole edges
  18398. var ihIdx, chkHole,
  18399. hIdx, nextIdx, intersection;
  18400. for ( ihIdx = 0; ihIdx < indepHoles.length; ihIdx++ ) {
  18401. chkHole = holes[indepHoles[ihIdx]];
  18402. for ( hIdx = 0; hIdx < chkHole.length; hIdx++ ) {
  18403. nextIdx = hIdx+1; nextIdx %= chkHole.length;
  18404. intersection = intersect_segments_2D( inShapePt, inHolePt, chkHole[hIdx], chkHole[nextIdx], true );
  18405. if ( intersection.length > 0 ) return true;
  18406. }
  18407. }
  18408. return false;
  18409. }
  18410. var holeIndex, shapeIndex,
  18411. shapePt, holePt,
  18412. holeIdx, cutKey, failedCuts = [],
  18413. tmpShape1, tmpShape2,
  18414. tmpHole1, tmpHole2;
  18415. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18416. indepHoles.push( h );
  18417. }
  18418. var counter = indepHoles.length * 2;
  18419. while ( indepHoles.length > 0 ) {
  18420. counter --;
  18421. if ( counter < 0 ) {
  18422. console.log( "Infinite Loop! Holes left:" + indepHoles.length + ", Probably Hole outside Shape!" );
  18423. break;
  18424. }
  18425. // search for shape-vertex and hole-vertex,
  18426. // which can be connected without intersections
  18427. for ( shapeIndex = 0; shapeIndex < shape.length; shapeIndex++ ) {
  18428. shapePt = shape[ shapeIndex ];
  18429. holeIndex = -1;
  18430. // search for hole which can be reached without intersections
  18431. for ( var h = 0; h < indepHoles.length; h ++ ) {
  18432. holeIdx = indepHoles[h];
  18433. // prevent multiple checks
  18434. cutKey = shapePt.x + ":" + shapePt.y + ":" + holeIdx;
  18435. if ( failedCuts[cutKey] !== undefined ) continue;
  18436. hole = holes[holeIdx];
  18437. for ( var h2 = 0; h2 < hole.length; h2 ++ ) {
  18438. holePt = hole[ h2 ];
  18439. if (! isCutLineInsideAngles( shapeIndex, h2 ) ) continue;
  18440. if ( intersectsShapeEdge( shapePt, holePt ) ) continue;
  18441. if ( intersectsHoleEdge( shapePt, holePt ) ) continue;
  18442. holeIndex = h2;
  18443. indepHoles.splice(h,1);
  18444. tmpShape1 = shape.slice( 0, shapeIndex+1 );
  18445. tmpShape2 = shape.slice( shapeIndex );
  18446. tmpHole1 = hole.slice( holeIndex );
  18447. tmpHole2 = hole.slice( 0, holeIndex+1 );
  18448. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  18449. // Debug only, to show the selected cuts
  18450. // glob_CutLines.push( [ shapePt, holePt ] );
  18451. break;
  18452. }
  18453. if ( holeIndex >= 0 ) break; // hole-vertex found
  18454. failedCuts[cutKey] = true; // remember failure
  18455. }
  18456. if ( holeIndex >= 0 ) break; // hole-vertex found
  18457. }
  18458. }
  18459. return shape; /* shape with no holes */
  18460. }
  18461. var i, il, f, face,
  18462. key, index,
  18463. allPointsMap = {};
  18464. // 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.
  18465. var allpoints = contour.concat();
  18466. for ( var h = 0, hl = holes.length; h < hl; h ++ ) {
  18467. Array.prototype.push.apply( allpoints, holes[h] );
  18468. }
  18469. //console.log( "allpoints",allpoints, allpoints.length );
  18470. // prepare all points map
  18471. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  18472. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  18473. if ( allPointsMap[ key ] !== undefined ) {
  18474. console.log( "Duplicate point", key );
  18475. }
  18476. allPointsMap[ key ] = i;
  18477. }
  18478. // remove holes by cutting paths to holes and adding them to the shape
  18479. var shapeWithoutHoles = removeHoles( contour, holes );
  18480. var triangles = THREE.FontUtils.Triangulate( shapeWithoutHoles, false ); // True returns indices for points of spooled shape
  18481. //console.log( "triangles",triangles, triangles.length );
  18482. // check all face vertices against all points map
  18483. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  18484. face = triangles[ i ];
  18485. for ( f = 0; f < 3; f ++ ) {
  18486. key = face[ f ].x + ":" + face[ f ].y;
  18487. index = allPointsMap[ key ];
  18488. if ( index !== undefined ) {
  18489. face[ f ] = index;
  18490. }
  18491. }
  18492. }
  18493. return triangles.concat();
  18494. },
  18495. isClockWise: function ( pts ) {
  18496. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  18497. },
  18498. // Bezier Curves formulas obtained from
  18499. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  18500. // Quad Bezier Functions
  18501. b2p0: function ( t, p ) {
  18502. var k = 1 - t;
  18503. return k * k * p;
  18504. },
  18505. b2p1: function ( t, p ) {
  18506. return 2 * ( 1 - t ) * t * p;
  18507. },
  18508. b2p2: function ( t, p ) {
  18509. return t * t * p;
  18510. },
  18511. b2: function ( t, p0, p1, p2 ) {
  18512. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  18513. },
  18514. // Cubic Bezier Functions
  18515. b3p0: function ( t, p ) {
  18516. var k = 1 - t;
  18517. return k * k * k * p;
  18518. },
  18519. b3p1: function ( t, p ) {
  18520. var k = 1 - t;
  18521. return 3 * k * k * t * p;
  18522. },
  18523. b3p2: function ( t, p ) {
  18524. var k = 1 - t;
  18525. return 3 * k * t * t * p;
  18526. },
  18527. b3p3: function ( t, p ) {
  18528. return t * t * t * p;
  18529. },
  18530. b3: function ( t, p0, p1, p2, p3 ) {
  18531. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  18532. }
  18533. };
  18534. /**************************************************************
  18535. * Line
  18536. **************************************************************/
  18537. THREE.LineCurve = function ( v1, v2 ) {
  18538. this.v1 = v1;
  18539. this.v2 = v2;
  18540. };
  18541. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  18542. THREE.LineCurve.prototype.getPoint = function ( t ) {
  18543. var point = this.v2.clone().sub(this.v1);
  18544. point.multiplyScalar( t ).add( this.v1 );
  18545. return point;
  18546. };
  18547. // Line curve is linear, so we can overwrite default getPointAt
  18548. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  18549. return this.getPoint( u );
  18550. };
  18551. THREE.LineCurve.prototype.getTangent = function( t ) {
  18552. var tangent = this.v2.clone().sub(this.v1);
  18553. return tangent.normalize();
  18554. };
  18555. /**************************************************************
  18556. * Quadratic Bezier curve
  18557. **************************************************************/
  18558. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  18559. this.v0 = v0;
  18560. this.v1 = v1;
  18561. this.v2 = v2;
  18562. };
  18563. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18564. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  18565. var tx, ty;
  18566. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18567. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18568. return new THREE.Vector2( tx, ty );
  18569. };
  18570. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  18571. var tx, ty;
  18572. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  18573. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  18574. // returns unit vector
  18575. var tangent = new THREE.Vector2( tx, ty );
  18576. tangent.normalize();
  18577. return tangent;
  18578. };
  18579. /**************************************************************
  18580. * Cubic Bezier curve
  18581. **************************************************************/
  18582. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  18583. this.v0 = v0;
  18584. this.v1 = v1;
  18585. this.v2 = v2;
  18586. this.v3 = v3;
  18587. };
  18588. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  18589. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  18590. var tx, ty;
  18591. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18592. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18593. return new THREE.Vector2( tx, ty );
  18594. };
  18595. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  18596. var tx, ty;
  18597. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18598. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18599. var tangent = new THREE.Vector2( tx, ty );
  18600. tangent.normalize();
  18601. return tangent;
  18602. };
  18603. /**************************************************************
  18604. * Spline curve
  18605. **************************************************************/
  18606. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  18607. this.points = (points == undefined) ? [] : points;
  18608. };
  18609. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18610. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18611. var v = new THREE.Vector2();
  18612. var c = [];
  18613. var points = this.points, point, intPoint, weight;
  18614. point = ( points.length - 1 ) * t;
  18615. intPoint = Math.floor( point );
  18616. weight = point - intPoint;
  18617. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18618. c[ 1 ] = intPoint;
  18619. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18620. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18621. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18622. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18623. return v;
  18624. };
  18625. /**************************************************************
  18626. * Ellipse curve
  18627. **************************************************************/
  18628. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius, aStartAngle, aEndAngle, aClockwise ) {
  18629. this.aX = aX;
  18630. this.aY = aY;
  18631. this.xRadius = xRadius;
  18632. this.yRadius = yRadius;
  18633. this.aStartAngle = aStartAngle;
  18634. this.aEndAngle = aEndAngle;
  18635. this.aClockwise = aClockwise;
  18636. };
  18637. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18638. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18639. var angle;
  18640. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18641. if ( deltaAngle < 0 ) deltaAngle += Math.PI * 2;
  18642. if ( deltaAngle > Math.PI * 2 ) deltaAngle -= Math.PI * 2;
  18643. if ( this.aClockwise === true ) {
  18644. angle = this.aEndAngle + ( 1 - t ) * ( Math.PI * 2 - deltaAngle );
  18645. } else {
  18646. angle = this.aStartAngle + t * deltaAngle;
  18647. }
  18648. var tx = this.aX + this.xRadius * Math.cos( angle );
  18649. var ty = this.aY + this.yRadius * Math.sin( angle );
  18650. return new THREE.Vector2( tx, ty );
  18651. };
  18652. /**************************************************************
  18653. * Arc curve
  18654. **************************************************************/
  18655. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18656. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18657. };
  18658. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18659. /**************************************************************
  18660. * Line3D
  18661. **************************************************************/
  18662. THREE.LineCurve3 = THREE.Curve.create(
  18663. function ( v1, v2 ) {
  18664. this.v1 = v1;
  18665. this.v2 = v2;
  18666. },
  18667. function ( t ) {
  18668. var r = new THREE.Vector3();
  18669. r.subVectors( this.v2, this.v1 ); // diff
  18670. r.multiplyScalar( t );
  18671. r.add( this.v1 );
  18672. return r;
  18673. }
  18674. );
  18675. /**************************************************************
  18676. * Quadratic Bezier 3D curve
  18677. **************************************************************/
  18678. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18679. function ( v0, v1, v2 ) {
  18680. this.v0 = v0;
  18681. this.v1 = v1;
  18682. this.v2 = v2;
  18683. },
  18684. function ( t ) {
  18685. var tx, ty, tz;
  18686. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18687. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18688. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18689. return new THREE.Vector3( tx, ty, tz );
  18690. }
  18691. );
  18692. /**************************************************************
  18693. * Cubic Bezier 3D curve
  18694. **************************************************************/
  18695. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18696. function ( v0, v1, v2, v3 ) {
  18697. this.v0 = v0;
  18698. this.v1 = v1;
  18699. this.v2 = v2;
  18700. this.v3 = v3;
  18701. },
  18702. function ( t ) {
  18703. var tx, ty, tz;
  18704. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18705. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18706. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18707. return new THREE.Vector3( tx, ty, tz );
  18708. }
  18709. );
  18710. /**************************************************************
  18711. * Spline 3D curve
  18712. **************************************************************/
  18713. THREE.SplineCurve3 = THREE.Curve.create(
  18714. function ( points /* array of Vector3 */) {
  18715. this.points = (points == undefined) ? [] : points;
  18716. },
  18717. function ( t ) {
  18718. var v = new THREE.Vector3();
  18719. var c = [];
  18720. var points = this.points, point, intPoint, weight;
  18721. point = ( points.length - 1 ) * t;
  18722. intPoint = Math.floor( point );
  18723. weight = point - intPoint;
  18724. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18725. c[ 1 ] = intPoint;
  18726. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18727. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18728. var pt0 = points[ c[0] ],
  18729. pt1 = points[ c[1] ],
  18730. pt2 = points[ c[2] ],
  18731. pt3 = points[ c[3] ];
  18732. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18733. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18734. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18735. return v;
  18736. }
  18737. );
  18738. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18739. // var v = new THREE.Vector3();
  18740. // var c = [];
  18741. // var points = this.points, point, intPoint, weight;
  18742. // point = ( points.length - 1 ) * t;
  18743. // intPoint = Math.floor( point );
  18744. // weight = point - intPoint;
  18745. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18746. // c[ 1 ] = intPoint;
  18747. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18748. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18749. // var pt0 = points[ c[0] ],
  18750. // pt1 = points[ c[1] ],
  18751. // pt2 = points[ c[2] ],
  18752. // pt3 = points[ c[3] ];
  18753. // // t = weight;
  18754. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18755. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18756. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18757. // return v;
  18758. // }
  18759. /**************************************************************
  18760. * Closed Spline 3D curve
  18761. **************************************************************/
  18762. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18763. function ( points /* array of Vector3 */) {
  18764. this.points = (points == undefined) ? [] : points;
  18765. },
  18766. function ( t ) {
  18767. var v = new THREE.Vector3();
  18768. var c = [];
  18769. var points = this.points, point, intPoint, weight;
  18770. point = ( points.length - 0 ) * t;
  18771. // This needs to be from 0-length +1
  18772. intPoint = Math.floor( point );
  18773. weight = point - intPoint;
  18774. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18775. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18776. c[ 1 ] = ( intPoint ) % points.length;
  18777. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18778. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18779. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18780. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18781. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18782. return v;
  18783. }
  18784. );
  18785. /**
  18786. * @author mikael emtinger / http://gomo.se/
  18787. */
  18788. THREE.AnimationHandler = ( function () {
  18789. var playing = [];
  18790. var library = {};
  18791. var that = {};
  18792. that.update = function ( deltaTimeMS ) {
  18793. for ( var i = 0; i < playing.length; i ++ ) {
  18794. playing[ i ].update( deltaTimeMS );
  18795. }
  18796. };
  18797. that.addToUpdate = function ( animation ) {
  18798. if ( playing.indexOf( animation ) === -1 ) {
  18799. playing.push( animation );
  18800. }
  18801. };
  18802. that.removeFromUpdate = function ( animation ) {
  18803. var index = playing.indexOf( animation );
  18804. if ( index !== -1 ) {
  18805. playing.splice( index, 1 );
  18806. }
  18807. };
  18808. that.add = function ( data ) {
  18809. if ( library[ data.name ] !== undefined ) {
  18810. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18811. }
  18812. library[ data.name ] = data;
  18813. initData( data );
  18814. };
  18815. that.remove = function ( name ) {
  18816. if ( library[ name ] === undefined ) {
  18817. console.log( "THREE.AnimationHandler.add: Warning! " + name + " doesn't exists in library. Doing nothing." );
  18818. }
  18819. library[ name ] = undefined;
  18820. };
  18821. that.get = function ( name ) {
  18822. if ( typeof name === "string" ) {
  18823. if ( library[ name ] ) {
  18824. return library[ name ];
  18825. } else {
  18826. return null;
  18827. }
  18828. } else {
  18829. // todo: add simple tween library
  18830. }
  18831. };
  18832. that.parse = function ( root ) {
  18833. // setup hierarchy
  18834. var hierarchy = [];
  18835. if ( root instanceof THREE.SkinnedMesh ) {
  18836. for ( var b = 0; b < root.bones.length; b++ ) {
  18837. hierarchy.push( root.bones[ b ] );
  18838. }
  18839. } else {
  18840. parseRecurseHierarchy( root, hierarchy );
  18841. }
  18842. return hierarchy;
  18843. };
  18844. var parseRecurseHierarchy = function ( root, hierarchy ) {
  18845. hierarchy.push( root );
  18846. for ( var c = 0; c < root.children.length; c++ )
  18847. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18848. }
  18849. var initData = function ( data ) {
  18850. if ( data.initialized === true )
  18851. return;
  18852. // loop through all keys
  18853. for ( var h = 0; h < data.hierarchy.length; h ++ ) {
  18854. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18855. // remove minus times
  18856. if ( data.hierarchy[ h ].keys[ k ].time < 0 ) {
  18857. data.hierarchy[ h ].keys[ k ].time = 0;
  18858. }
  18859. // create quaternions
  18860. if ( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18861. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18862. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18863. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion().fromArray( quat );
  18864. }
  18865. }
  18866. // prepare morph target keys
  18867. if ( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18868. // get all used
  18869. var usedMorphTargets = {};
  18870. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18871. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18872. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18873. usedMorphTargets[ morphTargetName ] = -1;
  18874. }
  18875. }
  18876. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18877. // set all used on all frames
  18878. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18879. var influences = {};
  18880. for ( var morphTargetName in usedMorphTargets ) {
  18881. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18882. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18883. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18884. break;
  18885. }
  18886. }
  18887. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18888. influences[ morphTargetName ] = 0;
  18889. }
  18890. }
  18891. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18892. }
  18893. }
  18894. // remove all keys that are on the same time
  18895. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18896. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18897. data.hierarchy[ h ].keys.splice( k, 1 );
  18898. k --;
  18899. }
  18900. }
  18901. // set index
  18902. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18903. data.hierarchy[ h ].keys[ k ].index = k;
  18904. }
  18905. }
  18906. data.initialized = true;
  18907. };
  18908. // interpolation types
  18909. that.LINEAR = 0;
  18910. that.CATMULLROM = 1;
  18911. that.CATMULLROM_FORWARD = 2;
  18912. return that;
  18913. }() );
  18914. /**
  18915. * @author mikael emtinger / http://gomo.se/
  18916. * @author mrdoob / http://mrdoob.com/
  18917. * @author alteredq / http://alteredqualia.com/
  18918. */
  18919. THREE.Animation = function ( root, name ) {
  18920. this.root = root;
  18921. this.data = THREE.AnimationHandler.get( name );
  18922. this.hierarchy = THREE.AnimationHandler.parse( root );
  18923. this.currentTime = 0;
  18924. this.timeScale = 1;
  18925. this.isPlaying = false;
  18926. this.isPaused = true;
  18927. this.loop = true;
  18928. this.interpolationType = THREE.AnimationHandler.LINEAR;
  18929. };
  18930. THREE.Animation.prototype.play = function ( startTime ) {
  18931. this.currentTime = startTime !== undefined ? startTime : 0;
  18932. if ( this.isPlaying === false ) {
  18933. this.isPlaying = true;
  18934. this.reset();
  18935. this.update( 0 );
  18936. }
  18937. this.isPaused = false;
  18938. THREE.AnimationHandler.addToUpdate( this );
  18939. };
  18940. THREE.Animation.prototype.pause = function() {
  18941. if ( this.isPaused === true ) {
  18942. THREE.AnimationHandler.addToUpdate( this );
  18943. } else {
  18944. THREE.AnimationHandler.removeFromUpdate( this );
  18945. }
  18946. this.isPaused = !this.isPaused;
  18947. };
  18948. THREE.Animation.prototype.stop = function() {
  18949. this.isPlaying = false;
  18950. this.isPaused = false;
  18951. THREE.AnimationHandler.removeFromUpdate( this );
  18952. };
  18953. THREE.Animation.prototype.reset = function () {
  18954. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18955. var object = this.hierarchy[ h ];
  18956. object.matrixAutoUpdate = true;
  18957. if ( object.animationCache === undefined ) {
  18958. object.animationCache = {};
  18959. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18960. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18961. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18962. }
  18963. var prevKey = object.animationCache.prevKey;
  18964. var nextKey = object.animationCache.nextKey;
  18965. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18966. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18967. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18968. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18969. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18970. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18971. }
  18972. };
  18973. THREE.Animation.prototype.update = (function(){
  18974. var points = [];
  18975. var target = new THREE.Vector3();
  18976. // Catmull-Rom spline
  18977. var interpolateCatmullRom = function ( points, scale ) {
  18978. var c = [], v3 = [],
  18979. point, intPoint, weight, w2, w3,
  18980. pa, pb, pc, pd;
  18981. point = ( points.length - 1 ) * scale;
  18982. intPoint = Math.floor( point );
  18983. weight = point - intPoint;
  18984. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18985. c[ 1 ] = intPoint;
  18986. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18987. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18988. pa = points[ c[ 0 ] ];
  18989. pb = points[ c[ 1 ] ];
  18990. pc = points[ c[ 2 ] ];
  18991. pd = points[ c[ 3 ] ];
  18992. w2 = weight * weight;
  18993. w3 = weight * w2;
  18994. v3[ 0 ] = interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18995. v3[ 1 ] = interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18996. v3[ 2 ] = interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18997. return v3;
  18998. };
  18999. var interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  19000. var v0 = ( p2 - p0 ) * 0.5,
  19001. v1 = ( p3 - p1 ) * 0.5;
  19002. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  19003. };
  19004. return function ( delta ) {
  19005. if ( this.isPlaying === false ) return;
  19006. this.currentTime += delta * this.timeScale;
  19007. //
  19008. var vector;
  19009. var types = [ "pos", "rot", "scl" ];
  19010. var duration = this.data.length;
  19011. if ( this.loop === true && this.currentTime > duration ) {
  19012. this.currentTime %= duration;
  19013. this.reset();
  19014. } else if ( this.loop === false && this.currentTime > duration ) {
  19015. this.stop();
  19016. return;
  19017. }
  19018. this.currentTime = Math.min( this.currentTime, duration );
  19019. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  19020. var object = this.hierarchy[ h ];
  19021. var animationCache = object.animationCache;
  19022. // loop through pos/rot/scl
  19023. for ( var t = 0; t < 3; t ++ ) {
  19024. // get keys
  19025. var type = types[ t ];
  19026. var prevKey = animationCache.prevKey[ type ];
  19027. var nextKey = animationCache.nextKey[ type ];
  19028. if ( nextKey.time <= this.currentTime ) {
  19029. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  19030. nextKey = this.getNextKeyWith( type, h, 1 );
  19031. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  19032. prevKey = nextKey;
  19033. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  19034. }
  19035. animationCache.prevKey[ type ] = prevKey;
  19036. animationCache.nextKey[ type ] = nextKey;
  19037. }
  19038. object.matrixAutoUpdate = true;
  19039. object.matrixWorldNeedsUpdate = true;
  19040. var scale = ( this.currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  19041. var prevXYZ = prevKey[ type ];
  19042. var nextXYZ = nextKey[ type ];
  19043. if ( scale < 0 ) scale = 0;
  19044. if ( scale > 1 ) scale = 1;
  19045. // interpolate
  19046. if ( type === "pos" ) {
  19047. vector = object.position;
  19048. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  19049. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  19050. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  19051. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  19052. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  19053. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19054. points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  19055. points[ 1 ] = prevXYZ;
  19056. points[ 2 ] = nextXYZ;
  19057. points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  19058. scale = scale * 0.33 + 0.33;
  19059. var currentPoint = interpolateCatmullRom( points, scale );
  19060. vector.x = currentPoint[ 0 ];
  19061. vector.y = currentPoint[ 1 ];
  19062. vector.z = currentPoint[ 2 ];
  19063. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19064. var forwardPoint = interpolateCatmullRom( points, scale * 1.01 );
  19065. target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  19066. target.sub( vector );
  19067. target.y = 0;
  19068. target.normalize();
  19069. var angle = Math.atan2( target.x, target.z );
  19070. object.rotation.set( 0, angle, 0 );
  19071. }
  19072. }
  19073. } else if ( type === "rot" ) {
  19074. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  19075. } else if ( type === "scl" ) {
  19076. vector = object.scale;
  19077. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  19078. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  19079. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  19080. }
  19081. }
  19082. }
  19083. };
  19084. })();
  19085. // Get next key with
  19086. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  19087. var keys = this.data.hierarchy[ h ].keys;
  19088. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  19089. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19090. key = key < keys.length - 1 ? key : keys.length - 1;
  19091. } else {
  19092. key = key % keys.length;
  19093. }
  19094. for ( ; key < keys.length; key++ ) {
  19095. if ( keys[ key ][ type ] !== undefined ) {
  19096. return keys[ key ];
  19097. }
  19098. }
  19099. return this.data.hierarchy[ h ].keys[ 0 ];
  19100. };
  19101. // Get previous key with
  19102. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  19103. var keys = this.data.hierarchy[ h ].keys;
  19104. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  19105. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  19106. key = key > 0 ? key : 0;
  19107. } else {
  19108. key = key >= 0 ? key : key + keys.length;
  19109. }
  19110. for ( ; key >= 0; key -- ) {
  19111. if ( keys[ key ][ type ] !== undefined ) {
  19112. return keys[ key ];
  19113. }
  19114. }
  19115. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  19116. };
  19117. /**
  19118. * @author mikael emtinger / http://gomo.se/
  19119. * @author mrdoob / http://mrdoob.com/
  19120. * @author alteredq / http://alteredqualia.com/
  19121. * @author khang duong
  19122. * @author erik kitson
  19123. */
  19124. THREE.KeyFrameAnimation = function ( root, data ) {
  19125. this.root = root;
  19126. this.data = THREE.AnimationHandler.get( data );
  19127. this.hierarchy = THREE.AnimationHandler.parse( root );
  19128. this.currentTime = 0;
  19129. this.timeScale = 0.001;
  19130. this.isPlaying = false;
  19131. this.isPaused = true;
  19132. this.loop = true;
  19133. // initialize to first keyframes
  19134. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  19135. var keys = this.data.hierarchy[h].keys,
  19136. sids = this.data.hierarchy[h].sids,
  19137. obj = this.hierarchy[h];
  19138. if ( keys.length && sids ) {
  19139. for ( var s = 0; s < sids.length; s++ ) {
  19140. var sid = sids[ s ],
  19141. next = this.getNextKeyWith( sid, h, 0 );
  19142. if ( next ) {
  19143. next.apply( sid );
  19144. }
  19145. }
  19146. obj.matrixAutoUpdate = false;
  19147. this.data.hierarchy[h].node.updateMatrix();
  19148. obj.matrixWorldNeedsUpdate = true;
  19149. }
  19150. }
  19151. };
  19152. // Play
  19153. THREE.KeyFrameAnimation.prototype.play = function ( startTime ) {
  19154. this.currentTime = startTime !== undefined ? startTime : 0;
  19155. if ( this.isPlaying === false ) {
  19156. this.isPlaying = true;
  19157. // reset key cache
  19158. var h, hl = this.hierarchy.length,
  19159. object,
  19160. node;
  19161. for ( h = 0; h < hl; h++ ) {
  19162. object = this.hierarchy[ h ];
  19163. node = this.data.hierarchy[ h ];
  19164. if ( node.animationCache === undefined ) {
  19165. node.animationCache = {};
  19166. node.animationCache.prevKey = null;
  19167. node.animationCache.nextKey = null;
  19168. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  19169. }
  19170. var keys = this.data.hierarchy[h].keys;
  19171. if (keys.length) {
  19172. node.animationCache.prevKey = keys[ 0 ];
  19173. node.animationCache.nextKey = keys[ 1 ];
  19174. this.startTime = Math.min( keys[0].time, this.startTime );
  19175. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  19176. }
  19177. }
  19178. this.update( 0 );
  19179. }
  19180. this.isPaused = false;
  19181. THREE.AnimationHandler.addToUpdate( this );
  19182. };
  19183. // Pause
  19184. THREE.KeyFrameAnimation.prototype.pause = function() {
  19185. if( this.isPaused ) {
  19186. THREE.AnimationHandler.addToUpdate( this );
  19187. } else {
  19188. THREE.AnimationHandler.removeFromUpdate( this );
  19189. }
  19190. this.isPaused = !this.isPaused;
  19191. };
  19192. // Stop
  19193. THREE.KeyFrameAnimation.prototype.stop = function() {
  19194. this.isPlaying = false;
  19195. this.isPaused = false;
  19196. THREE.AnimationHandler.removeFromUpdate( this );
  19197. // reset JIT matrix and remove cache
  19198. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  19199. var obj = this.hierarchy[ h ];
  19200. var node = this.data.hierarchy[ h ];
  19201. if ( node.animationCache !== undefined ) {
  19202. var original = node.animationCache.originalMatrix;
  19203. if( obj instanceof THREE.Bone ) {
  19204. original.copy( obj.skinMatrix );
  19205. obj.skinMatrix = original;
  19206. } else {
  19207. original.copy( obj.matrix );
  19208. obj.matrix = original;
  19209. }
  19210. delete node.animationCache;
  19211. }
  19212. }
  19213. };
  19214. // Update
  19215. THREE.KeyFrameAnimation.prototype.update = function ( delta ) {
  19216. if ( this.isPlaying === false ) return;
  19217. this.currentTime += delta * this.timeScale;
  19218. //
  19219. var duration = this.data.length;
  19220. if ( this.loop === true && this.currentTime > duration ) {
  19221. this.currentTime %= duration;
  19222. }
  19223. this.currentTime = Math.min( this.currentTime, duration );
  19224. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  19225. var object = this.hierarchy[ h ];
  19226. var node = this.data.hierarchy[ h ];
  19227. var keys = node.keys,
  19228. animationCache = node.animationCache;
  19229. if ( keys.length ) {
  19230. var prevKey = animationCache.prevKey;
  19231. var nextKey = animationCache.nextKey;
  19232. if ( nextKey.time <= this.currentTime ) {
  19233. while ( nextKey.time < this.currentTime && nextKey.index > prevKey.index ) {
  19234. prevKey = nextKey;
  19235. nextKey = keys[ prevKey.index + 1 ];
  19236. }
  19237. animationCache.prevKey = prevKey;
  19238. animationCache.nextKey = nextKey;
  19239. }
  19240. if ( nextKey.time >= this.currentTime ) {
  19241. prevKey.interpolate( nextKey, this.currentTime );
  19242. } else {
  19243. prevKey.interpolate( nextKey, nextKey.time );
  19244. }
  19245. this.data.hierarchy[ h ].node.updateMatrix();
  19246. object.matrixWorldNeedsUpdate = true;
  19247. }
  19248. }
  19249. };
  19250. // Get next key with
  19251. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  19252. var keys = this.data.hierarchy[ h ].keys;
  19253. key = key % keys.length;
  19254. for ( ; key < keys.length; key++ ) {
  19255. if ( keys[ key ].hasTarget( sid ) ) {
  19256. return keys[ key ];
  19257. }
  19258. }
  19259. return keys[ 0 ];
  19260. };
  19261. // Get previous key with
  19262. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  19263. var keys = this.data.hierarchy[ h ].keys;
  19264. key = key >= 0 ? key : key + keys.length;
  19265. for ( ; key >= 0; key-- ) {
  19266. if ( keys[ key ].hasTarget( sid ) ) {
  19267. return keys[ key ];
  19268. }
  19269. }
  19270. return keys[ keys.length - 1 ];
  19271. };
  19272. /**
  19273. * @author mrdoob / http://mrdoob.com
  19274. */
  19275. THREE.MorphAnimation = function ( mesh ) {
  19276. this.mesh = mesh;
  19277. this.frames = mesh.morphTargetInfluences.length;
  19278. this.currentTime = 0;
  19279. this.duration = 1000;
  19280. this.loop = true;
  19281. this.isPlaying = false;
  19282. };
  19283. THREE.MorphAnimation.prototype = {
  19284. play: function () {
  19285. this.isPlaying = true;
  19286. },
  19287. pause: function () {
  19288. this.isPlaying = false;
  19289. },
  19290. update: ( function () {
  19291. var lastFrame = 0;
  19292. var currentFrame = 0;
  19293. return function ( delta ) {
  19294. if ( this.isPlaying === false ) return;
  19295. this.currentTime += delta;
  19296. if ( this.loop === true && this.currentTime > this.duration ) {
  19297. this.currentTime %= this.duration;
  19298. }
  19299. this.currentTime = Math.min( this.currentTime, this.duration );
  19300. var interpolation = this.duration / this.frames;
  19301. var frame = Math.floor( this.currentTime / interpolation );
  19302. if ( frame != currentFrame ) {
  19303. this.mesh.morphTargetInfluences[ lastFrame ] = 0;
  19304. this.mesh.morphTargetInfluences[ currentFrame ] = 1;
  19305. this.mesh.morphTargetInfluences[ frame ] = 0;
  19306. lastFrame = currentFrame;
  19307. currentFrame = frame;
  19308. }
  19309. this.mesh.morphTargetInfluences[ frame ] = ( this.currentTime % interpolation ) / interpolation;
  19310. this.mesh.morphTargetInfluences[ lastFrame ] = 1 - this.mesh.morphTargetInfluences[ frame ];
  19311. }
  19312. } )()
  19313. };
  19314. /**
  19315. * Camera for rendering cube maps
  19316. * - renders scene into axis-aligned cube
  19317. *
  19318. * @author alteredq / http://alteredqualia.com/
  19319. */
  19320. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  19321. THREE.Object3D.call( this );
  19322. var fov = 90, aspect = 1;
  19323. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19324. cameraPX.up.set( 0, -1, 0 );
  19325. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  19326. this.add( cameraPX );
  19327. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19328. cameraNX.up.set( 0, -1, 0 );
  19329. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  19330. this.add( cameraNX );
  19331. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19332. cameraPY.up.set( 0, 0, 1 );
  19333. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  19334. this.add( cameraPY );
  19335. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19336. cameraNY.up.set( 0, 0, -1 );
  19337. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  19338. this.add( cameraNY );
  19339. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19340. cameraPZ.up.set( 0, -1, 0 );
  19341. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  19342. this.add( cameraPZ );
  19343. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  19344. cameraNZ.up.set( 0, -1, 0 );
  19345. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  19346. this.add( cameraNZ );
  19347. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  19348. this.updateCubeMap = function ( renderer, scene ) {
  19349. var renderTarget = this.renderTarget;
  19350. var generateMipmaps = renderTarget.generateMipmaps;
  19351. renderTarget.generateMipmaps = false;
  19352. renderTarget.activeCubeFace = 0;
  19353. renderer.render( scene, cameraPX, renderTarget );
  19354. renderTarget.activeCubeFace = 1;
  19355. renderer.render( scene, cameraNX, renderTarget );
  19356. renderTarget.activeCubeFace = 2;
  19357. renderer.render( scene, cameraPY, renderTarget );
  19358. renderTarget.activeCubeFace = 3;
  19359. renderer.render( scene, cameraNY, renderTarget );
  19360. renderTarget.activeCubeFace = 4;
  19361. renderer.render( scene, cameraPZ, renderTarget );
  19362. renderTarget.generateMipmaps = generateMipmaps;
  19363. renderTarget.activeCubeFace = 5;
  19364. renderer.render( scene, cameraNZ, renderTarget );
  19365. };
  19366. };
  19367. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  19368. /**
  19369. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19370. *
  19371. * A general perpose camera, for setting FOV, Lens Focal Length,
  19372. * and switching between perspective and orthographic views easily.
  19373. * Use this only if you do not wish to manage
  19374. * both a Orthographic and Perspective Camera
  19375. *
  19376. */
  19377. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  19378. THREE.Camera.call( this );
  19379. this.fov = fov;
  19380. this.left = -width / 2;
  19381. this.right = width / 2
  19382. this.top = height / 2;
  19383. this.bottom = -height / 2;
  19384. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  19385. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  19386. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  19387. this.zoom = 1;
  19388. this.toPerspective();
  19389. var aspect = width/height;
  19390. };
  19391. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  19392. THREE.CombinedCamera.prototype.toPerspective = function () {
  19393. // Switches to the Perspective Camera
  19394. this.near = this.cameraP.near;
  19395. this.far = this.cameraP.far;
  19396. this.cameraP.fov = this.fov / this.zoom ;
  19397. this.cameraP.updateProjectionMatrix();
  19398. this.projectionMatrix = this.cameraP.projectionMatrix;
  19399. this.inPerspectiveMode = true;
  19400. this.inOrthographicMode = false;
  19401. };
  19402. THREE.CombinedCamera.prototype.toOrthographic = function () {
  19403. // Switches to the Orthographic camera estimating viewport from Perspective
  19404. var fov = this.fov;
  19405. var aspect = this.cameraP.aspect;
  19406. var near = this.cameraP.near;
  19407. var far = this.cameraP.far;
  19408. // The size that we set is the mid plane of the viewing frustum
  19409. var hyperfocus = ( near + far ) / 2;
  19410. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  19411. var planeHeight = 2 * halfHeight;
  19412. var planeWidth = planeHeight * aspect;
  19413. var halfWidth = planeWidth / 2;
  19414. halfHeight /= this.zoom;
  19415. halfWidth /= this.zoom;
  19416. this.cameraO.left = -halfWidth;
  19417. this.cameraO.right = halfWidth;
  19418. this.cameraO.top = halfHeight;
  19419. this.cameraO.bottom = -halfHeight;
  19420. // this.cameraO.left = -farHalfWidth;
  19421. // this.cameraO.right = farHalfWidth;
  19422. // this.cameraO.top = farHalfHeight;
  19423. // this.cameraO.bottom = -farHalfHeight;
  19424. // this.cameraO.left = this.left / this.zoom;
  19425. // this.cameraO.right = this.right / this.zoom;
  19426. // this.cameraO.top = this.top / this.zoom;
  19427. // this.cameraO.bottom = this.bottom / this.zoom;
  19428. this.cameraO.updateProjectionMatrix();
  19429. this.near = this.cameraO.near;
  19430. this.far = this.cameraO.far;
  19431. this.projectionMatrix = this.cameraO.projectionMatrix;
  19432. this.inPerspectiveMode = false;
  19433. this.inOrthographicMode = true;
  19434. };
  19435. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  19436. this.cameraP.aspect = width / height;
  19437. this.left = -width / 2;
  19438. this.right = width / 2
  19439. this.top = height / 2;
  19440. this.bottom = -height / 2;
  19441. };
  19442. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  19443. this.fov = fov;
  19444. if ( this.inPerspectiveMode ) {
  19445. this.toPerspective();
  19446. } else {
  19447. this.toOrthographic();
  19448. }
  19449. };
  19450. // For mantaining similar API with PerspectiveCamera
  19451. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  19452. if ( this.inPerspectiveMode ) {
  19453. this.toPerspective();
  19454. } else {
  19455. this.toPerspective();
  19456. this.toOrthographic();
  19457. }
  19458. };
  19459. /*
  19460. * Uses Focal Length (in mm) to estimate and set FOV
  19461. * 35mm (fullframe) camera is used if frame size is not specified;
  19462. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  19463. */
  19464. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  19465. if ( frameHeight === undefined ) frameHeight = 24;
  19466. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  19467. this.setFov( fov );
  19468. return fov;
  19469. };
  19470. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  19471. this.zoom = zoom;
  19472. if ( this.inPerspectiveMode ) {
  19473. this.toPerspective();
  19474. } else {
  19475. this.toOrthographic();
  19476. }
  19477. };
  19478. THREE.CombinedCamera.prototype.toFrontView = function() {
  19479. this.rotation.x = 0;
  19480. this.rotation.y = 0;
  19481. this.rotation.z = 0;
  19482. // should we be modifing the matrix instead?
  19483. this.rotationAutoUpdate = false;
  19484. };
  19485. THREE.CombinedCamera.prototype.toBackView = function() {
  19486. this.rotation.x = 0;
  19487. this.rotation.y = Math.PI;
  19488. this.rotation.z = 0;
  19489. this.rotationAutoUpdate = false;
  19490. };
  19491. THREE.CombinedCamera.prototype.toLeftView = function() {
  19492. this.rotation.x = 0;
  19493. this.rotation.y = - Math.PI / 2;
  19494. this.rotation.z = 0;
  19495. this.rotationAutoUpdate = false;
  19496. };
  19497. THREE.CombinedCamera.prototype.toRightView = function() {
  19498. this.rotation.x = 0;
  19499. this.rotation.y = Math.PI / 2;
  19500. this.rotation.z = 0;
  19501. this.rotationAutoUpdate = false;
  19502. };
  19503. THREE.CombinedCamera.prototype.toTopView = function() {
  19504. this.rotation.x = - Math.PI / 2;
  19505. this.rotation.y = 0;
  19506. this.rotation.z = 0;
  19507. this.rotationAutoUpdate = false;
  19508. };
  19509. THREE.CombinedCamera.prototype.toBottomView = function() {
  19510. this.rotation.x = Math.PI / 2;
  19511. this.rotation.y = 0;
  19512. this.rotation.z = 0;
  19513. this.rotationAutoUpdate = false;
  19514. };
  19515. /**
  19516. * @author mrdoob / http://mrdoob.com/
  19517. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19518. */
  19519. THREE.BoxGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19520. THREE.Geometry.call( this );
  19521. this.parameters = {
  19522. width: width,
  19523. height: height,
  19524. depth: depth,
  19525. widthSegments: widthSegments,
  19526. heightSegments: heightSegments,
  19527. depthSegments: depthSegments
  19528. };
  19529. this.widthSegments = widthSegments || 1;
  19530. this.heightSegments = heightSegments || 1;
  19531. this.depthSegments = depthSegments || 1;
  19532. var scope = this;
  19533. var width_half = width / 2;
  19534. var height_half = height / 2;
  19535. var depth_half = depth / 2;
  19536. buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, 0 ); // px
  19537. buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, 1 ); // nx
  19538. buildPlane( 'x', 'z', 1, 1, width, depth, height_half, 2 ); // py
  19539. buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, 3 ); // ny
  19540. buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, 4 ); // pz
  19541. buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, 5 ); // nz
  19542. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19543. var w, ix, iy,
  19544. gridX = scope.widthSegments,
  19545. gridY = scope.heightSegments,
  19546. width_half = width / 2,
  19547. height_half = height / 2,
  19548. offset = scope.vertices.length;
  19549. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19550. w = 'z';
  19551. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19552. w = 'y';
  19553. gridY = scope.depthSegments;
  19554. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19555. w = 'x';
  19556. gridX = scope.depthSegments;
  19557. }
  19558. var gridX1 = gridX + 1,
  19559. gridY1 = gridY + 1,
  19560. segment_width = width / gridX,
  19561. segment_height = height / gridY,
  19562. normal = new THREE.Vector3();
  19563. normal[ w ] = depth > 0 ? 1 : - 1;
  19564. for ( iy = 0; iy < gridY1; iy ++ ) {
  19565. for ( ix = 0; ix < gridX1; ix ++ ) {
  19566. var vector = new THREE.Vector3();
  19567. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19568. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19569. vector[ w ] = depth;
  19570. scope.vertices.push( vector );
  19571. }
  19572. }
  19573. for ( iy = 0; iy < gridY; iy++ ) {
  19574. for ( ix = 0; ix < gridX; ix++ ) {
  19575. var a = ix + gridX1 * iy;
  19576. var b = ix + gridX1 * ( iy + 1 );
  19577. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19578. var d = ( ix + 1 ) + gridX1 * iy;
  19579. var uva = new THREE.Vector2( ix / gridX, 1 - iy / gridY );
  19580. var uvb = new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY );
  19581. var uvc = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iy + 1 ) / gridY );
  19582. var uvd = new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY );
  19583. var face = new THREE.Face3( a + offset, b + offset, d + offset );
  19584. face.normal.copy( normal );
  19585. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19586. face.materialIndex = materialIndex;
  19587. scope.faces.push( face );
  19588. scope.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  19589. face = new THREE.Face3( b + offset, c + offset, d + offset );
  19590. face.normal.copy( normal );
  19591. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone() );
  19592. face.materialIndex = materialIndex;
  19593. scope.faces.push( face );
  19594. scope.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  19595. }
  19596. }
  19597. }
  19598. this.mergeVertices();
  19599. };
  19600. THREE.BoxGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19601. /**
  19602. * @author hughes
  19603. * @author mrdoob / http://mrdoob.com/
  19604. */
  19605. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  19606. this.parameters = {
  19607. radius: radius,
  19608. segments: segments,
  19609. thetaStart: thetaStart,
  19610. thetaLength: thetaLength
  19611. };
  19612. radius = radius || 50;
  19613. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  19614. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19615. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19616. //
  19617. var elements = segments + 2;
  19618. var indices = new Uint16Array( segments * 3 );
  19619. var vertices = new Float32Array( elements * 3 );
  19620. var normals = new Float32Array( elements * 3 );
  19621. var uvs = new Float32Array( elements * 2 );
  19622. // center
  19623. normals[ 2 ] = 1;
  19624. uvs[ 0 ] = 0.5;
  19625. uvs[ 1 ] = 0.5;
  19626. var offset = 0, offset2 = 2, offset3 = 3;
  19627. for ( var i = 0; i <= segments; i ++ ) {
  19628. var segment = thetaStart + i / segments * thetaLength;
  19629. var x = radius * Math.cos( segment );
  19630. var y = radius * Math.sin( segment );
  19631. vertices[ offset3 ] = x;
  19632. vertices[ offset3 + 1 ] = y;
  19633. normals[ offset3 + 2 ] = 1;
  19634. uvs[ offset2 ] = ( x / radius + 1 ) / 2;
  19635. uvs[ offset2 + 1 ] = ( y / radius + 1 ) / 2;
  19636. offset2 += 2;
  19637. offset3 += 3;
  19638. //
  19639. indices[ offset ] = 0;
  19640. indices[ offset + 1 ] = i + 1;
  19641. indices[ offset + 2 ] = i + 2;
  19642. offset += 3;
  19643. }
  19644. THREE.IndexedGeometry2.call( this, indices, vertices, normals, uvs );
  19645. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19646. };
  19647. THREE.CircleGeometry.prototype = Object.create( THREE.IndexedGeometry2.prototype );
  19648. // DEPRECATED
  19649. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19650. console.warn( 'DEPRECATED: THREE.CubeGeometry is deprecated. Use THREE.BoxGeometry instead.' );
  19651. return new THREE.BoxGeometry( width, height, depth, widthSegments, heightSegments, depthSegments );
  19652. };
  19653. /**
  19654. * @author mrdoob / http://mrdoob.com/
  19655. */
  19656. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19657. THREE.Geometry.call( this );
  19658. this.parameters = {
  19659. radiusTop: radiusTop,
  19660. radiusBottom: radiusBottom,
  19661. height: height,
  19662. radialSegments: radialSegments,
  19663. heightSegments: heightSegments,
  19664. openEnded: openEnded
  19665. };
  19666. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19667. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19668. height = height !== undefined ? height : 100;
  19669. radialSegments = radialSegments || 8;
  19670. heightSegments = heightSegments || 1;
  19671. openEnded = openEnded !== undefined ? openEnded : false;
  19672. var heightHalf = height / 2;
  19673. var x, y, vertices = [], uvs = [];
  19674. for ( y = 0; y <= heightSegments; y ++ ) {
  19675. var verticesRow = [];
  19676. var uvsRow = [];
  19677. var v = y / heightSegments;
  19678. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19679. for ( x = 0; x <= radialSegments; x ++ ) {
  19680. var u = x / radialSegments;
  19681. var vertex = new THREE.Vector3();
  19682. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19683. vertex.y = - v * height + heightHalf;
  19684. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19685. this.vertices.push( vertex );
  19686. verticesRow.push( this.vertices.length - 1 );
  19687. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19688. }
  19689. vertices.push( verticesRow );
  19690. uvs.push( uvsRow );
  19691. }
  19692. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19693. var na, nb;
  19694. for ( x = 0; x < radialSegments; x ++ ) {
  19695. if ( radiusTop !== 0 ) {
  19696. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19697. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19698. } else {
  19699. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19700. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19701. }
  19702. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19703. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19704. for ( y = 0; y < heightSegments; y ++ ) {
  19705. var v1 = vertices[ y ][ x ];
  19706. var v2 = vertices[ y + 1 ][ x ];
  19707. var v3 = vertices[ y + 1 ][ x + 1 ];
  19708. var v4 = vertices[ y ][ x + 1 ];
  19709. var n1 = na.clone();
  19710. var n2 = na.clone();
  19711. var n3 = nb.clone();
  19712. var n4 = nb.clone();
  19713. var uv1 = uvs[ y ][ x ].clone();
  19714. var uv2 = uvs[ y + 1 ][ x ].clone();
  19715. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19716. var uv4 = uvs[ y ][ x + 1 ].clone();
  19717. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  19718. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  19719. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  19720. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  19721. }
  19722. }
  19723. // top cap
  19724. if ( openEnded === false && radiusTop > 0 ) {
  19725. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19726. for ( x = 0; x < radialSegments; x ++ ) {
  19727. var v1 = vertices[ 0 ][ x ];
  19728. var v2 = vertices[ 0 ][ x + 1 ];
  19729. var v3 = this.vertices.length - 1;
  19730. var n1 = new THREE.Vector3( 0, 1, 0 );
  19731. var n2 = new THREE.Vector3( 0, 1, 0 );
  19732. var n3 = new THREE.Vector3( 0, 1, 0 );
  19733. var uv1 = uvs[ 0 ][ x ].clone();
  19734. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19735. var uv3 = new THREE.Vector2( uv2.x, 0 );
  19736. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19737. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19738. }
  19739. }
  19740. // bottom cap
  19741. if ( openEnded === false && radiusBottom > 0 ) {
  19742. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19743. for ( x = 0; x < radialSegments; x ++ ) {
  19744. var v1 = vertices[ y ][ x + 1 ];
  19745. var v2 = vertices[ y ][ x ];
  19746. var v3 = this.vertices.length - 1;
  19747. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19748. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19749. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19750. var uv1 = uvs[ y ][ x + 1 ].clone();
  19751. var uv2 = uvs[ y ][ x ].clone();
  19752. var uv3 = new THREE.Vector2( uv2.x, 1 );
  19753. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19754. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19755. }
  19756. }
  19757. this.computeFaceNormals();
  19758. }
  19759. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19760. /**
  19761. * @author zz85 / http://www.lab4games.net/zz85/blog
  19762. *
  19763. * Creates extruded geometry from a path shape.
  19764. *
  19765. * parameters = {
  19766. *
  19767. * curveSegments: <int>, // number of points on the curves
  19768. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19769. * amount: <int>, // Depth to extrude the shape
  19770. *
  19771. * bevelEnabled: <bool>, // turn on bevel
  19772. * bevelThickness: <float>, // how deep into the original shape bevel goes
  19773. * bevelSize: <float>, // how far from shape outline is bevel
  19774. * bevelSegments: <int>, // number of bevel layers
  19775. *
  19776. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19777. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19778. *
  19779. * material: <int> // material index for front and back faces
  19780. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19781. * uvGenerator: <Object> // object that provides UV generator functions
  19782. *
  19783. * }
  19784. **/
  19785. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19786. if ( typeof( shapes ) === "undefined" ) {
  19787. shapes = [];
  19788. return;
  19789. }
  19790. THREE.Geometry.call( this );
  19791. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19792. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19793. this.addShapeList( shapes, options );
  19794. this.computeFaceNormals();
  19795. // can't really use automatic vertex normals
  19796. // as then front and back sides get smoothed too
  19797. // should do separate smoothing just for sides
  19798. //this.computeVertexNormals();
  19799. //console.log( "took", ( Date.now() - startTime ) );
  19800. };
  19801. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19802. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19803. var sl = shapes.length;
  19804. for ( var s = 0; s < sl; s ++ ) {
  19805. var shape = shapes[ s ];
  19806. this.addShape( shape, options );
  19807. }
  19808. };
  19809. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19810. var amount = options.amount !== undefined ? options.amount : 100;
  19811. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19812. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19813. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19814. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19815. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19816. var steps = options.steps !== undefined ? options.steps : 1;
  19817. var extrudePath = options.extrudePath;
  19818. var extrudePts, extrudeByPath = false;
  19819. var material = options.material;
  19820. var extrudeMaterial = options.extrudeMaterial;
  19821. // Use default WorldUVGenerator if no UV generators are specified.
  19822. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19823. var shapebb = this.shapebb;
  19824. //shapebb = shape.getBoundingBox();
  19825. var splineTube, binormal, normal, position2;
  19826. if ( extrudePath ) {
  19827. extrudePts = extrudePath.getSpacedPoints( steps );
  19828. extrudeByPath = true;
  19829. bevelEnabled = false; // bevels not supported for path extrusion
  19830. // SETUP TNB variables
  19831. // Reuse TNB from TubeGeomtry for now.
  19832. // TODO1 - have a .isClosed in spline?
  19833. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19834. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19835. binormal = new THREE.Vector3();
  19836. normal = new THREE.Vector3();
  19837. position2 = new THREE.Vector3();
  19838. }
  19839. // Safeguards if bevels are not enabled
  19840. if ( ! bevelEnabled ) {
  19841. bevelSegments = 0;
  19842. bevelThickness = 0;
  19843. bevelSize = 0;
  19844. }
  19845. // Variables initalization
  19846. var ahole, h, hl; // looping of holes
  19847. var scope = this;
  19848. var bevelPoints = [];
  19849. var shapesOffset = this.vertices.length;
  19850. var shapePoints = shape.extractPoints( curveSegments );
  19851. var vertices = shapePoints.shape;
  19852. var holes = shapePoints.holes;
  19853. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19854. if ( reverse ) {
  19855. vertices = vertices.reverse();
  19856. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19857. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19858. ahole = holes[ h ];
  19859. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19860. holes[ h ] = ahole.reverse();
  19861. }
  19862. }
  19863. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19864. }
  19865. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19866. /* Vertices */
  19867. var contour = vertices; // vertices has all points but contour has only points of circumference
  19868. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19869. ahole = holes[ h ];
  19870. vertices = vertices.concat( ahole );
  19871. }
  19872. function scalePt2 ( pt, vec, size ) {
  19873. if ( !vec ) console.log( "die" );
  19874. return vec.clone().multiplyScalar( size ).add( pt );
  19875. }
  19876. var b, bs, t, z,
  19877. vert, vlen = vertices.length,
  19878. face, flen = faces.length,
  19879. cont, clen = contour.length;
  19880. // Find directions for point movement
  19881. var RAD_TO_DEGREES = 180 / Math.PI;
  19882. function getBevelVec( inPt, inPrev, inNext ) {
  19883. var EPSILON = 0.0000000001;
  19884. var sign = THREE.Math.sign;
  19885. // computes for inPt the corresponding point inPt' on a new contour
  19886. // shiftet by 1 unit (length of normalized vector) to the left
  19887. // if we walk along contour clockwise, this new contour is outside the old one
  19888. //
  19889. // inPt' is the intersection of the two lines parallel to the two
  19890. // adjacent edges of inPt at a distance of 1 unit on the left side.
  19891. var v_trans_x, v_trans_y, shrink_by = 1; // resulting translation vector for inPt
  19892. // good reading for geometry algorithms (here: line-line intersection)
  19893. // http://geomalgorithms.com/a05-_intersect-1.html
  19894. var v_prev_x = inPt.x - inPrev.x, v_prev_y = inPt.y - inPrev.y;
  19895. var v_next_x = inNext.x - inPt.x, v_next_y = inNext.y - inPt.y;
  19896. var v_prev_lensq = ( v_prev_x * v_prev_x + v_prev_y * v_prev_y );
  19897. // check for colinear edges
  19898. var colinear0 = ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19899. if ( Math.abs( colinear0 ) > EPSILON ) { // not colinear
  19900. // length of vectors for normalizing
  19901. var v_prev_len = Math.sqrt( v_prev_lensq );
  19902. var v_next_len = Math.sqrt( v_next_x * v_next_x + v_next_y * v_next_y );
  19903. // shift adjacent points by unit vectors to the left
  19904. var ptPrevShift_x = ( inPrev.x - v_prev_y / v_prev_len );
  19905. var ptPrevShift_y = ( inPrev.y + v_prev_x / v_prev_len );
  19906. var ptNextShift_x = ( inNext.x - v_next_y / v_next_len );
  19907. var ptNextShift_y = ( inNext.y + v_next_x / v_next_len );
  19908. // scaling factor for v_prev to intersection point
  19909. var sf = ( ( ptNextShift_x - ptPrevShift_x ) * v_next_y -
  19910. ( ptNextShift_y - ptPrevShift_y ) * v_next_x ) /
  19911. ( v_prev_x * v_next_y - v_prev_y * v_next_x );
  19912. // vector from inPt to intersection point
  19913. v_trans_x = ( ptPrevShift_x + v_prev_x * sf - inPt.x );
  19914. v_trans_y = ( ptPrevShift_y + v_prev_y * sf - inPt.y );
  19915. // Don't normalize!, otherwise sharp corners become ugly
  19916. // but prevent crazy spikes
  19917. var v_trans_lensq = ( v_trans_x * v_trans_x + v_trans_y * v_trans_y )
  19918. if ( v_trans_lensq <= 2 ) {
  19919. return new THREE.Vector2( v_trans_x, v_trans_y );
  19920. } else {
  19921. shrink_by = Math.sqrt( v_trans_lensq / 2 );
  19922. }
  19923. } else { // handle special case of colinear edges
  19924. var direction_eq = false; // assumes: opposite
  19925. if ( v_prev_x > EPSILON ) {
  19926. if ( v_next_x > EPSILON ) { direction_eq = true; }
  19927. } else {
  19928. if ( v_prev_x < -EPSILON ) {
  19929. if ( v_next_x < -EPSILON ) { direction_eq = true; }
  19930. } else {
  19931. if ( sign(v_prev_y) == sign(v_next_y) ) { direction_eq = true; }
  19932. }
  19933. }
  19934. if ( direction_eq ) {
  19935. // console.log("Warning: lines are a straight sequence");
  19936. v_trans_x = -v_prev_y;
  19937. v_trans_y = v_prev_x;
  19938. shrink_by = Math.sqrt( v_prev_lensq );
  19939. } else {
  19940. // console.log("Warning: lines are a straight spike");
  19941. v_trans_x = v_prev_x;
  19942. v_trans_y = v_prev_y;
  19943. shrink_by = Math.sqrt( v_prev_lensq / 2 );
  19944. }
  19945. }
  19946. return new THREE.Vector2( v_trans_x / shrink_by, v_trans_y / shrink_by );
  19947. }
  19948. var contourMovements = [];
  19949. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19950. if ( j === il ) j = 0;
  19951. if ( k === il ) k = 0;
  19952. // (j)---(i)---(k)
  19953. // console.log('i,j,k', i, j , k)
  19954. var pt_i = contour[ i ];
  19955. var pt_j = contour[ j ];
  19956. var pt_k = contour[ k ];
  19957. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19958. }
  19959. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19960. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19961. ahole = holes[ h ];
  19962. oneHoleMovements = [];
  19963. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19964. if ( j === il ) j = 0;
  19965. if ( k === il ) k = 0;
  19966. // (j)---(i)---(k)
  19967. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19968. }
  19969. holesMovements.push( oneHoleMovements );
  19970. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19971. }
  19972. // Loop bevelSegments, 1 for the front, 1 for the back
  19973. for ( b = 0; b < bevelSegments; b ++ ) {
  19974. //for ( b = bevelSegments; b > 0; b -- ) {
  19975. t = b / bevelSegments;
  19976. z = bevelThickness * ( 1 - t );
  19977. //z = bevelThickness * t;
  19978. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19979. //bs = bevelSize * t ; // linear
  19980. // contract shape
  19981. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19982. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19983. v( vert.x, vert.y, - z );
  19984. }
  19985. // expand holes
  19986. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19987. ahole = holes[ h ];
  19988. oneHoleMovements = holesMovements[ h ];
  19989. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19990. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19991. v( vert.x, vert.y, -z );
  19992. }
  19993. }
  19994. }
  19995. bs = bevelSize;
  19996. // Back facing vertices
  19997. for ( i = 0; i < vlen; i ++ ) {
  19998. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19999. if ( !extrudeByPath ) {
  20000. v( vert.x, vert.y, 0 );
  20001. } else {
  20002. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  20003. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  20004. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  20005. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  20006. v( position2.x, position2.y, position2.z );
  20007. }
  20008. }
  20009. // Add stepped vertices...
  20010. // Including front facing vertices
  20011. var s;
  20012. for ( s = 1; s <= steps; s ++ ) {
  20013. for ( i = 0; i < vlen; i ++ ) {
  20014. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  20015. if ( !extrudeByPath ) {
  20016. v( vert.x, vert.y, amount / steps * s );
  20017. } else {
  20018. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  20019. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  20020. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  20021. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  20022. v( position2.x, position2.y, position2.z );
  20023. }
  20024. }
  20025. }
  20026. // Add bevel segments planes
  20027. //for ( b = 1; b <= bevelSegments; b ++ ) {
  20028. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  20029. t = b / bevelSegments;
  20030. z = bevelThickness * ( 1 - t );
  20031. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  20032. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  20033. // contract shape
  20034. for ( i = 0, il = contour.length; i < il; i ++ ) {
  20035. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  20036. v( vert.x, vert.y, amount + z );
  20037. }
  20038. // expand holes
  20039. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20040. ahole = holes[ h ];
  20041. oneHoleMovements = holesMovements[ h ];
  20042. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  20043. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  20044. if ( !extrudeByPath ) {
  20045. v( vert.x, vert.y, amount + z );
  20046. } else {
  20047. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  20048. }
  20049. }
  20050. }
  20051. }
  20052. /* Faces */
  20053. // Top and bottom faces
  20054. buildLidFaces();
  20055. // Sides faces
  20056. buildSideFaces();
  20057. ///// Internal functions
  20058. function buildLidFaces() {
  20059. if ( bevelEnabled ) {
  20060. var layer = 0 ; // steps + 1
  20061. var offset = vlen * layer;
  20062. // Bottom faces
  20063. for ( i = 0; i < flen; i ++ ) {
  20064. face = faces[ i ];
  20065. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  20066. }
  20067. layer = steps + bevelSegments * 2;
  20068. offset = vlen * layer;
  20069. // Top faces
  20070. for ( i = 0; i < flen; i ++ ) {
  20071. face = faces[ i ];
  20072. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  20073. }
  20074. } else {
  20075. // Bottom faces
  20076. for ( i = 0; i < flen; i++ ) {
  20077. face = faces[ i ];
  20078. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  20079. }
  20080. // Top faces
  20081. for ( i = 0; i < flen; i ++ ) {
  20082. face = faces[ i ];
  20083. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  20084. }
  20085. }
  20086. }
  20087. // Create faces for the z-sides of the shape
  20088. function buildSideFaces() {
  20089. var layeroffset = 0;
  20090. sidewalls( contour, layeroffset );
  20091. layeroffset += contour.length;
  20092. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  20093. ahole = holes[ h ];
  20094. sidewalls( ahole, layeroffset );
  20095. //, true
  20096. layeroffset += ahole.length;
  20097. }
  20098. }
  20099. function sidewalls( contour, layeroffset ) {
  20100. var j, k;
  20101. i = contour.length;
  20102. while ( --i >= 0 ) {
  20103. j = i;
  20104. k = i - 1;
  20105. if ( k < 0 ) k = contour.length - 1;
  20106. //console.log('b', i,j, i-1, k,vertices.length);
  20107. var s = 0, sl = steps + bevelSegments * 2;
  20108. for ( s = 0; s < sl; s ++ ) {
  20109. var slen1 = vlen * s;
  20110. var slen2 = vlen * ( s + 1 );
  20111. var a = layeroffset + j + slen1,
  20112. b = layeroffset + k + slen1,
  20113. c = layeroffset + k + slen2,
  20114. d = layeroffset + j + slen2;
  20115. f4( a, b, c, d, contour, s, sl, j, k );
  20116. }
  20117. }
  20118. }
  20119. function v( x, y, z ) {
  20120. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  20121. }
  20122. function f3( a, b, c, isBottom ) {
  20123. a += shapesOffset;
  20124. b += shapesOffset;
  20125. c += shapesOffset;
  20126. // normal, color, material
  20127. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  20128. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  20129. scope.faceVertexUvs[ 0 ].push( uvs );
  20130. }
  20131. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  20132. a += shapesOffset;
  20133. b += shapesOffset;
  20134. c += shapesOffset;
  20135. d += shapesOffset;
  20136. scope.faces.push( new THREE.Face3( a, b, d, null, null, extrudeMaterial ) );
  20137. scope.faces.push( new THREE.Face3( b, c, d, null, null, extrudeMaterial ) );
  20138. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  20139. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  20140. scope.faceVertexUvs[ 0 ].push( [ uvs[ 0 ], uvs[ 1 ], uvs[ 3 ] ] );
  20141. scope.faceVertexUvs[ 0 ].push( [ uvs[ 1 ], uvs[ 2 ], uvs[ 3 ] ] );
  20142. }
  20143. };
  20144. THREE.ExtrudeGeometry.WorldUVGenerator = {
  20145. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  20146. var ax = geometry.vertices[ indexA ].x,
  20147. ay = geometry.vertices[ indexA ].y,
  20148. bx = geometry.vertices[ indexB ].x,
  20149. by = geometry.vertices[ indexB ].y,
  20150. cx = geometry.vertices[ indexC ].x,
  20151. cy = geometry.vertices[ indexC ].y;
  20152. return [
  20153. new THREE.Vector2( ax, ay ),
  20154. new THREE.Vector2( bx, by ),
  20155. new THREE.Vector2( cx, cy )
  20156. ];
  20157. },
  20158. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  20159. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  20160. },
  20161. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  20162. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  20163. contourIndex1, contourIndex2 ) {
  20164. var ax = geometry.vertices[ indexA ].x,
  20165. ay = geometry.vertices[ indexA ].y,
  20166. az = geometry.vertices[ indexA ].z,
  20167. bx = geometry.vertices[ indexB ].x,
  20168. by = geometry.vertices[ indexB ].y,
  20169. bz = geometry.vertices[ indexB ].z,
  20170. cx = geometry.vertices[ indexC ].x,
  20171. cy = geometry.vertices[ indexC ].y,
  20172. cz = geometry.vertices[ indexC ].z,
  20173. dx = geometry.vertices[ indexD ].x,
  20174. dy = geometry.vertices[ indexD ].y,
  20175. dz = geometry.vertices[ indexD ].z;
  20176. if ( Math.abs( ay - by ) < 0.01 ) {
  20177. return [
  20178. new THREE.Vector2( ax, 1 - az ),
  20179. new THREE.Vector2( bx, 1 - bz ),
  20180. new THREE.Vector2( cx, 1 - cz ),
  20181. new THREE.Vector2( dx, 1 - dz )
  20182. ];
  20183. } else {
  20184. return [
  20185. new THREE.Vector2( ay, 1 - az ),
  20186. new THREE.Vector2( by, 1 - bz ),
  20187. new THREE.Vector2( cy, 1 - cz ),
  20188. new THREE.Vector2( dy, 1 - dz )
  20189. ];
  20190. }
  20191. }
  20192. };
  20193. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  20194. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  20195. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  20196. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  20197. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  20198. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  20199. /**
  20200. * @author jonobr1 / http://jonobr1.com
  20201. *
  20202. * Creates a one-sided polygonal geometry from a path shape. Similar to
  20203. * ExtrudeGeometry.
  20204. *
  20205. * parameters = {
  20206. *
  20207. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  20208. *
  20209. * material: <int> // material index for front and back faces
  20210. * uvGenerator: <Object> // object that provides UV generator functions
  20211. *
  20212. * }
  20213. **/
  20214. THREE.ShapeGeometry = function ( shapes, options ) {
  20215. THREE.Geometry.call( this );
  20216. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  20217. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  20218. this.addShapeList( shapes, options );
  20219. this.computeFaceNormals();
  20220. };
  20221. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20222. /**
  20223. * Add an array of shapes to THREE.ShapeGeometry.
  20224. */
  20225. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  20226. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  20227. this.addShape( shapes[ i ], options );
  20228. }
  20229. return this;
  20230. };
  20231. /**
  20232. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  20233. */
  20234. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  20235. if ( options === undefined ) options = {};
  20236. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  20237. var material = options.material;
  20238. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  20239. var shapebb = this.shapebb;
  20240. //
  20241. var i, l, hole, s;
  20242. var shapesOffset = this.vertices.length;
  20243. var shapePoints = shape.extractPoints( curveSegments );
  20244. var vertices = shapePoints.shape;
  20245. var holes = shapePoints.holes;
  20246. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  20247. if ( reverse ) {
  20248. vertices = vertices.reverse();
  20249. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  20250. for ( i = 0, l = holes.length; i < l; i++ ) {
  20251. hole = holes[ i ];
  20252. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  20253. holes[ i ] = hole.reverse();
  20254. }
  20255. }
  20256. reverse = false;
  20257. }
  20258. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  20259. // Vertices
  20260. var contour = vertices;
  20261. for ( i = 0, l = holes.length; i < l; i++ ) {
  20262. hole = holes[ i ];
  20263. vertices = vertices.concat( hole );
  20264. }
  20265. //
  20266. var vert, vlen = vertices.length;
  20267. var face, flen = faces.length;
  20268. var cont, clen = contour.length;
  20269. for ( i = 0; i < vlen; i++ ) {
  20270. vert = vertices[ i ];
  20271. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  20272. }
  20273. for ( i = 0; i < flen; i++ ) {
  20274. face = faces[ i ];
  20275. var a = face[ 0 ] + shapesOffset;
  20276. var b = face[ 1 ] + shapesOffset;
  20277. var c = face[ 2 ] + shapesOffset;
  20278. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  20279. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  20280. }
  20281. };
  20282. /**
  20283. * @author astrodud / http://astrodud.isgreat.org/
  20284. * @author zz85 / https://github.com/zz85
  20285. * @author bhouston / http://exocortex.com
  20286. */
  20287. // points - to create a closed torus, one must use a set of points
  20288. // like so: [ a, b, c, d, a ], see first is the same as last.
  20289. // segments - the number of circumference segments to create
  20290. // phiStart - the starting radian
  20291. // phiLength - the radian (0 to 2*PI) range of the lathed section
  20292. // 2*pi is a closed lathe, less than 2PI is a portion.
  20293. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  20294. THREE.Geometry.call( this );
  20295. segments = segments || 12;
  20296. phiStart = phiStart || 0;
  20297. phiLength = phiLength || 2 * Math.PI;
  20298. var inversePointLength = 1.0 / ( points.length - 1 );
  20299. var inverseSegments = 1.0 / segments;
  20300. for ( var i = 0, il = segments; i <= il; i ++ ) {
  20301. var phi = phiStart + i * inverseSegments * phiLength;
  20302. var c = Math.cos( phi ),
  20303. s = Math.sin( phi );
  20304. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  20305. var pt = points[ j ];
  20306. var vertex = new THREE.Vector3();
  20307. vertex.x = c * pt.x - s * pt.y;
  20308. vertex.y = s * pt.x + c * pt.y;
  20309. vertex.z = pt.z;
  20310. this.vertices.push( vertex );
  20311. }
  20312. }
  20313. var np = points.length;
  20314. for ( var i = 0, il = segments; i < il; i ++ ) {
  20315. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  20316. var base = j + np * i;
  20317. var a = base;
  20318. var b = base + np;
  20319. var c = base + 1 + np;
  20320. var d = base + 1;
  20321. var u0 = i * inverseSegments;
  20322. var v0 = j * inversePointLength;
  20323. var u1 = u0 + inverseSegments;
  20324. var v1 = v0 + inversePointLength;
  20325. this.faces.push( new THREE.Face3( a, b, d ) );
  20326. this.faceVertexUvs[ 0 ].push( [
  20327. new THREE.Vector2( u0, v0 ),
  20328. new THREE.Vector2( u1, v0 ),
  20329. new THREE.Vector2( u0, v1 )
  20330. ] );
  20331. this.faces.push( new THREE.Face3( b, c, d ) );
  20332. this.faceVertexUvs[ 0 ].push( [
  20333. new THREE.Vector2( u1, v0 ),
  20334. new THREE.Vector2( u1, v1 ),
  20335. new THREE.Vector2( u0, v1 )
  20336. ] );
  20337. }
  20338. }
  20339. this.mergeVertices();
  20340. this.computeFaceNormals();
  20341. this.computeVertexNormals();
  20342. };
  20343. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20344. /**
  20345. * @author mrdoob / http://mrdoob.com/
  20346. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  20347. */
  20348. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  20349. this.parameters = {
  20350. width: width,
  20351. height: height,
  20352. widthSegments: widthSegments,
  20353. heightSegments: heightSegments
  20354. };
  20355. var width_half = width / 2;
  20356. var height_half = height / 2;
  20357. var gridX = widthSegments || 1;
  20358. var gridY = heightSegments || 1;
  20359. var gridX1 = gridX + 1;
  20360. var gridY1 = gridY + 1;
  20361. var segment_width = width / gridX;
  20362. var segment_height = height / gridY;
  20363. var vertices = new Float32Array( gridX1 * gridY1 * 3 );
  20364. var normals = new Float32Array( gridX1 * gridY1 * 3 );
  20365. var uvs = new Float32Array( gridX1 * gridY1 * 2 );
  20366. var offset = 0;
  20367. var offset2 = 0;
  20368. for ( var iy = 0; iy < gridY1; iy ++ ) {
  20369. var y = iy * segment_height - height_half;
  20370. for ( var ix = 0; ix < gridX1; ix ++ ) {
  20371. var x = ix * segment_width - width_half;
  20372. vertices[ offset ] = x;
  20373. vertices[ offset + 1 ] = - y;
  20374. normals[ offset + 2 ] = 1;
  20375. uvs[ offset2 ] = ix / gridX;
  20376. uvs[ offset2 + 1 ] = 1 - ( iy / gridY );
  20377. offset += 3;
  20378. offset2 += 2;
  20379. }
  20380. }
  20381. offset = 0;
  20382. var indices = new ( vertices.length > 65535 ? Uint32Array : Uint16Array )( gridX * gridY * 6 );
  20383. for ( var iy = 0; iy < gridY; iy ++ ) {
  20384. for ( var ix = 0; ix < gridX; ix ++ ) {
  20385. var a = ix + gridX1 * iy;
  20386. var b = ix + gridX1 * ( iy + 1 );
  20387. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  20388. var d = ( ix + 1 ) + gridX1 * iy;
  20389. indices[ offset ] = a;
  20390. indices[ offset + 1 ] = b;
  20391. indices[ offset + 2 ] = d;
  20392. indices[ offset + 3 ] = b;
  20393. indices[ offset + 4 ] = c;
  20394. indices[ offset + 5 ] = d;
  20395. offset += 6;
  20396. }
  20397. }
  20398. THREE.IndexedGeometry2.call( this, indices, vertices, normals, uvs );
  20399. };
  20400. THREE.PlaneGeometry.prototype = Object.create( THREE.IndexedGeometry2.prototype );
  20401. /**
  20402. * @author Kaleb Murphy
  20403. */
  20404. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  20405. THREE.Geometry.call( this );
  20406. innerRadius = innerRadius || 0;
  20407. outerRadius = outerRadius || 50;
  20408. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20409. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  20410. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  20411. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  20412. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  20413. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  20414. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20415. var vertex = new THREE.Vector3();
  20416. var segment = thetaStart + o / thetaSegments * thetaLength;
  20417. vertex.x = radius * Math.cos( segment );
  20418. vertex.y = radius * Math.sin( segment );
  20419. this.vertices.push( vertex );
  20420. uvs.push( new THREE.Vector2( ( vertex.x / outerRadius + 1 ) / 2, ( vertex.y / outerRadius + 1 ) / 2 ) );
  20421. }
  20422. radius += radiusStep;
  20423. }
  20424. var n = new THREE.Vector3( 0, 0, 1 );
  20425. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  20426. var thetaSegment = i * thetaSegments;
  20427. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  20428. var segment = o + thetaSegment;
  20429. var v1 = segment + i;
  20430. var v2 = segment + thetaSegments + i;
  20431. var v3 = segment + thetaSegments + 1 + i;
  20432. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  20433. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  20434. v1 = segment + i;
  20435. v2 = segment + thetaSegments + 1 + i;
  20436. v3 = segment + 1 + i;
  20437. this.faces.push( new THREE.Face3( v1, v2, v3, [ n.clone(), n.clone(), n.clone() ] ) );
  20438. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ].clone(), uvs[ v2 ].clone(), uvs[ v3 ].clone() ]);
  20439. }
  20440. }
  20441. this.computeFaceNormals();
  20442. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20443. };
  20444. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20445. /**
  20446. * @author mrdoob / http://mrdoob.com/
  20447. */
  20448. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  20449. THREE.Geometry.call( this );
  20450. this.parameters = {
  20451. radius: radius,
  20452. widthSegments: widthSegments,
  20453. heightSegments: heightSegments,
  20454. phiStart: phiStart,
  20455. phiLength: phiLength,
  20456. thetaStart: thetaStart,
  20457. thetaLength: thetaLength
  20458. };
  20459. radius = radius || 50;
  20460. widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  20461. heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  20462. phiStart = phiStart !== undefined ? phiStart : 0;
  20463. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  20464. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  20465. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  20466. var x, y, vertices = [], uvs = [];
  20467. for ( y = 0; y <= heightSegments; y ++ ) {
  20468. var verticesRow = [];
  20469. var uvsRow = [];
  20470. for ( x = 0; x <= widthSegments; x ++ ) {
  20471. var u = x / widthSegments;
  20472. var v = y / heightSegments;
  20473. var vertex = new THREE.Vector3();
  20474. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20475. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  20476. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  20477. this.vertices.push( vertex );
  20478. verticesRow.push( this.vertices.length - 1 );
  20479. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  20480. }
  20481. vertices.push( verticesRow );
  20482. uvs.push( uvsRow );
  20483. }
  20484. for ( y = 0; y < heightSegments; y ++ ) {
  20485. for ( x = 0; x < widthSegments; x ++ ) {
  20486. var v1 = vertices[ y ][ x + 1 ];
  20487. var v2 = vertices[ y ][ x ];
  20488. var v3 = vertices[ y + 1 ][ x ];
  20489. var v4 = vertices[ y + 1 ][ x + 1 ];
  20490. var n1 = this.vertices[ v1 ].clone().normalize();
  20491. var n2 = this.vertices[ v2 ].clone().normalize();
  20492. var n3 = this.vertices[ v3 ].clone().normalize();
  20493. var n4 = this.vertices[ v4 ].clone().normalize();
  20494. var uv1 = uvs[ y ][ x + 1 ].clone();
  20495. var uv2 = uvs[ y ][ x ].clone();
  20496. var uv3 = uvs[ y + 1 ][ x ].clone();
  20497. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  20498. if ( Math.abs( this.vertices[ v1 ].y ) === radius ) {
  20499. uv1.x = ( uv1.x + uv2.x ) / 2;
  20500. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  20501. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  20502. } else if ( Math.abs( this.vertices[ v3 ].y ) === radius ) {
  20503. uv3.x = ( uv3.x + uv4.x ) / 2;
  20504. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  20505. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  20506. } else {
  20507. this.faces.push( new THREE.Face3( v1, v2, v4, [ n1, n2, n4 ] ) );
  20508. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv4 ] );
  20509. this.faces.push( new THREE.Face3( v2, v3, v4, [ n2.clone(), n3, n4.clone() ] ) );
  20510. this.faceVertexUvs[ 0 ].push( [ uv2.clone(), uv3, uv4.clone() ] );
  20511. }
  20512. }
  20513. }
  20514. this.computeFaceNormals();
  20515. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20516. };
  20517. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20518. /**
  20519. * @author zz85 / http://www.lab4games.net/zz85/blog
  20520. * @author alteredq / http://alteredqualia.com/
  20521. *
  20522. * For creating 3D text geometry in three.js
  20523. *
  20524. * Text = 3D Text
  20525. *
  20526. * parameters = {
  20527. * size: <float>, // size of the text
  20528. * height: <float>, // thickness to extrude text
  20529. * curveSegments: <int>, // number of points on the curves
  20530. *
  20531. * font: <string>, // font name
  20532. * weight: <string>, // font weight (normal, bold)
  20533. * style: <string>, // font style (normal, italics)
  20534. *
  20535. * bevelEnabled: <bool>, // turn on bevel
  20536. * bevelThickness: <float>, // how deep into text bevel goes
  20537. * bevelSize: <float>, // how far from text outline is bevel
  20538. * }
  20539. *
  20540. */
  20541. /* Usage Examples
  20542. // TextGeometry wrapper
  20543. var text3d = new TextGeometry( text, options );
  20544. // Complete manner
  20545. var textShapes = THREE.FontUtils.generateShapes( text, options );
  20546. var text3d = new ExtrudeGeometry( textShapes, options );
  20547. */
  20548. THREE.TextGeometry = function ( text, parameters ) {
  20549. parameters = parameters || {};
  20550. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  20551. // translate parameters to ExtrudeGeometry API
  20552. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  20553. // defaults
  20554. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  20555. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  20556. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  20557. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  20558. };
  20559. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  20560. /**
  20561. * @author oosmoxiecode
  20562. * @author mrdoob / http://mrdoob.com/
  20563. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  20564. */
  20565. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  20566. THREE.Geometry.call( this );
  20567. this.parameters = {
  20568. radius: radius,
  20569. tube: tube,
  20570. radialSegments: radialSegments,
  20571. tubularSegments: tubularSegments,
  20572. arc: arc
  20573. };
  20574. radius = radius || 100;
  20575. tube = tube || 40;
  20576. radialSegments = radialSegments || 8;
  20577. tubularSegments = tubularSegments || 6;
  20578. arc = arc || Math.PI * 2;
  20579. var center = new THREE.Vector3(), uvs = [], normals = [];
  20580. for ( var j = 0; j <= radialSegments; j ++ ) {
  20581. for ( var i = 0; i <= tubularSegments; i ++ ) {
  20582. var u = i / tubularSegments * arc;
  20583. var v = j / radialSegments * Math.PI * 2;
  20584. center.x = radius * Math.cos( u );
  20585. center.y = radius * Math.sin( u );
  20586. var vertex = new THREE.Vector3();
  20587. vertex.x = ( radius + tube * Math.cos( v ) ) * Math.cos( u );
  20588. vertex.y = ( radius + tube * Math.cos( v ) ) * Math.sin( u );
  20589. vertex.z = tube * Math.sin( v );
  20590. this.vertices.push( vertex );
  20591. uvs.push( new THREE.Vector2( i / tubularSegments, j / radialSegments ) );
  20592. normals.push( vertex.clone().sub( center ).normalize() );
  20593. }
  20594. }
  20595. for ( var j = 1; j <= radialSegments; j ++ ) {
  20596. for ( var i = 1; i <= tubularSegments; i ++ ) {
  20597. var a = ( tubularSegments + 1 ) * j + i - 1;
  20598. var b = ( tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  20599. var c = ( tubularSegments + 1 ) * ( j - 1 ) + i;
  20600. var d = ( tubularSegments + 1 ) * j + i;
  20601. var face = new THREE.Face3( a, b, d, [ normals[ a ].clone(), normals[ b ].clone(), normals[ d ].clone() ] );
  20602. this.faces.push( face );
  20603. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ d ].clone() ] );
  20604. face = new THREE.Face3( b, c, d, [ normals[ b ].clone(), normals[ c ].clone(), normals[ d ].clone() ] );
  20605. this.faces.push( face );
  20606. this.faceVertexUvs[ 0 ].push( [ uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20607. }
  20608. }
  20609. this.computeFaceNormals();
  20610. };
  20611. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20612. /**
  20613. * @author oosmoxiecode
  20614. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20615. */
  20616. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20617. THREE.Geometry.call( this );
  20618. this.parameters = {
  20619. radius: radius,
  20620. tube: tube,
  20621. radialSegments: radialSegments,
  20622. tubularSegments: tubularSegments,
  20623. p: p,
  20624. q: q,
  20625. heightScale: heightScale
  20626. };
  20627. radius = radius || 100;
  20628. tube = tube || 40;
  20629. radialSegments = radialSegments || 64;
  20630. tubularSegments = tubularSegments || 8;
  20631. p = p || 2;
  20632. q = q || 3;
  20633. heightScale = heightScale || 1;
  20634. var grid = new Array( radialSegments );
  20635. var tang = new THREE.Vector3();
  20636. var n = new THREE.Vector3();
  20637. var bitan = new THREE.Vector3();
  20638. for ( var i = 0; i < radialSegments; ++ i ) {
  20639. grid[ i ] = new Array( tubularSegments );
  20640. var u = i / radialSegments * 2 * p * Math.PI;
  20641. var p1 = getPos( u, q, p, radius, heightScale );
  20642. var p2 = getPos( u + 0.01, q, p, radius, heightScale );
  20643. tang.subVectors( p2, p1 );
  20644. n.addVectors( p2, p1 );
  20645. bitan.crossVectors( tang, n );
  20646. n.crossVectors( bitan, tang );
  20647. bitan.normalize();
  20648. n.normalize();
  20649. for ( var j = 0; j < tubularSegments; ++ j ) {
  20650. var v = j / tubularSegments * 2 * Math.PI;
  20651. var cx = - tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20652. var cy = tube * Math.sin( v );
  20653. var pos = new THREE.Vector3();
  20654. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20655. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20656. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20657. grid[ i ][ j ] = this.vertices.push( pos ) - 1;
  20658. }
  20659. }
  20660. for ( var i = 0; i < radialSegments; ++ i ) {
  20661. for ( var j = 0; j < tubularSegments; ++ j ) {
  20662. var ip = ( i + 1 ) % radialSegments;
  20663. var jp = ( j + 1 ) % tubularSegments;
  20664. var a = grid[ i ][ j ];
  20665. var b = grid[ ip ][ j ];
  20666. var c = grid[ ip ][ jp ];
  20667. var d = grid[ i ][ jp ];
  20668. var uva = new THREE.Vector2( i / radialSegments, j / tubularSegments );
  20669. var uvb = new THREE.Vector2( ( i + 1 ) / radialSegments, j / tubularSegments );
  20670. var uvc = new THREE.Vector2( ( i + 1 ) / radialSegments, ( j + 1 ) / tubularSegments );
  20671. var uvd = new THREE.Vector2( i / radialSegments, ( j + 1 ) / tubularSegments );
  20672. this.faces.push( new THREE.Face3( a, b, d ) );
  20673. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20674. this.faces.push( new THREE.Face3( b, c, d ) );
  20675. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20676. }
  20677. }
  20678. this.computeFaceNormals();
  20679. this.computeVertexNormals();
  20680. function getPos( u, in_q, in_p, radius, heightScale ) {
  20681. var cu = Math.cos( u );
  20682. var su = Math.sin( u );
  20683. var quOverP = in_q / in_p * u;
  20684. var cs = Math.cos( quOverP );
  20685. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20686. var ty = radius * ( 2 + cs ) * su * 0.5;
  20687. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20688. return new THREE.Vector3( tx, ty, tz );
  20689. }
  20690. };
  20691. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20692. /**
  20693. * @author WestLangley / https://github.com/WestLangley
  20694. * @author zz85 / https://github.com/zz85
  20695. * @author miningold / https://github.com/miningold
  20696. *
  20697. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20698. *
  20699. * Creates a tube which extrudes along a 3d spline
  20700. *
  20701. * Uses parallel transport frames as described in
  20702. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20703. */
  20704. THREE.TubeGeometry = function ( path, segments, radius, radialSegments, closed ) {
  20705. THREE.Geometry.call( this );
  20706. this.parameters = {
  20707. path: path,
  20708. segments: segments,
  20709. radius: radius,
  20710. radialSegments: radialSegments,
  20711. closed: closed
  20712. };
  20713. segments = segments || 64;
  20714. radius = radius || 1;
  20715. radialSegments = radialSegments || 8;
  20716. closed = closed || false;
  20717. var grid = [];
  20718. var scope = this,
  20719. tangent,
  20720. normal,
  20721. binormal,
  20722. numpoints = segments + 1,
  20723. x, y, z,
  20724. tx, ty, tz,
  20725. u, v,
  20726. cx, cy,
  20727. pos, pos2 = new THREE.Vector3(),
  20728. i, j,
  20729. ip, jp,
  20730. a, b, c, d,
  20731. uva, uvb, uvc, uvd;
  20732. var frames = new THREE.TubeGeometry.FrenetFrames( path, segments, closed ),
  20733. tangents = frames.tangents,
  20734. normals = frames.normals,
  20735. binormals = frames.binormals;
  20736. // proxy internals
  20737. this.tangents = tangents;
  20738. this.normals = normals;
  20739. this.binormals = binormals;
  20740. function vert( x, y, z ) {
  20741. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20742. }
  20743. // consruct the grid
  20744. for ( i = 0; i < numpoints; i++ ) {
  20745. grid[ i ] = [];
  20746. u = i / ( numpoints - 1 );
  20747. pos = path.getPointAt( u );
  20748. tangent = tangents[ i ];
  20749. normal = normals[ i ];
  20750. binormal = binormals[ i ];
  20751. for ( j = 0; j < radialSegments; j++ ) {
  20752. v = j / radialSegments * 2 * Math.PI;
  20753. cx = -radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20754. cy = radius * Math.sin( v );
  20755. pos2.copy( pos );
  20756. pos2.x += cx * normal.x + cy * binormal.x;
  20757. pos2.y += cx * normal.y + cy * binormal.y;
  20758. pos2.z += cx * normal.z + cy * binormal.z;
  20759. grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20760. }
  20761. }
  20762. // construct the mesh
  20763. for ( i = 0; i < segments; i++ ) {
  20764. for ( j = 0; j < radialSegments; j++ ) {
  20765. ip = ( closed ) ? (i + 1) % segments : i + 1;
  20766. jp = (j + 1) % radialSegments;
  20767. a = grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20768. b = grid[ ip ][ j ];
  20769. c = grid[ ip ][ jp ];
  20770. d = grid[ i ][ jp ];
  20771. uva = new THREE.Vector2( i / segments, j / radialSegments );
  20772. uvb = new THREE.Vector2( ( i + 1 ) / segments, j / radialSegments );
  20773. uvc = new THREE.Vector2( ( i + 1 ) / segments, ( j + 1 ) / radialSegments );
  20774. uvd = new THREE.Vector2( i / segments, ( j + 1 ) / radialSegments );
  20775. this.faces.push( new THREE.Face3( a, b, d ) );
  20776. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvd ] );
  20777. this.faces.push( new THREE.Face3( b, c, d ) );
  20778. this.faceVertexUvs[ 0 ].push( [ uvb.clone(), uvc, uvd.clone() ] );
  20779. }
  20780. }
  20781. this.computeFaceNormals();
  20782. this.computeVertexNormals();
  20783. };
  20784. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20785. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20786. THREE.TubeGeometry.FrenetFrames = function ( path, segments, closed ) {
  20787. var tangent = new THREE.Vector3(),
  20788. normal = new THREE.Vector3(),
  20789. binormal = new THREE.Vector3(),
  20790. tangents = [],
  20791. normals = [],
  20792. binormals = [],
  20793. vec = new THREE.Vector3(),
  20794. mat = new THREE.Matrix4(),
  20795. numpoints = segments + 1,
  20796. theta,
  20797. epsilon = 0.0001,
  20798. smallest,
  20799. tx, ty, tz,
  20800. i, u, v;
  20801. // expose internals
  20802. this.tangents = tangents;
  20803. this.normals = normals;
  20804. this.binormals = binormals;
  20805. // compute the tangent vectors for each segment on the path
  20806. for ( i = 0; i < numpoints; i++ ) {
  20807. u = i / ( numpoints - 1 );
  20808. tangents[ i ] = path.getTangentAt( u );
  20809. tangents[ i ].normalize();
  20810. }
  20811. initialNormal3();
  20812. function initialNormal1(lastBinormal) {
  20813. // fixed start binormal. Has dangers of 0 vectors
  20814. normals[ 0 ] = new THREE.Vector3();
  20815. binormals[ 0 ] = new THREE.Vector3();
  20816. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20817. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20818. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20819. }
  20820. function initialNormal2() {
  20821. // This uses the Frenet-Serret formula for deriving binormal
  20822. var t2 = path.getTangentAt( epsilon );
  20823. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20824. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20825. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20826. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20827. }
  20828. function initialNormal3() {
  20829. // select an initial normal vector perpenicular to the first tangent vector,
  20830. // and in the direction of the smallest tangent xyz component
  20831. normals[ 0 ] = new THREE.Vector3();
  20832. binormals[ 0 ] = new THREE.Vector3();
  20833. smallest = Number.MAX_VALUE;
  20834. tx = Math.abs( tangents[ 0 ].x );
  20835. ty = Math.abs( tangents[ 0 ].y );
  20836. tz = Math.abs( tangents[ 0 ].z );
  20837. if ( tx <= smallest ) {
  20838. smallest = tx;
  20839. normal.set( 1, 0, 0 );
  20840. }
  20841. if ( ty <= smallest ) {
  20842. smallest = ty;
  20843. normal.set( 0, 1, 0 );
  20844. }
  20845. if ( tz <= smallest ) {
  20846. normal.set( 0, 0, 1 );
  20847. }
  20848. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20849. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20850. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20851. }
  20852. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20853. for ( i = 1; i < numpoints; i++ ) {
  20854. normals[ i ] = normals[ i-1 ].clone();
  20855. binormals[ i ] = binormals[ i-1 ].clone();
  20856. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20857. if ( vec.length() > epsilon ) {
  20858. vec.normalize();
  20859. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20860. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20861. }
  20862. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20863. }
  20864. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20865. if ( closed ) {
  20866. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20867. theta /= ( numpoints - 1 );
  20868. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20869. theta = -theta;
  20870. }
  20871. for ( i = 1; i < numpoints; i++ ) {
  20872. // twist a little...
  20873. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20874. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20875. }
  20876. }
  20877. };
  20878. /**
  20879. * @author clockworkgeek / https://github.com/clockworkgeek
  20880. * @author timothypratley / https://github.com/timothypratley
  20881. * @author WestLangley / http://github.com/WestLangley
  20882. */
  20883. THREE.PolyhedronGeometry = function ( vertices, indices, radius, detail ) {
  20884. THREE.Geometry.call( this );
  20885. radius = radius || 1;
  20886. detail = detail || 0;
  20887. var that = this;
  20888. for ( var i = 0, l = vertices.length; i < l; i += 3 ) {
  20889. prepare( new THREE.Vector3( vertices[ i ], vertices[ i + 1 ], vertices[ i + 2 ] ) );
  20890. }
  20891. var midpoints = [], p = this.vertices;
  20892. var faces = [];
  20893. for ( var i = 0, j = 0, l = indices.length; i < l; i += 3, j ++ ) {
  20894. var v1 = p[ indices[ i ] ];
  20895. var v2 = p[ indices[ i + 1 ] ];
  20896. var v3 = p[ indices[ i + 2 ] ];
  20897. faces[ j ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20898. }
  20899. var centroid = new THREE.Vector3();
  20900. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20901. subdivide( faces[ i ], detail );
  20902. }
  20903. // Handle case when face straddles the seam
  20904. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20905. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20906. var x0 = uvs[ 0 ].x;
  20907. var x1 = uvs[ 1 ].x;
  20908. var x2 = uvs[ 2 ].x;
  20909. var max = Math.max( x0, Math.max( x1, x2 ) );
  20910. var min = Math.min( x0, Math.min( x1, x2 ) );
  20911. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20912. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20913. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20914. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20915. }
  20916. }
  20917. // Apply radius
  20918. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20919. this.vertices[ i ].multiplyScalar( radius );
  20920. }
  20921. // Merge vertices
  20922. this.mergeVertices();
  20923. this.computeFaceNormals();
  20924. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20925. // Project vector onto sphere's surface
  20926. function prepare( vector ) {
  20927. var vertex = vector.normalize().clone();
  20928. vertex.index = that.vertices.push( vertex ) - 1;
  20929. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20930. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20931. var v = inclination( vector ) / Math.PI + 0.5;
  20932. vertex.uv = new THREE.Vector2( u, 1 - v );
  20933. return vertex;
  20934. }
  20935. // Approximate a curved face with recursively sub-divided triangles.
  20936. function make( v1, v2, v3 ) {
  20937. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20938. that.faces.push( face );
  20939. centroid.copy( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20940. var azi = azimuth( centroid );
  20941. that.faceVertexUvs[ 0 ].push( [
  20942. correctUV( v1.uv, v1, azi ),
  20943. correctUV( v2.uv, v2, azi ),
  20944. correctUV( v3.uv, v3, azi )
  20945. ] );
  20946. }
  20947. // Analytically subdivide a face to the required detail level.
  20948. function subdivide( face, detail ) {
  20949. var cols = Math.pow(2, detail);
  20950. var cells = Math.pow(4, detail);
  20951. var a = prepare( that.vertices[ face.a ] );
  20952. var b = prepare( that.vertices[ face.b ] );
  20953. var c = prepare( that.vertices[ face.c ] );
  20954. var v = [];
  20955. // Construct all of the vertices for this subdivision.
  20956. for ( var i = 0 ; i <= cols; i ++ ) {
  20957. v[ i ] = [];
  20958. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20959. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20960. var rows = cols - i;
  20961. for ( var j = 0; j <= rows; j ++) {
  20962. if ( j == 0 && i == cols ) {
  20963. v[ i ][ j ] = aj;
  20964. } else {
  20965. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20966. }
  20967. }
  20968. }
  20969. // Construct all of the faces.
  20970. for ( var i = 0; i < cols ; i ++ ) {
  20971. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20972. var k = Math.floor( j / 2 );
  20973. if ( j % 2 == 0 ) {
  20974. make(
  20975. v[ i ][ k + 1],
  20976. v[ i + 1 ][ k ],
  20977. v[ i ][ k ]
  20978. );
  20979. } else {
  20980. make(
  20981. v[ i ][ k + 1 ],
  20982. v[ i + 1][ k + 1],
  20983. v[ i + 1 ][ k ]
  20984. );
  20985. }
  20986. }
  20987. }
  20988. }
  20989. // Angle around the Y axis, counter-clockwise when looking from above.
  20990. function azimuth( vector ) {
  20991. return Math.atan2( vector.z, -vector.x );
  20992. }
  20993. // Angle above the XZ plane.
  20994. function inclination( vector ) {
  20995. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20996. }
  20997. // Texture fixing helper. Spheres have some odd behaviours.
  20998. function correctUV( uv, vector, azimuth ) {
  20999. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  21000. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  21001. return uv.clone();
  21002. }
  21003. };
  21004. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21005. /**
  21006. * @author timothypratley / https://github.com/timothypratley
  21007. */
  21008. THREE.IcosahedronGeometry = function ( radius, detail ) {
  21009. this.parameters = {
  21010. radius: radius,
  21011. detail: detail
  21012. };
  21013. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  21014. var vertices = [
  21015. -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  21016. 0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t,
  21017. t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1
  21018. ];
  21019. var indices = [
  21020. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
  21021. 1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
  21022. 3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
  21023. 4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
  21024. ];
  21025. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  21026. };
  21027. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21028. /**
  21029. * @author timothypratley / https://github.com/timothypratley
  21030. */
  21031. THREE.OctahedronGeometry = function ( radius, detail ) {
  21032. this.parameters = {
  21033. radius: radius,
  21034. detail: detail
  21035. };
  21036. var vertices = [
  21037. 1, 0, 0, -1, 0, 0, 0, 1, 0, 0,-1, 0, 0, 0, 1, 0, 0,-1
  21038. ];
  21039. var indices = [
  21040. 0, 2, 4, 0, 4, 3, 0, 3, 5, 0, 5, 2, 1, 2, 5, 1, 5, 3, 1, 3, 4, 1, 4, 2
  21041. ];
  21042. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  21043. };
  21044. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21045. /**
  21046. * @author timothypratley / https://github.com/timothypratley
  21047. */
  21048. THREE.TetrahedronGeometry = function ( radius, detail ) {
  21049. var vertices = [
  21050. 1, 1, 1, -1, -1, 1, -1, 1, -1, 1, -1, -1
  21051. ];
  21052. var indices = [
  21053. 2, 1, 0, 0, 3, 2, 1, 3, 0, 2, 3, 1
  21054. ];
  21055. THREE.PolyhedronGeometry.call( this, vertices, indices, radius, detail );
  21056. };
  21057. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21058. /**
  21059. * @author zz85 / https://github.com/zz85
  21060. * Parametric Surfaces Geometry
  21061. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  21062. *
  21063. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements );
  21064. *
  21065. */
  21066. THREE.ParametricGeometry = function ( func, slices, stacks ) {
  21067. THREE.Geometry.call( this );
  21068. var verts = this.vertices;
  21069. var faces = this.faces;
  21070. var uvs = this.faceVertexUvs[ 0 ];
  21071. var i, il, j, p;
  21072. var u, v;
  21073. var stackCount = stacks + 1;
  21074. var sliceCount = slices + 1;
  21075. for ( i = 0; i <= stacks; i ++ ) {
  21076. v = i / stacks;
  21077. for ( j = 0; j <= slices; j ++ ) {
  21078. u = j / slices;
  21079. p = func( u, v );
  21080. verts.push( p );
  21081. }
  21082. }
  21083. var a, b, c, d;
  21084. var uva, uvb, uvc, uvd;
  21085. for ( i = 0; i < stacks; i ++ ) {
  21086. for ( j = 0; j < slices; j ++ ) {
  21087. a = i * sliceCount + j;
  21088. b = i * sliceCount + j + 1;
  21089. c = (i + 1) * sliceCount + j + 1;
  21090. d = (i + 1) * sliceCount + j;
  21091. uva = new THREE.Vector2( j / slices, i / stacks );
  21092. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  21093. uvc = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  21094. uvd = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  21095. faces.push( new THREE.Face3( a, b, d ) );
  21096. uvs.push( [ uva, uvb, uvd ] );
  21097. faces.push( new THREE.Face3( b, c, d ) );
  21098. uvs.push( [ uvb.clone(), uvc, uvd.clone() ] );
  21099. }
  21100. }
  21101. // console.log(this);
  21102. // magic bullet
  21103. // var diff = this.mergeVertices();
  21104. // console.log('removed ', diff, ' vertices by merging');
  21105. this.computeFaceNormals();
  21106. this.computeVertexNormals();
  21107. };
  21108. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  21109. /**
  21110. * @author sroucheray / http://sroucheray.org/
  21111. * @author mrdoob / http://mrdoob.com/
  21112. */
  21113. THREE.AxisHelper = function ( size ) {
  21114. size = size || 1;
  21115. var geometry = new THREE.Geometry();
  21116. geometry.vertices.push(
  21117. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  21118. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  21119. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  21120. );
  21121. geometry.colors.push(
  21122. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  21123. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  21124. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  21125. );
  21126. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21127. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21128. };
  21129. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  21130. /**
  21131. * @author WestLangley / http://github.com/WestLangley
  21132. * @author zz85 / http://github.com/zz85
  21133. * @author bhouston / http://exocortex.com
  21134. *
  21135. * Creates an arrow for visualizing directions
  21136. *
  21137. * Parameters:
  21138. * dir - Vector3
  21139. * origin - Vector3
  21140. * length - Number
  21141. * hex - color in hex value
  21142. * headLength - Number
  21143. * headWidth - Number
  21144. */
  21145. THREE.ArrowHelper = function ( dir, origin, length, hex, headLength, headWidth ) {
  21146. // dir is assumed to be normalized
  21147. THREE.Object3D.call( this );
  21148. if ( hex === undefined ) hex = 0xffff00;
  21149. if ( length === undefined ) length = 1;
  21150. if ( headLength === undefined ) headLength = 0.2 * length;
  21151. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  21152. this.position = origin;
  21153. var lineGeometry = new THREE.Geometry();
  21154. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  21155. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  21156. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  21157. this.line.matrixAutoUpdate = false;
  21158. this.add( this.line );
  21159. var coneGeometry = new THREE.CylinderGeometry( 0, 0.5, 1, 5, 1 );
  21160. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, - 0.5, 0 ) );
  21161. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  21162. this.cone.matrixAutoUpdate = false;
  21163. this.add( this.cone );
  21164. this.setDirection( dir );
  21165. this.setLength( length, headLength, headWidth );
  21166. };
  21167. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  21168. THREE.ArrowHelper.prototype.setDirection = function () {
  21169. var axis = new THREE.Vector3();
  21170. var radians;
  21171. return function ( dir ) {
  21172. // dir is assumed to be normalized
  21173. if ( dir.y > 0.99999 ) {
  21174. this.quaternion.set( 0, 0, 0, 1 );
  21175. } else if ( dir.y < - 0.99999 ) {
  21176. this.quaternion.set( 1, 0, 0, 0 );
  21177. } else {
  21178. axis.set( dir.z, 0, - dir.x ).normalize();
  21179. radians = Math.acos( dir.y );
  21180. this.quaternion.setFromAxisAngle( axis, radians );
  21181. }
  21182. };
  21183. }();
  21184. THREE.ArrowHelper.prototype.setLength = function ( length, headLength, headWidth ) {
  21185. if ( headLength === undefined ) headLength = 0.2 * length;
  21186. if ( headWidth === undefined ) headWidth = 0.2 * headLength;
  21187. this.line.scale.set( 1, length, 1 );
  21188. this.line.updateMatrix();
  21189. this.cone.scale.set( headWidth, headLength, headWidth );
  21190. this.cone.position.y = length;
  21191. this.cone.updateMatrix();
  21192. };
  21193. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  21194. this.line.material.color.setHex( hex );
  21195. this.cone.material.color.setHex( hex );
  21196. };
  21197. /**
  21198. * @author mrdoob / http://mrdoob.com/
  21199. */
  21200. THREE.BoxHelper = function ( object ) {
  21201. // 5____4
  21202. // 1/___0/|
  21203. // | 6__|_7
  21204. // 2/___3/
  21205. var vertices = [
  21206. new THREE.Vector3( 1, 1, 1 ),
  21207. new THREE.Vector3( - 1, 1, 1 ),
  21208. new THREE.Vector3( - 1, - 1, 1 ),
  21209. new THREE.Vector3( 1, - 1, 1 ),
  21210. new THREE.Vector3( 1, 1, - 1 ),
  21211. new THREE.Vector3( - 1, 1, - 1 ),
  21212. new THREE.Vector3( - 1, - 1, - 1 ),
  21213. new THREE.Vector3( 1, - 1, - 1 )
  21214. ];
  21215. this.vertices = vertices;
  21216. // TODO: Wouldn't be nice if Line had .segments?
  21217. var geometry = new THREE.Geometry();
  21218. geometry.vertices.push(
  21219. vertices[ 0 ], vertices[ 1 ],
  21220. vertices[ 1 ], vertices[ 2 ],
  21221. vertices[ 2 ], vertices[ 3 ],
  21222. vertices[ 3 ], vertices[ 0 ],
  21223. vertices[ 4 ], vertices[ 5 ],
  21224. vertices[ 5 ], vertices[ 6 ],
  21225. vertices[ 6 ], vertices[ 7 ],
  21226. vertices[ 7 ], vertices[ 4 ],
  21227. vertices[ 0 ], vertices[ 4 ],
  21228. vertices[ 1 ], vertices[ 5 ],
  21229. vertices[ 2 ], vertices[ 6 ],
  21230. vertices[ 3 ], vertices[ 7 ]
  21231. );
  21232. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  21233. if ( object !== undefined ) {
  21234. this.update( object );
  21235. }
  21236. };
  21237. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  21238. THREE.BoxHelper.prototype.update = function ( object ) {
  21239. var geometry = object.geometry;
  21240. if ( geometry.boundingBox === null ) {
  21241. geometry.computeBoundingBox();
  21242. }
  21243. var min = geometry.boundingBox.min;
  21244. var max = geometry.boundingBox.max;
  21245. var vertices = this.vertices;
  21246. vertices[ 0 ].set( max.x, max.y, max.z );
  21247. vertices[ 1 ].set( min.x, max.y, max.z );
  21248. vertices[ 2 ].set( min.x, min.y, max.z );
  21249. vertices[ 3 ].set( max.x, min.y, max.z );
  21250. vertices[ 4 ].set( max.x, max.y, min.z );
  21251. vertices[ 5 ].set( min.x, max.y, min.z );
  21252. vertices[ 6 ].set( min.x, min.y, min.z );
  21253. vertices[ 7 ].set( max.x, min.y, min.z );
  21254. this.geometry.computeBoundingSphere();
  21255. this.geometry.verticesNeedUpdate = true;
  21256. this.matrixAutoUpdate = false;
  21257. this.matrixWorld = object.matrixWorld;
  21258. };
  21259. /**
  21260. * @author WestLangley / http://github.com/WestLangley
  21261. */
  21262. // a helper to show the world-axis-aligned bounding box for an object
  21263. THREE.BoundingBoxHelper = function ( object, hex ) {
  21264. var color = ( hex !== undefined ) ? hex : 0x888888;
  21265. this.object = object;
  21266. this.box = new THREE.Box3();
  21267. THREE.Mesh.call( this, new THREE.BoxGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  21268. };
  21269. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  21270. THREE.BoundingBoxHelper.prototype.update = function () {
  21271. this.box.setFromObject( this.object );
  21272. this.box.size( this.scale );
  21273. this.box.center( this.position );
  21274. };
  21275. /**
  21276. * @author alteredq / http://alteredqualia.com/
  21277. *
  21278. * - shows frustum, line of sight and up of the camera
  21279. * - suitable for fast updates
  21280. * - based on frustum visualization in lightgl.js shadowmap example
  21281. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  21282. */
  21283. THREE.CameraHelper = function ( camera ) {
  21284. var geometry = new THREE.Geometry();
  21285. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  21286. var pointMap = {};
  21287. // colors
  21288. var hexFrustum = 0xffaa00;
  21289. var hexCone = 0xff0000;
  21290. var hexUp = 0x00aaff;
  21291. var hexTarget = 0xffffff;
  21292. var hexCross = 0x333333;
  21293. // near
  21294. addLine( "n1", "n2", hexFrustum );
  21295. addLine( "n2", "n4", hexFrustum );
  21296. addLine( "n4", "n3", hexFrustum );
  21297. addLine( "n3", "n1", hexFrustum );
  21298. // far
  21299. addLine( "f1", "f2", hexFrustum );
  21300. addLine( "f2", "f4", hexFrustum );
  21301. addLine( "f4", "f3", hexFrustum );
  21302. addLine( "f3", "f1", hexFrustum );
  21303. // sides
  21304. addLine( "n1", "f1", hexFrustum );
  21305. addLine( "n2", "f2", hexFrustum );
  21306. addLine( "n3", "f3", hexFrustum );
  21307. addLine( "n4", "f4", hexFrustum );
  21308. // cone
  21309. addLine( "p", "n1", hexCone );
  21310. addLine( "p", "n2", hexCone );
  21311. addLine( "p", "n3", hexCone );
  21312. addLine( "p", "n4", hexCone );
  21313. // up
  21314. addLine( "u1", "u2", hexUp );
  21315. addLine( "u2", "u3", hexUp );
  21316. addLine( "u3", "u1", hexUp );
  21317. // target
  21318. addLine( "c", "t", hexTarget );
  21319. addLine( "p", "c", hexCross );
  21320. // cross
  21321. addLine( "cn1", "cn2", hexCross );
  21322. addLine( "cn3", "cn4", hexCross );
  21323. addLine( "cf1", "cf2", hexCross );
  21324. addLine( "cf3", "cf4", hexCross );
  21325. function addLine( a, b, hex ) {
  21326. addPoint( a, hex );
  21327. addPoint( b, hex );
  21328. }
  21329. function addPoint( id, hex ) {
  21330. geometry.vertices.push( new THREE.Vector3() );
  21331. geometry.colors.push( new THREE.Color( hex ) );
  21332. if ( pointMap[ id ] === undefined ) {
  21333. pointMap[ id ] = [];
  21334. }
  21335. pointMap[ id ].push( geometry.vertices.length - 1 );
  21336. }
  21337. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21338. this.camera = camera;
  21339. this.matrixWorld = camera.matrixWorld;
  21340. this.matrixAutoUpdate = false;
  21341. this.pointMap = pointMap;
  21342. this.update();
  21343. };
  21344. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  21345. THREE.CameraHelper.prototype.update = function () {
  21346. var vector = new THREE.Vector3();
  21347. var camera = new THREE.Camera();
  21348. var projector = new THREE.Projector();
  21349. return function () {
  21350. var scope = this;
  21351. var w = 1, h = 1;
  21352. // we need just camera projection matrix
  21353. // world matrix must be identity
  21354. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  21355. // center / target
  21356. setPoint( "c", 0, 0, -1 );
  21357. setPoint( "t", 0, 0, 1 );
  21358. // near
  21359. setPoint( "n1", -w, -h, -1 );
  21360. setPoint( "n2", w, -h, -1 );
  21361. setPoint( "n3", -w, h, -1 );
  21362. setPoint( "n4", w, h, -1 );
  21363. // far
  21364. setPoint( "f1", -w, -h, 1 );
  21365. setPoint( "f2", w, -h, 1 );
  21366. setPoint( "f3", -w, h, 1 );
  21367. setPoint( "f4", w, h, 1 );
  21368. // up
  21369. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  21370. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  21371. setPoint( "u3", 0, h * 2, -1 );
  21372. // cross
  21373. setPoint( "cf1", -w, 0, 1 );
  21374. setPoint( "cf2", w, 0, 1 );
  21375. setPoint( "cf3", 0, -h, 1 );
  21376. setPoint( "cf4", 0, h, 1 );
  21377. setPoint( "cn1", -w, 0, -1 );
  21378. setPoint( "cn2", w, 0, -1 );
  21379. setPoint( "cn3", 0, -h, -1 );
  21380. setPoint( "cn4", 0, h, -1 );
  21381. function setPoint( point, x, y, z ) {
  21382. vector.set( x, y, z );
  21383. projector.unprojectVector( vector, camera );
  21384. var points = scope.pointMap[ point ];
  21385. if ( points !== undefined ) {
  21386. for ( var i = 0, il = points.length; i < il; i ++ ) {
  21387. scope.geometry.vertices[ points[ i ] ].copy( vector );
  21388. }
  21389. }
  21390. }
  21391. this.geometry.verticesNeedUpdate = true;
  21392. };
  21393. }();
  21394. /**
  21395. * @author alteredq / http://alteredqualia.com/
  21396. * @author mrdoob / http://mrdoob.com/
  21397. * @author WestLangley / http://github.com/WestLangley
  21398. */
  21399. THREE.DirectionalLightHelper = function ( light, size ) {
  21400. THREE.Object3D.call( this );
  21401. this.light = light;
  21402. this.light.updateMatrixWorld();
  21403. this.matrixWorld = light.matrixWorld;
  21404. this.matrixAutoUpdate = false;
  21405. size = size || 1;
  21406. var geometry = new THREE.Geometry();
  21407. geometry.vertices.push(
  21408. new THREE.Vector3( - size, size, 0 ),
  21409. new THREE.Vector3( size, size, 0 ),
  21410. new THREE.Vector3( size, - size, 0 ),
  21411. new THREE.Vector3( - size, - size, 0 ),
  21412. new THREE.Vector3( - size, size, 0 )
  21413. );
  21414. var material = new THREE.LineBasicMaterial( { fog: false } );
  21415. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21416. this.lightPlane = new THREE.Line( geometry, material );
  21417. this.add( this.lightPlane );
  21418. geometry = new THREE.Geometry();
  21419. geometry.vertices.push(
  21420. new THREE.Vector3(),
  21421. new THREE.Vector3()
  21422. );
  21423. material = new THREE.LineBasicMaterial( { fog: false } );
  21424. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21425. this.targetLine = new THREE.Line( geometry, material );
  21426. this.add( this.targetLine );
  21427. this.update();
  21428. };
  21429. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21430. THREE.DirectionalLightHelper.prototype.dispose = function () {
  21431. this.lightPlane.geometry.dispose();
  21432. this.lightPlane.material.dispose();
  21433. this.targetLine.geometry.dispose();
  21434. this.targetLine.material.dispose();
  21435. };
  21436. THREE.DirectionalLightHelper.prototype.update = function () {
  21437. var v1 = new THREE.Vector3();
  21438. var v2 = new THREE.Vector3();
  21439. var v3 = new THREE.Vector3();
  21440. return function () {
  21441. v1.setFromMatrixPosition( this.light.matrixWorld );
  21442. v2.setFromMatrixPosition( this.light.target.matrixWorld );
  21443. v3.subVectors( v2, v1 );
  21444. this.lightPlane.lookAt( v3 );
  21445. this.lightPlane.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21446. this.targetLine.geometry.vertices[ 1 ].copy( v3 );
  21447. this.targetLine.geometry.verticesNeedUpdate = true;
  21448. this.targetLine.material.color.copy( this.lightPlane.material.color );
  21449. }
  21450. }();
  21451. /**
  21452. * @author WestLangley / http://github.com/WestLangley
  21453. */
  21454. THREE.EdgesHelper = function ( object, hex ) {
  21455. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21456. var edge = [ 0, 0 ], hash = {};
  21457. var sortFunction = function ( a, b ) { return a - b };
  21458. var keys = [ 'a', 'b', 'c' ];
  21459. var geometry = new THREE.BufferGeometry();
  21460. var geometry2 = object.geometry.clone();
  21461. geometry2.mergeVertices();
  21462. geometry2.computeFaceNormals();
  21463. var vertices = geometry2.vertices;
  21464. var faces = geometry2.faces;
  21465. var numEdges = 0;
  21466. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21467. var face = faces[ i ];
  21468. for ( var j = 0; j < 3; j ++ ) {
  21469. edge[ 0 ] = face[ keys[ j ] ];
  21470. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21471. edge.sort( sortFunction );
  21472. var key = edge.toString();
  21473. if ( hash[ key ] === undefined ) {
  21474. hash[ key ] = { vert1: edge[ 0 ], vert2: edge[ 1 ], face1: i, face2: undefined };
  21475. numEdges ++;
  21476. } else {
  21477. hash[ key ].face2 = i;
  21478. }
  21479. }
  21480. }
  21481. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21482. var coords = geometry.attributes.position.array;
  21483. var index = 0;
  21484. for ( var key in hash ) {
  21485. var h = hash[ key ];
  21486. if ( h.face2 === undefined || faces[ h.face1 ].normal.dot( faces[ h.face2 ].normal ) < 0.9999 ) { // hardwired const OK
  21487. var vertex = vertices[ h.vert1 ];
  21488. coords[ index ++ ] = vertex.x;
  21489. coords[ index ++ ] = vertex.y;
  21490. coords[ index ++ ] = vertex.z;
  21491. vertex = vertices[ h.vert2 ];
  21492. coords[ index ++ ] = vertex.x;
  21493. coords[ index ++ ] = vertex.y;
  21494. coords[ index ++ ] = vertex.z;
  21495. }
  21496. }
  21497. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21498. this.matrixAutoUpdate = false;
  21499. this.matrixWorld = object.matrixWorld;
  21500. };
  21501. THREE.EdgesHelper.prototype = Object.create( THREE.Line.prototype );
  21502. /**
  21503. * @author mrdoob / http://mrdoob.com/
  21504. * @author WestLangley / http://github.com/WestLangley
  21505. */
  21506. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  21507. this.object = object;
  21508. this.size = ( size !== undefined ) ? size : 1;
  21509. var color = ( hex !== undefined ) ? hex : 0xffff00;
  21510. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21511. var geometry = new THREE.Geometry();
  21512. var faces = this.object.geometry.faces;
  21513. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21514. geometry.vertices.push( new THREE.Vector3(), new THREE.Vector3() );
  21515. }
  21516. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21517. this.matrixAutoUpdate = false;
  21518. this.normalMatrix = new THREE.Matrix3();
  21519. this.update();
  21520. };
  21521. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21522. THREE.FaceNormalsHelper.prototype.update = function () {
  21523. var vertices = this.geometry.vertices;
  21524. var object = this.object;
  21525. var objectVertices = object.geometry.vertices;
  21526. var objectFaces = object.geometry.faces;
  21527. var objectWorldMatrix = object.matrixWorld;
  21528. object.updateMatrixWorld( true );
  21529. this.normalMatrix.getNormalMatrix( objectWorldMatrix );
  21530. for ( var i = 0, i2 = 0, l = objectFaces.length; i < l; i ++, i2 += 2 ) {
  21531. var face = objectFaces[ i ];
  21532. vertices[ i2 ].copy( objectVertices[ face.a ] )
  21533. .add( objectVertices[ face.b ] )
  21534. .add( objectVertices[ face.c ] )
  21535. .divideScalar( 3 )
  21536. .applyMatrix4( objectWorldMatrix );
  21537. vertices[ i2 + 1 ].copy( face.normal )
  21538. .applyMatrix3( this.normalMatrix )
  21539. .normalize()
  21540. .multiplyScalar( this.size )
  21541. .add( vertices[ i2 ] );
  21542. }
  21543. this.geometry.verticesNeedUpdate = true;
  21544. return this;
  21545. };
  21546. /**
  21547. * @author mrdoob / http://mrdoob.com/
  21548. */
  21549. THREE.GridHelper = function ( size, step ) {
  21550. var geometry = new THREE.Geometry();
  21551. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21552. this.color1 = new THREE.Color( 0x444444 );
  21553. this.color2 = new THREE.Color( 0x888888 );
  21554. for ( var i = - size; i <= size; i += step ) {
  21555. geometry.vertices.push(
  21556. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21557. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21558. );
  21559. var color = i === 0 ? this.color1 : this.color2;
  21560. geometry.colors.push( color, color, color, color );
  21561. }
  21562. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21563. };
  21564. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21565. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21566. this.color1.set( colorCenterLine );
  21567. this.color2.set( colorGrid );
  21568. this.geometry.colorsNeedUpdate = true;
  21569. }
  21570. /**
  21571. * @author alteredq / http://alteredqualia.com/
  21572. * @author mrdoob / http://mrdoob.com/
  21573. */
  21574. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21575. THREE.Object3D.call( this );
  21576. this.light = light;
  21577. this.light.updateMatrixWorld();
  21578. this.matrixWorld = light.matrixWorld;
  21579. this.matrixAutoUpdate = false;
  21580. this.colors = [ new THREE.Color(), new THREE.Color() ];
  21581. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21582. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21583. for ( var i = 0, il = 8; i < il; i ++ ) {
  21584. geometry.faces[ i ].color = this.colors[ i < 4 ? 0 : 1 ];
  21585. }
  21586. var material = new THREE.MeshBasicMaterial( { vertexColors: THREE.FaceColors, wireframe: true } );
  21587. this.lightSphere = new THREE.Mesh( geometry, material );
  21588. this.add( this.lightSphere );
  21589. this.update();
  21590. };
  21591. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21592. THREE.HemisphereLightHelper.prototype.dispose = function () {
  21593. this.lightSphere.geometry.dispose();
  21594. this.lightSphere.material.dispose();
  21595. };
  21596. THREE.HemisphereLightHelper.prototype.update = function () {
  21597. var vector = new THREE.Vector3();
  21598. return function () {
  21599. this.colors[ 0 ].copy( this.light.color ).multiplyScalar( this.light.intensity );
  21600. this.colors[ 1 ].copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21601. this.lightSphere.lookAt( vector.setFromMatrixPosition( this.light.matrixWorld ).negate() );
  21602. this.lightSphere.geometry.colorsNeedUpdate = true;
  21603. }
  21604. }();
  21605. /**
  21606. * @author alteredq / http://alteredqualia.com/
  21607. * @author mrdoob / http://mrdoob.com/
  21608. */
  21609. THREE.PointLightHelper = function ( light, sphereSize ) {
  21610. this.light = light;
  21611. this.light.updateMatrixWorld();
  21612. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21613. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21614. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21615. THREE.Mesh.call( this, geometry, material );
  21616. this.matrixWorld = this.light.matrixWorld;
  21617. this.matrixAutoUpdate = false;
  21618. /*
  21619. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21620. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21621. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21622. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21623. var d = light.distance;
  21624. if ( d === 0.0 ) {
  21625. this.lightDistance.visible = false;
  21626. } else {
  21627. this.lightDistance.scale.set( d, d, d );
  21628. }
  21629. this.add( this.lightDistance );
  21630. */
  21631. };
  21632. THREE.PointLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21633. THREE.PointLightHelper.prototype.dispose = function () {
  21634. this.geometry.dispose();
  21635. this.material.dispose();
  21636. };
  21637. THREE.PointLightHelper.prototype.update = function () {
  21638. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21639. /*
  21640. var d = this.light.distance;
  21641. if ( d === 0.0 ) {
  21642. this.lightDistance.visible = false;
  21643. } else {
  21644. this.lightDistance.visible = true;
  21645. this.lightDistance.scale.set( d, d, d );
  21646. }
  21647. */
  21648. };
  21649. /**
  21650. * @author alteredq / http://alteredqualia.com/
  21651. * @author mrdoob / http://mrdoob.com/
  21652. * @author WestLangley / http://github.com/WestLangley
  21653. */
  21654. THREE.SpotLightHelper = function ( light ) {
  21655. THREE.Object3D.call( this );
  21656. this.light = light;
  21657. this.light.updateMatrixWorld();
  21658. this.matrixWorld = light.matrixWorld;
  21659. this.matrixAutoUpdate = false;
  21660. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21661. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21662. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21663. var material = new THREE.MeshBasicMaterial( { wireframe: true, fog: false } );
  21664. this.cone = new THREE.Mesh( geometry, material );
  21665. this.add( this.cone );
  21666. this.update();
  21667. };
  21668. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21669. THREE.SpotLightHelper.prototype.dispose = function () {
  21670. this.cone.geometry.dispose();
  21671. this.cone.material.dispose();
  21672. };
  21673. THREE.SpotLightHelper.prototype.update = function () {
  21674. var vector = new THREE.Vector3();
  21675. var vector2 = new THREE.Vector3();
  21676. return function () {
  21677. var coneLength = this.light.distance ? this.light.distance : 10000;
  21678. var coneWidth = coneLength * Math.tan( this.light.angle );
  21679. this.cone.scale.set( coneWidth, coneWidth, coneLength );
  21680. vector.setFromMatrixPosition( this.light.matrixWorld );
  21681. vector2.setFromMatrixPosition( this.light.target.matrixWorld );
  21682. this.cone.lookAt( vector2.sub( vector ) );
  21683. this.cone.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21684. };
  21685. }();
  21686. /**
  21687. * @author mrdoob / http://mrdoob.com/
  21688. * @author WestLangley / http://github.com/WestLangley
  21689. */
  21690. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21691. this.object = object;
  21692. this.size = ( size !== undefined ) ? size : 1;
  21693. var color = ( hex !== undefined ) ? hex : 0xff0000;
  21694. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21695. var geometry = new THREE.Geometry();
  21696. var vertices = object.geometry.vertices;
  21697. var faces = object.geometry.faces;
  21698. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21699. var face = faces[ i ];
  21700. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21701. geometry.vertices.push( new THREE.Vector3() );
  21702. geometry.vertices.push( new THREE.Vector3() );
  21703. }
  21704. }
  21705. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21706. this.matrixAutoUpdate = false;
  21707. this.normalMatrix = new THREE.Matrix3();
  21708. this.update();
  21709. };
  21710. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21711. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21712. var v1 = new THREE.Vector3();
  21713. return function( object ) {
  21714. var keys = [ 'a', 'b', 'c', 'd' ];
  21715. this.object.updateMatrixWorld( true );
  21716. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21717. var vertices = this.geometry.vertices;
  21718. var verts = this.object.geometry.vertices;
  21719. var faces = this.object.geometry.faces;
  21720. var worldMatrix = this.object.matrixWorld;
  21721. var idx = 0;
  21722. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21723. var face = faces[ i ];
  21724. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21725. var vertexId = face[ keys[ j ] ];
  21726. var vertex = verts[ vertexId ];
  21727. var normal = face.vertexNormals[ j ];
  21728. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21729. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21730. v1.add( vertices[ idx ] );
  21731. idx = idx + 1;
  21732. vertices[ idx ].copy( v1 );
  21733. idx = idx + 1;
  21734. }
  21735. }
  21736. this.geometry.verticesNeedUpdate = true;
  21737. return this;
  21738. }
  21739. }());
  21740. /**
  21741. * @author mrdoob / http://mrdoob.com/
  21742. * @author WestLangley / http://github.com/WestLangley
  21743. */
  21744. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21745. this.object = object;
  21746. this.size = ( size !== undefined ) ? size : 1;
  21747. var color = ( hex !== undefined ) ? hex : 0x0000ff;
  21748. var width = ( linewidth !== undefined ) ? linewidth : 1;
  21749. var geometry = new THREE.Geometry();
  21750. var vertices = object.geometry.vertices;
  21751. var faces = object.geometry.faces;
  21752. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21753. var face = faces[ i ];
  21754. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21755. geometry.vertices.push( new THREE.Vector3() );
  21756. geometry.vertices.push( new THREE.Vector3() );
  21757. }
  21758. }
  21759. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21760. this.matrixAutoUpdate = false;
  21761. this.update();
  21762. };
  21763. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21764. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21765. var v1 = new THREE.Vector3();
  21766. return function( object ) {
  21767. var keys = [ 'a', 'b', 'c', 'd' ];
  21768. this.object.updateMatrixWorld( true );
  21769. var vertices = this.geometry.vertices;
  21770. var verts = this.object.geometry.vertices;
  21771. var faces = this.object.geometry.faces;
  21772. var worldMatrix = this.object.matrixWorld;
  21773. var idx = 0;
  21774. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21775. var face = faces[ i ];
  21776. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21777. var vertexId = face[ keys[ j ] ];
  21778. var vertex = verts[ vertexId ];
  21779. var tangent = face.vertexTangents[ j ];
  21780. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21781. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21782. v1.add( vertices[ idx ] );
  21783. idx = idx + 1;
  21784. vertices[ idx ].copy( v1 );
  21785. idx = idx + 1;
  21786. }
  21787. }
  21788. this.geometry.verticesNeedUpdate = true;
  21789. return this;
  21790. }
  21791. }());
  21792. /**
  21793. * @author mrdoob / http://mrdoob.com/
  21794. */
  21795. THREE.WireframeHelper = function ( object, hex ) {
  21796. var color = ( hex !== undefined ) ? hex : 0xffffff;
  21797. var edge = [ 0, 0 ], hash = {};
  21798. var sortFunction = function ( a, b ) { return a - b };
  21799. var keys = [ 'a', 'b', 'c' ];
  21800. var geometry = new THREE.BufferGeometry();
  21801. if ( object.geometry instanceof THREE.Geometry ) {
  21802. var vertices = object.geometry.vertices;
  21803. var faces = object.geometry.faces;
  21804. var numEdges = 0;
  21805. // allocate maximal size
  21806. var edges = new Uint32Array( 6 * faces.length );
  21807. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21808. var face = faces[ i ];
  21809. for ( var j = 0; j < 3; j ++ ) {
  21810. edge[ 0 ] = face[ keys[ j ] ];
  21811. edge[ 1 ] = face[ keys[ ( j + 1 ) % 3 ] ];
  21812. edge.sort( sortFunction );
  21813. var key = edge.toString();
  21814. if ( hash[ key ] === undefined ) {
  21815. edges[ 2 * numEdges ] = edge[ 0 ];
  21816. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21817. hash[ key ] = true;
  21818. numEdges ++;
  21819. }
  21820. }
  21821. }
  21822. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21823. var coords = geometry.attributes.position.array;
  21824. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21825. for ( var j = 0; j < 2; j ++ ) {
  21826. var vertex = vertices[ edges [ 2 * i + j] ];
  21827. var index = 6 * i + 3 * j;
  21828. coords[ index + 0 ] = vertex.x;
  21829. coords[ index + 1 ] = vertex.y;
  21830. coords[ index + 2 ] = vertex.z;
  21831. }
  21832. }
  21833. } else if ( object.geometry instanceof THREE.BufferGeometry && object.geometry.attributes.index !== undefined ) { // indexed BufferGeometry
  21834. var vertices = object.geometry.attributes.position.array;
  21835. var indices = object.geometry.attributes.index.array;
  21836. var offsets = object.geometry.offsets;
  21837. var numEdges = 0;
  21838. // allocate maximal size
  21839. var edges = new Uint32Array( 2 * indices.length );
  21840. for ( var o = 0, ol = offsets.length; o < ol; ++ o ) {
  21841. var start = offsets[ o ].start;
  21842. var count = offsets[ o ].count;
  21843. var index = offsets[ o ].index;
  21844. for ( var i = start, il = start + count; i < il; i += 3 ) {
  21845. for ( var j = 0; j < 3; j ++ ) {
  21846. edge[ 0 ] = index + indices[ i + j ];
  21847. edge[ 1 ] = index + indices[ i + ( j + 1 ) % 3 ];
  21848. edge.sort( sortFunction );
  21849. var key = edge.toString();
  21850. if ( hash[ key ] === undefined ) {
  21851. edges[ 2 * numEdges ] = edge[ 0 ];
  21852. edges[ 2 * numEdges + 1 ] = edge[ 1 ];
  21853. hash[ key ] = true;
  21854. numEdges ++;
  21855. }
  21856. }
  21857. }
  21858. }
  21859. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21860. var coords = geometry.attributes.position.array;
  21861. for ( var i = 0, l = numEdges; i < l; i ++ ) {
  21862. for ( var j = 0; j < 2; j ++ ) {
  21863. var index = 6 * i + 3 * j;
  21864. var index2 = 3 * edges[ 2 * i + j];
  21865. coords[ index + 0 ] = vertices[ index2 ];
  21866. coords[ index + 1 ] = vertices[ index2 + 1 ];
  21867. coords[ index + 2 ] = vertices[ index2 + 2 ];
  21868. }
  21869. }
  21870. } else if ( object.geometry instanceof THREE.BufferGeometry ) { // non-indexed BufferGeometry
  21871. var vertices = object.geometry.attributes.position.array;
  21872. var numEdges = vertices.length / 3;
  21873. var numTris = numEdges / 3;
  21874. geometry.addAttribute( 'position', new THREE.Float32Attribute( numEdges * 2, 3 ) );
  21875. var coords = geometry.attributes.position.array;
  21876. for ( var i = 0, l = numTris; i < l; i ++ ) {
  21877. for ( var j = 0; j < 3; j ++ ) {
  21878. var index = 18 * i + 6 * j;
  21879. var index1 = 9 * i + 3 * j;
  21880. coords[ index + 0 ] = vertices[ index1 ];
  21881. coords[ index + 1 ] = vertices[ index1 + 1 ];
  21882. coords[ index + 2 ] = vertices[ index1 + 2 ];
  21883. var index2 = 9 * i + 3 * ( ( j + 1 ) % 3 );
  21884. coords[ index + 3 ] = vertices[ index2 ];
  21885. coords[ index + 4 ] = vertices[ index2 + 1 ];
  21886. coords[ index + 5 ] = vertices[ index2 + 2 ];
  21887. }
  21888. }
  21889. }
  21890. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ), THREE.LinePieces );
  21891. this.matrixAutoUpdate = false;
  21892. this.matrixWorld = object.matrixWorld;
  21893. };
  21894. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21895. /**
  21896. * @author alteredq / http://alteredqualia.com/
  21897. */
  21898. THREE.ImmediateRenderObject = function () {
  21899. THREE.Object3D.call( this );
  21900. this.render = function ( renderCallback ) { };
  21901. };
  21902. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21903. /**
  21904. * @author mikael emtinger / http://gomo.se/
  21905. * @author alteredq / http://alteredqualia.com/
  21906. */
  21907. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21908. THREE.Object3D.call( this );
  21909. this.lensFlares = [];
  21910. this.positionScreen = new THREE.Vector3();
  21911. this.customUpdateCallback = undefined;
  21912. if( texture !== undefined ) {
  21913. this.add( texture, size, distance, blending, color );
  21914. }
  21915. };
  21916. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21917. /*
  21918. * Add: adds another flare
  21919. */
  21920. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21921. if( size === undefined ) size = -1;
  21922. if( distance === undefined ) distance = 0;
  21923. if( opacity === undefined ) opacity = 1;
  21924. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21925. if( blending === undefined ) blending = THREE.NormalBlending;
  21926. distance = Math.min( distance, Math.max( 0, distance ) );
  21927. this.lensFlares.push( { texture: texture, // THREE.Texture
  21928. size: size, // size in pixels (-1 = use texture.width)
  21929. distance: distance, // distance (0-1) from light source (0=at light source)
  21930. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21931. scale: 1, // scale
  21932. rotation: 1, // rotation
  21933. opacity: opacity, // opacity
  21934. color: color, // color
  21935. blending: blending } ); // blending
  21936. };
  21937. /*
  21938. * Update lens flares update positions on all flares based on the screen position
  21939. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21940. */
  21941. THREE.LensFlare.prototype.updateLensFlares = function () {
  21942. var f, fl = this.lensFlares.length;
  21943. var flare;
  21944. var vecX = -this.positionScreen.x * 2;
  21945. var vecY = -this.positionScreen.y * 2;
  21946. for( f = 0; f < fl; f ++ ) {
  21947. flare = this.lensFlares[ f ];
  21948. flare.x = this.positionScreen.x + vecX * flare.distance;
  21949. flare.y = this.positionScreen.y + vecY * flare.distance;
  21950. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21951. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21952. }
  21953. };
  21954. /**
  21955. * @author alteredq / http://alteredqualia.com/
  21956. */
  21957. THREE.MorphBlendMesh = function( geometry, material ) {
  21958. THREE.Mesh.call( this, geometry, material );
  21959. this.animationsMap = {};
  21960. this.animationsList = [];
  21961. // prepare default animation
  21962. // (all frames played together in 1 second)
  21963. var numFrames = this.geometry.morphTargets.length;
  21964. var name = "__default";
  21965. var startFrame = 0;
  21966. var endFrame = numFrames - 1;
  21967. var fps = numFrames / 1;
  21968. this.createAnimation( name, startFrame, endFrame, fps );
  21969. this.setAnimationWeight( name, 1 );
  21970. };
  21971. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21972. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21973. var animation = {
  21974. startFrame: start,
  21975. endFrame: end,
  21976. length: end - start + 1,
  21977. fps: fps,
  21978. duration: ( end - start ) / fps,
  21979. lastFrame: 0,
  21980. currentFrame: 0,
  21981. active: false,
  21982. time: 0,
  21983. direction: 1,
  21984. weight: 1,
  21985. directionBackwards: false,
  21986. mirroredLoop: false
  21987. };
  21988. this.animationsMap[ name ] = animation;
  21989. this.animationsList.push( animation );
  21990. };
  21991. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21992. var pattern = /([a-z]+)(\d+)/;
  21993. var firstAnimation, frameRanges = {};
  21994. var geometry = this.geometry;
  21995. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21996. var morph = geometry.morphTargets[ i ];
  21997. var chunks = morph.name.match( pattern );
  21998. if ( chunks && chunks.length > 1 ) {
  21999. var name = chunks[ 1 ];
  22000. var num = chunks[ 2 ];
  22001. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  22002. var range = frameRanges[ name ];
  22003. if ( i < range.start ) range.start = i;
  22004. if ( i > range.end ) range.end = i;
  22005. if ( ! firstAnimation ) firstAnimation = name;
  22006. }
  22007. }
  22008. for ( var name in frameRanges ) {
  22009. var range = frameRanges[ name ];
  22010. this.createAnimation( name, range.start, range.end, fps );
  22011. }
  22012. this.firstAnimation = firstAnimation;
  22013. };
  22014. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  22015. var animation = this.animationsMap[ name ];
  22016. if ( animation ) {
  22017. animation.direction = 1;
  22018. animation.directionBackwards = false;
  22019. }
  22020. };
  22021. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  22022. var animation = this.animationsMap[ name ];
  22023. if ( animation ) {
  22024. animation.direction = -1;
  22025. animation.directionBackwards = true;
  22026. }
  22027. };
  22028. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  22029. var animation = this.animationsMap[ name ];
  22030. if ( animation ) {
  22031. animation.fps = fps;
  22032. animation.duration = ( animation.end - animation.start ) / animation.fps;
  22033. }
  22034. };
  22035. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  22036. var animation = this.animationsMap[ name ];
  22037. if ( animation ) {
  22038. animation.duration = duration;
  22039. animation.fps = ( animation.end - animation.start ) / animation.duration;
  22040. }
  22041. };
  22042. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  22043. var animation = this.animationsMap[ name ];
  22044. if ( animation ) {
  22045. animation.weight = weight;
  22046. }
  22047. };
  22048. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  22049. var animation = this.animationsMap[ name ];
  22050. if ( animation ) {
  22051. animation.time = time;
  22052. }
  22053. };
  22054. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  22055. var time = 0;
  22056. var animation = this.animationsMap[ name ];
  22057. if ( animation ) {
  22058. time = animation.time;
  22059. }
  22060. return time;
  22061. };
  22062. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  22063. var duration = -1;
  22064. var animation = this.animationsMap[ name ];
  22065. if ( animation ) {
  22066. duration = animation.duration;
  22067. }
  22068. return duration;
  22069. };
  22070. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  22071. var animation = this.animationsMap[ name ];
  22072. if ( animation ) {
  22073. animation.time = 0;
  22074. animation.active = true;
  22075. } else {
  22076. console.warn( "animation[" + name + "] undefined" );
  22077. }
  22078. };
  22079. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  22080. var animation = this.animationsMap[ name ];
  22081. if ( animation ) {
  22082. animation.active = false;
  22083. }
  22084. };
  22085. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  22086. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  22087. var animation = this.animationsList[ i ];
  22088. if ( ! animation.active ) continue;
  22089. var frameTime = animation.duration / animation.length;
  22090. animation.time += animation.direction * delta;
  22091. if ( animation.mirroredLoop ) {
  22092. if ( animation.time > animation.duration || animation.time < 0 ) {
  22093. animation.direction *= -1;
  22094. if ( animation.time > animation.duration ) {
  22095. animation.time = animation.duration;
  22096. animation.directionBackwards = true;
  22097. }
  22098. if ( animation.time < 0 ) {
  22099. animation.time = 0;
  22100. animation.directionBackwards = false;
  22101. }
  22102. }
  22103. } else {
  22104. animation.time = animation.time % animation.duration;
  22105. if ( animation.time < 0 ) animation.time += animation.duration;
  22106. }
  22107. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  22108. var weight = animation.weight;
  22109. if ( keyframe !== animation.currentFrame ) {
  22110. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  22111. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  22112. this.morphTargetInfluences[ keyframe ] = 0;
  22113. animation.lastFrame = animation.currentFrame;
  22114. animation.currentFrame = keyframe;
  22115. }
  22116. var mix = ( animation.time % frameTime ) / frameTime;
  22117. if ( animation.directionBackwards ) mix = 1 - mix;
  22118. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  22119. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  22120. }
  22121. };
  22122. /**
  22123. * @author mikael emtinger / http://gomo.se/
  22124. * @author alteredq / http://alteredqualia.com/
  22125. */
  22126. THREE.LensFlarePlugin = function () {
  22127. var _gl, _renderer, _precision, _lensFlare = {};
  22128. this.init = function ( renderer ) {
  22129. _gl = renderer.context;
  22130. _renderer = renderer;
  22131. _precision = renderer.getPrecision();
  22132. _lensFlare.vertices = new Float32Array( 8 + 8 );
  22133. _lensFlare.faces = new Uint16Array( 6 );
  22134. var i = 0;
  22135. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  22136. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  22137. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  22138. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  22139. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  22140. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  22141. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  22142. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  22143. i = 0;
  22144. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  22145. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  22146. // buffers
  22147. _lensFlare.vertexBuffer = _gl.createBuffer();
  22148. _lensFlare.elementBuffer = _gl.createBuffer();
  22149. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  22150. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  22151. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  22152. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  22153. // textures
  22154. _lensFlare.tempTexture = _gl.createTexture();
  22155. _lensFlare.occlusionTexture = _gl.createTexture();
  22156. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22157. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  22158. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  22159. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  22160. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  22161. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  22162. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  22163. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  22164. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  22165. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  22166. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  22167. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  22168. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  22169. _lensFlare.hasVertexTexture = false;
  22170. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  22171. } else {
  22172. _lensFlare.hasVertexTexture = true;
  22173. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  22174. }
  22175. _lensFlare.attributes = {};
  22176. _lensFlare.uniforms = {};
  22177. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  22178. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  22179. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  22180. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  22181. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  22182. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  22183. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  22184. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  22185. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  22186. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  22187. };
  22188. /*
  22189. * Render lens flares
  22190. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  22191. * reads these back and calculates occlusion.
  22192. * Then _lensFlare.update_lensFlares() is called to re-position and
  22193. * update transparency of flares. Then they are rendered.
  22194. *
  22195. */
  22196. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22197. var flares = scene.__webglFlares,
  22198. nFlares = flares.length;
  22199. if ( ! nFlares ) return;
  22200. var tempPosition = new THREE.Vector3();
  22201. var invAspect = viewportHeight / viewportWidth,
  22202. halfViewportWidth = viewportWidth * 0.5,
  22203. halfViewportHeight = viewportHeight * 0.5;
  22204. var size = 16 / viewportHeight,
  22205. scale = new THREE.Vector2( size * invAspect, size );
  22206. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  22207. screenPositionPixels = new THREE.Vector2( 1, 1 );
  22208. var uniforms = _lensFlare.uniforms,
  22209. attributes = _lensFlare.attributes;
  22210. // set _lensFlare program and reset blending
  22211. _gl.useProgram( _lensFlare.program );
  22212. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  22213. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  22214. // loop through all lens flares to update their occlusion and positions
  22215. // setup gl and common used attribs/unforms
  22216. _gl.uniform1i( uniforms.occlusionMap, 0 );
  22217. _gl.uniform1i( uniforms.map, 1 );
  22218. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  22219. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22220. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22221. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  22222. _gl.disable( _gl.CULL_FACE );
  22223. _gl.depthMask( false );
  22224. var i, j, jl, flare, sprite;
  22225. for ( i = 0; i < nFlares; i ++ ) {
  22226. size = 16 / viewportHeight;
  22227. scale.set( size * invAspect, size );
  22228. // calc object screen position
  22229. flare = flares[ i ];
  22230. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  22231. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  22232. tempPosition.applyProjection( camera.projectionMatrix );
  22233. // setup arrays for gl programs
  22234. screenPosition.copy( tempPosition )
  22235. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  22236. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  22237. // screen cull
  22238. if ( _lensFlare.hasVertexTexture || (
  22239. screenPositionPixels.x > 0 &&
  22240. screenPositionPixels.x < viewportWidth &&
  22241. screenPositionPixels.y > 0 &&
  22242. screenPositionPixels.y < viewportHeight ) ) {
  22243. // save current RGB to temp texture
  22244. _gl.activeTexture( _gl.TEXTURE1 );
  22245. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22246. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  22247. // render pink quad
  22248. _gl.uniform1i( uniforms.renderType, 0 );
  22249. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  22250. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  22251. _gl.disable( _gl.BLEND );
  22252. _gl.enable( _gl.DEPTH_TEST );
  22253. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22254. // copy result to occlusionMap
  22255. _gl.activeTexture( _gl.TEXTURE0 );
  22256. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  22257. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  22258. // restore graphics
  22259. _gl.uniform1i( uniforms.renderType, 1 );
  22260. _gl.disable( _gl.DEPTH_TEST );
  22261. _gl.activeTexture( _gl.TEXTURE1 );
  22262. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  22263. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22264. // update object positions
  22265. flare.positionScreen.copy( screenPosition )
  22266. if ( flare.customUpdateCallback ) {
  22267. flare.customUpdateCallback( flare );
  22268. } else {
  22269. flare.updateLensFlares();
  22270. }
  22271. // render flares
  22272. _gl.uniform1i( uniforms.renderType, 2 );
  22273. _gl.enable( _gl.BLEND );
  22274. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  22275. sprite = flare.lensFlares[ j ];
  22276. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  22277. screenPosition.x = sprite.x;
  22278. screenPosition.y = sprite.y;
  22279. screenPosition.z = sprite.z;
  22280. size = sprite.size * sprite.scale / viewportHeight;
  22281. scale.x = size * invAspect;
  22282. scale.y = size;
  22283. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  22284. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  22285. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22286. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  22287. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  22288. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  22289. _renderer.setTexture( sprite.texture, 1 );
  22290. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22291. }
  22292. }
  22293. }
  22294. }
  22295. // restore gl
  22296. _gl.enable( _gl.CULL_FACE );
  22297. _gl.enable( _gl.DEPTH_TEST );
  22298. _gl.depthMask( true );
  22299. };
  22300. function createProgram ( shader, precision ) {
  22301. var program = _gl.createProgram();
  22302. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22303. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22304. var prefix = "precision " + precision + " float;\n";
  22305. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22306. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22307. _gl.compileShader( fragmentShader );
  22308. _gl.compileShader( vertexShader );
  22309. _gl.attachShader( program, fragmentShader );
  22310. _gl.attachShader( program, vertexShader );
  22311. _gl.linkProgram( program );
  22312. return program;
  22313. };
  22314. };
  22315. /**
  22316. * @author alteredq / http://alteredqualia.com/
  22317. */
  22318. THREE.ShadowMapPlugin = function () {
  22319. var _gl,
  22320. _renderer,
  22321. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22322. _frustum = new THREE.Frustum(),
  22323. _projScreenMatrix = new THREE.Matrix4(),
  22324. _min = new THREE.Vector3(),
  22325. _max = new THREE.Vector3(),
  22326. _matrixPosition = new THREE.Vector3();
  22327. this.init = function ( renderer ) {
  22328. _gl = renderer.context;
  22329. _renderer = renderer;
  22330. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22331. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22332. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22333. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22334. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22335. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22336. _depthMaterial._shadowPass = true;
  22337. _depthMaterialMorph._shadowPass = true;
  22338. _depthMaterialSkin._shadowPass = true;
  22339. _depthMaterialMorphSkin._shadowPass = true;
  22340. };
  22341. this.render = function ( scene, camera ) {
  22342. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  22343. this.update( scene, camera );
  22344. };
  22345. this.update = function ( scene, camera ) {
  22346. var i, il, j, jl, n,
  22347. shadowMap, shadowMatrix, shadowCamera,
  22348. program, buffer, material,
  22349. webglObject, object, light,
  22350. renderList,
  22351. lights = [],
  22352. k = 0,
  22353. fog = null;
  22354. // set GL state for depth map
  22355. _gl.clearColor( 1, 1, 1, 1 );
  22356. _gl.disable( _gl.BLEND );
  22357. _gl.enable( _gl.CULL_FACE );
  22358. _gl.frontFace( _gl.CCW );
  22359. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22360. _gl.cullFace( _gl.FRONT );
  22361. } else {
  22362. _gl.cullFace( _gl.BACK );
  22363. }
  22364. _renderer.setDepthTest( true );
  22365. // preprocess lights
  22366. // - skip lights that are not casting shadows
  22367. // - create virtual lights for cascaded shadow maps
  22368. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  22369. light = scene.__lights[ i ];
  22370. if ( ! light.castShadow ) continue;
  22371. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  22372. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  22373. var virtualLight;
  22374. if ( ! light.shadowCascadeArray[ n ] ) {
  22375. virtualLight = createVirtualLight( light, n );
  22376. virtualLight.originalCamera = camera;
  22377. var gyro = new THREE.Gyroscope();
  22378. gyro.position.copy( light.shadowCascadeOffset );
  22379. gyro.add( virtualLight );
  22380. gyro.add( virtualLight.target );
  22381. camera.add( gyro );
  22382. light.shadowCascadeArray[ n ] = virtualLight;
  22383. console.log( "Created virtualLight", virtualLight );
  22384. } else {
  22385. virtualLight = light.shadowCascadeArray[ n ];
  22386. }
  22387. updateVirtualLight( light, n );
  22388. lights[ k ] = virtualLight;
  22389. k ++;
  22390. }
  22391. } else {
  22392. lights[ k ] = light;
  22393. k ++;
  22394. }
  22395. }
  22396. // render depth map
  22397. for ( i = 0, il = lights.length; i < il; i ++ ) {
  22398. light = lights[ i ];
  22399. if ( ! light.shadowMap ) {
  22400. var shadowFilter = THREE.LinearFilter;
  22401. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  22402. shadowFilter = THREE.NearestFilter;
  22403. }
  22404. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  22405. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  22406. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  22407. light.shadowMatrix = new THREE.Matrix4();
  22408. }
  22409. if ( ! light.shadowCamera ) {
  22410. if ( light instanceof THREE.SpotLight ) {
  22411. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  22412. } else if ( light instanceof THREE.DirectionalLight ) {
  22413. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  22414. } else {
  22415. console.error( "Unsupported light type for shadow" );
  22416. continue;
  22417. }
  22418. scene.add( light.shadowCamera );
  22419. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22420. }
  22421. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  22422. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  22423. light.shadowCamera.add( light.cameraHelper );
  22424. }
  22425. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  22426. updateShadowCamera( camera, light );
  22427. }
  22428. shadowMap = light.shadowMap;
  22429. shadowMatrix = light.shadowMatrix;
  22430. shadowCamera = light.shadowCamera;
  22431. shadowCamera.position.setFromMatrixPosition( light.matrixWorld );
  22432. _matrixPosition.setFromMatrixPosition( light.target.matrixWorld );
  22433. shadowCamera.lookAt( _matrixPosition );
  22434. shadowCamera.updateMatrixWorld();
  22435. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  22436. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  22437. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  22438. // compute shadow matrix
  22439. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  22440. 0.0, 0.5, 0.0, 0.5,
  22441. 0.0, 0.0, 0.5, 0.5,
  22442. 0.0, 0.0, 0.0, 1.0 );
  22443. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  22444. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  22445. // update camera matrices and frustum
  22446. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  22447. _frustum.setFromMatrix( _projScreenMatrix );
  22448. // render shadow map
  22449. _renderer.setRenderTarget( shadowMap );
  22450. _renderer.clear();
  22451. // set object matrices & frustum culling
  22452. renderList = scene.__webglObjects;
  22453. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22454. webglObject = renderList[ j ];
  22455. object = webglObject.object;
  22456. webglObject.render = false;
  22457. if ( object.visible && object.castShadow ) {
  22458. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22459. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22460. webglObject.render = true;
  22461. }
  22462. }
  22463. }
  22464. // render regular objects
  22465. var objectMaterial, useMorphing, useSkinning;
  22466. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22467. webglObject = renderList[ j ];
  22468. if ( webglObject.render ) {
  22469. object = webglObject.object;
  22470. buffer = webglObject.buffer;
  22471. // culling is overriden globally for all objects
  22472. // while rendering depth map
  22473. // need to deal with MeshFaceMaterial somehow
  22474. // in that case just use the first of material.materials for now
  22475. // (proper solution would require to break objects by materials
  22476. // similarly to regular rendering and then set corresponding
  22477. // depth materials per each chunk instead of just once per object)
  22478. objectMaterial = getObjectMaterial( object );
  22479. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22480. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22481. if ( object.customDepthMaterial ) {
  22482. material = object.customDepthMaterial;
  22483. } else if ( useSkinning ) {
  22484. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22485. } else if ( useMorphing ) {
  22486. material = _depthMaterialMorph;
  22487. } else {
  22488. material = _depthMaterial;
  22489. }
  22490. if ( buffer instanceof THREE.BufferGeometry ) {
  22491. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  22492. } else {
  22493. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  22494. }
  22495. }
  22496. }
  22497. // set matrices and render immediate objects
  22498. renderList = scene.__webglObjectsImmediate;
  22499. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22500. webglObject = renderList[ j ];
  22501. object = webglObject.object;
  22502. if ( object.visible && object.castShadow ) {
  22503. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  22504. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  22505. }
  22506. }
  22507. }
  22508. // restore GL state
  22509. var clearColor = _renderer.getClearColor(),
  22510. clearAlpha = _renderer.getClearAlpha();
  22511. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22512. _gl.enable( _gl.BLEND );
  22513. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  22514. _gl.cullFace( _gl.BACK );
  22515. }
  22516. };
  22517. function createVirtualLight( light, cascade ) {
  22518. var virtualLight = new THREE.DirectionalLight();
  22519. virtualLight.isVirtual = true;
  22520. virtualLight.onlyShadow = true;
  22521. virtualLight.castShadow = true;
  22522. virtualLight.shadowCameraNear = light.shadowCameraNear;
  22523. virtualLight.shadowCameraFar = light.shadowCameraFar;
  22524. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  22525. virtualLight.shadowCameraRight = light.shadowCameraRight;
  22526. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  22527. virtualLight.shadowCameraTop = light.shadowCameraTop;
  22528. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22529. virtualLight.shadowDarkness = light.shadowDarkness;
  22530. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22531. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  22532. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  22533. virtualLight.pointsWorld = [];
  22534. virtualLight.pointsFrustum = [];
  22535. var pointsWorld = virtualLight.pointsWorld,
  22536. pointsFrustum = virtualLight.pointsFrustum;
  22537. for ( var i = 0; i < 8; i ++ ) {
  22538. pointsWorld[ i ] = new THREE.Vector3();
  22539. pointsFrustum[ i ] = new THREE.Vector3();
  22540. }
  22541. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22542. var farZ = light.shadowCascadeFarZ[ cascade ];
  22543. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  22544. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  22545. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  22546. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  22547. pointsFrustum[ 4 ].set( -1, -1, farZ );
  22548. pointsFrustum[ 5 ].set( 1, -1, farZ );
  22549. pointsFrustum[ 6 ].set( -1, 1, farZ );
  22550. pointsFrustum[ 7 ].set( 1, 1, farZ );
  22551. return virtualLight;
  22552. }
  22553. // Synchronize virtual light with the original light
  22554. function updateVirtualLight( light, cascade ) {
  22555. var virtualLight = light.shadowCascadeArray[ cascade ];
  22556. virtualLight.position.copy( light.position );
  22557. virtualLight.target.position.copy( light.target.position );
  22558. virtualLight.lookAt( virtualLight.target );
  22559. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  22560. virtualLight.shadowDarkness = light.shadowDarkness;
  22561. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  22562. var nearZ = light.shadowCascadeNearZ[ cascade ];
  22563. var farZ = light.shadowCascadeFarZ[ cascade ];
  22564. var pointsFrustum = virtualLight.pointsFrustum;
  22565. pointsFrustum[ 0 ].z = nearZ;
  22566. pointsFrustum[ 1 ].z = nearZ;
  22567. pointsFrustum[ 2 ].z = nearZ;
  22568. pointsFrustum[ 3 ].z = nearZ;
  22569. pointsFrustum[ 4 ].z = farZ;
  22570. pointsFrustum[ 5 ].z = farZ;
  22571. pointsFrustum[ 6 ].z = farZ;
  22572. pointsFrustum[ 7 ].z = farZ;
  22573. }
  22574. // Fit shadow camera's ortho frustum to camera frustum
  22575. function updateShadowCamera( camera, light ) {
  22576. var shadowCamera = light.shadowCamera,
  22577. pointsFrustum = light.pointsFrustum,
  22578. pointsWorld = light.pointsWorld;
  22579. _min.set( Infinity, Infinity, Infinity );
  22580. _max.set( -Infinity, -Infinity, -Infinity );
  22581. for ( var i = 0; i < 8; i ++ ) {
  22582. var p = pointsWorld[ i ];
  22583. p.copy( pointsFrustum[ i ] );
  22584. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  22585. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  22586. if ( p.x < _min.x ) _min.x = p.x;
  22587. if ( p.x > _max.x ) _max.x = p.x;
  22588. if ( p.y < _min.y ) _min.y = p.y;
  22589. if ( p.y > _max.y ) _max.y = p.y;
  22590. if ( p.z < _min.z ) _min.z = p.z;
  22591. if ( p.z > _max.z ) _max.z = p.z;
  22592. }
  22593. shadowCamera.left = _min.x;
  22594. shadowCamera.right = _max.x;
  22595. shadowCamera.top = _max.y;
  22596. shadowCamera.bottom = _min.y;
  22597. // can't really fit near/far
  22598. //shadowCamera.near = _min.z;
  22599. //shadowCamera.far = _max.z;
  22600. shadowCamera.updateProjectionMatrix();
  22601. }
  22602. // For the moment just ignore objects that have multiple materials with different animation methods
  22603. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  22604. function getObjectMaterial( object ) {
  22605. return object.material instanceof THREE.MeshFaceMaterial
  22606. ? object.material.materials[ 0 ]
  22607. : object.material;
  22608. };
  22609. };
  22610. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  22611. /**
  22612. * @author mikael emtinger / http://gomo.se/
  22613. * @author alteredq / http://alteredqualia.com/
  22614. */
  22615. THREE.SpritePlugin = function () {
  22616. var _gl, _renderer, _texture;
  22617. var vertices, faces, vertexBuffer, elementBuffer;
  22618. var program, attributes, uniforms;
  22619. this.init = function ( renderer ) {
  22620. _gl = renderer.context;
  22621. _renderer = renderer;
  22622. vertices = new Float32Array( [
  22623. - 0.5, - 0.5, 0, 0,
  22624. 0.5, - 0.5, 1, 0,
  22625. 0.5, 0.5, 1, 1,
  22626. - 0.5, 0.5, 0, 1
  22627. ] );
  22628. faces = new Uint16Array( [
  22629. 0, 1, 2,
  22630. 0, 2, 3
  22631. ] );
  22632. vertexBuffer = _gl.createBuffer();
  22633. elementBuffer = _gl.createBuffer();
  22634. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22635. _gl.bufferData( _gl.ARRAY_BUFFER, vertices, _gl.STATIC_DRAW );
  22636. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22637. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faces, _gl.STATIC_DRAW );
  22638. program = createProgram();
  22639. attributes = {
  22640. position: _gl.getAttribLocation ( program, 'position' ),
  22641. uv: _gl.getAttribLocation ( program, 'uv' )
  22642. };
  22643. uniforms = {
  22644. uvOffset: _gl.getUniformLocation( program, 'uvOffset' ),
  22645. uvScale: _gl.getUniformLocation( program, 'uvScale' ),
  22646. rotation: _gl.getUniformLocation( program, 'rotation' ),
  22647. scale: _gl.getUniformLocation( program, 'scale' ),
  22648. color: _gl.getUniformLocation( program, 'color' ),
  22649. map: _gl.getUniformLocation( program, 'map' ),
  22650. opacity: _gl.getUniformLocation( program, 'opacity' ),
  22651. modelViewMatrix: _gl.getUniformLocation( program, 'modelViewMatrix' ),
  22652. projectionMatrix: _gl.getUniformLocation( program, 'projectionMatrix' ),
  22653. fogType: _gl.getUniformLocation( program, 'fogType' ),
  22654. fogDensity: _gl.getUniformLocation( program, 'fogDensity' ),
  22655. fogNear: _gl.getUniformLocation( program, 'fogNear' ),
  22656. fogFar: _gl.getUniformLocation( program, 'fogFar' ),
  22657. fogColor: _gl.getUniformLocation( program, 'fogColor' ),
  22658. alphaTest: _gl.getUniformLocation( program, 'alphaTest' )
  22659. };
  22660. var canvas = document.createElement( 'canvas' );
  22661. canvas.width = 8;
  22662. canvas.height = 8;
  22663. var context = canvas.getContext( '2d' );
  22664. context.fillStyle = '#ffffff';
  22665. context.fillRect( 0, 0, canvas.width, canvas.height );
  22666. _texture = new THREE.Texture( canvas );
  22667. _texture.needsUpdate = true;
  22668. };
  22669. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22670. var sprites = scene.__webglSprites,
  22671. nSprites = sprites.length;
  22672. if ( ! nSprites ) return;
  22673. // setup gl
  22674. _gl.useProgram( program );
  22675. _gl.enableVertexAttribArray( attributes.position );
  22676. _gl.enableVertexAttribArray( attributes.uv );
  22677. _gl.disable( _gl.CULL_FACE );
  22678. _gl.enable( _gl.BLEND );
  22679. _gl.bindBuffer( _gl.ARRAY_BUFFER, vertexBuffer );
  22680. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22681. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22682. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, elementBuffer );
  22683. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22684. _gl.activeTexture( _gl.TEXTURE0 );
  22685. _gl.uniform1i( uniforms.map, 0 );
  22686. var oldFogType = 0;
  22687. var sceneFogType = 0;
  22688. var fog = scene.fog;
  22689. if ( fog ) {
  22690. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22691. if ( fog instanceof THREE.Fog ) {
  22692. _gl.uniform1f( uniforms.fogNear, fog.near );
  22693. _gl.uniform1f( uniforms.fogFar, fog.far );
  22694. _gl.uniform1i( uniforms.fogType, 1 );
  22695. oldFogType = 1;
  22696. sceneFogType = 1;
  22697. } else if ( fog instanceof THREE.FogExp2 ) {
  22698. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22699. _gl.uniform1i( uniforms.fogType, 2 );
  22700. oldFogType = 2;
  22701. sceneFogType = 2;
  22702. }
  22703. } else {
  22704. _gl.uniform1i( uniforms.fogType, 0 );
  22705. oldFogType = 0;
  22706. sceneFogType = 0;
  22707. }
  22708. // update positions and sort
  22709. var i, sprite, material, fogType, scale = [];
  22710. for( i = 0; i < nSprites; i ++ ) {
  22711. sprite = sprites[ i ];
  22712. material = sprite.material;
  22713. if ( sprite.visible === false ) continue;
  22714. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22715. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22716. }
  22717. sprites.sort( painterSortStable );
  22718. // render all sprites
  22719. for( i = 0; i < nSprites; i ++ ) {
  22720. sprite = sprites[ i ];
  22721. if ( sprite.visible === false ) continue;
  22722. material = sprite.material;
  22723. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22724. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22725. scale[ 0 ] = sprite.scale.x;
  22726. scale[ 1 ] = sprite.scale.y;
  22727. if ( scene.fog && material.fog ) {
  22728. fogType = sceneFogType;
  22729. } else {
  22730. fogType = 0;
  22731. }
  22732. if ( oldFogType !== fogType ) {
  22733. _gl.uniform1i( uniforms.fogType, fogType );
  22734. oldFogType = fogType;
  22735. }
  22736. if ( material.map !== null ) {
  22737. _gl.uniform2f( uniforms.uvOffset, material.map.offset.x, material.map.offset.y );
  22738. _gl.uniform2f( uniforms.uvScale, material.map.repeat.x, material.map.repeat.y );
  22739. } else {
  22740. _gl.uniform2f( uniforms.uvOffset, 0, 0 );
  22741. _gl.uniform2f( uniforms.uvScale, 1, 1 );
  22742. }
  22743. _gl.uniform1f( uniforms.opacity, material.opacity );
  22744. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22745. _gl.uniform1f( uniforms.rotation, material.rotation );
  22746. _gl.uniform2fv( uniforms.scale, scale );
  22747. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22748. _renderer.setDepthTest( material.depthTest );
  22749. _renderer.setDepthWrite( material.depthWrite );
  22750. if ( material.map && material.map.image && material.map.image.width ) {
  22751. _renderer.setTexture( material.map, 0 );
  22752. } else {
  22753. _renderer.setTexture( _texture, 0 );
  22754. }
  22755. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22756. }
  22757. // restore gl
  22758. _gl.enable( _gl.CULL_FACE );
  22759. };
  22760. function createProgram () {
  22761. var program = _gl.createProgram();
  22762. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22763. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22764. _gl.shaderSource( vertexShader, [
  22765. 'precision ' + _renderer.getPrecision() + ' float;',
  22766. 'uniform mat4 modelViewMatrix;',
  22767. 'uniform mat4 projectionMatrix;',
  22768. 'uniform float rotation;',
  22769. 'uniform vec2 scale;',
  22770. 'uniform vec2 uvOffset;',
  22771. 'uniform vec2 uvScale;',
  22772. 'attribute vec2 position;',
  22773. 'attribute vec2 uv;',
  22774. 'varying vec2 vUV;',
  22775. 'void main() {',
  22776. 'vUV = uvOffset + uv * uvScale;',
  22777. 'vec2 alignedPosition = position * scale;',
  22778. 'vec2 rotatedPosition;',
  22779. 'rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y;',
  22780. 'rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y;',
  22781. 'vec4 finalPosition;',
  22782. 'finalPosition = modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );',
  22783. 'finalPosition.xy += rotatedPosition;',
  22784. 'finalPosition = projectionMatrix * finalPosition;',
  22785. 'gl_Position = finalPosition;',
  22786. '}'
  22787. ].join( '\n' ) );
  22788. _gl.shaderSource( fragmentShader, [
  22789. 'precision ' + _renderer.getPrecision() + ' float;',
  22790. 'uniform vec3 color;',
  22791. 'uniform sampler2D map;',
  22792. 'uniform float opacity;',
  22793. 'uniform int fogType;',
  22794. 'uniform vec3 fogColor;',
  22795. 'uniform float fogDensity;',
  22796. 'uniform float fogNear;',
  22797. 'uniform float fogFar;',
  22798. 'uniform float alphaTest;',
  22799. 'varying vec2 vUV;',
  22800. 'void main() {',
  22801. 'vec4 texture = texture2D( map, vUV );',
  22802. 'if ( texture.a < alphaTest ) discard;',
  22803. 'gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );',
  22804. 'if ( fogType > 0 ) {',
  22805. 'float depth = gl_FragCoord.z / gl_FragCoord.w;',
  22806. 'float fogFactor = 0.0;',
  22807. 'if ( fogType == 1 ) {',
  22808. 'fogFactor = smoothstep( fogNear, fogFar, depth );',
  22809. '} else {',
  22810. 'const float LOG2 = 1.442695;',
  22811. 'float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );',
  22812. 'fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );',
  22813. '}',
  22814. 'gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );',
  22815. '}',
  22816. '}'
  22817. ].join( '\n' ) );
  22818. _gl.compileShader( vertexShader );
  22819. _gl.compileShader( fragmentShader );
  22820. _gl.attachShader( program, vertexShader );
  22821. _gl.attachShader( program, fragmentShader );
  22822. _gl.linkProgram( program );
  22823. return program;
  22824. };
  22825. function painterSortStable ( a, b ) {
  22826. if ( a.z !== b.z ) {
  22827. return b.z - a.z;
  22828. } else {
  22829. return b.id - a.id;
  22830. }
  22831. };
  22832. };
  22833. /**
  22834. * @author alteredq / http://alteredqualia.com/
  22835. */
  22836. THREE.DepthPassPlugin = function () {
  22837. this.enabled = false;
  22838. this.renderTarget = null;
  22839. var _gl,
  22840. _renderer,
  22841. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22842. _frustum = new THREE.Frustum(),
  22843. _projScreenMatrix = new THREE.Matrix4();
  22844. this.init = function ( renderer ) {
  22845. _gl = renderer.context;
  22846. _renderer = renderer;
  22847. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22848. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22849. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22850. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22851. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22852. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22853. _depthMaterial._shadowPass = true;
  22854. _depthMaterialMorph._shadowPass = true;
  22855. _depthMaterialSkin._shadowPass = true;
  22856. _depthMaterialMorphSkin._shadowPass = true;
  22857. };
  22858. this.render = function ( scene, camera ) {
  22859. if ( ! this.enabled ) return;
  22860. this.update( scene, camera );
  22861. };
  22862. this.update = function ( scene, camera ) {
  22863. var i, il, j, jl, n,
  22864. program, buffer, material,
  22865. webglObject, object, light,
  22866. renderList,
  22867. fog = null;
  22868. // set GL state for depth map
  22869. _gl.clearColor( 1, 1, 1, 1 );
  22870. _gl.disable( _gl.BLEND );
  22871. _renderer.setDepthTest( true );
  22872. // update scene
  22873. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22874. // update camera matrices and frustum
  22875. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22876. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22877. _frustum.setFromMatrix( _projScreenMatrix );
  22878. // render depth map
  22879. _renderer.setRenderTarget( this.renderTarget );
  22880. _renderer.clear();
  22881. // set object matrices & frustum culling
  22882. renderList = scene.__webglObjects;
  22883. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22884. webglObject = renderList[ j ];
  22885. object = webglObject.object;
  22886. webglObject.render = false;
  22887. if ( object.visible ) {
  22888. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22889. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22890. webglObject.render = true;
  22891. }
  22892. }
  22893. }
  22894. // render regular objects
  22895. var objectMaterial, useMorphing, useSkinning;
  22896. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22897. webglObject = renderList[ j ];
  22898. if ( webglObject.render ) {
  22899. object = webglObject.object;
  22900. buffer = webglObject.buffer;
  22901. // todo: create proper depth material for particles
  22902. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22903. objectMaterial = getObjectMaterial( object );
  22904. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22905. useMorphing = object.geometry.morphTargets !== undefined && object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22906. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22907. if ( object.customDepthMaterial ) {
  22908. material = object.customDepthMaterial;
  22909. } else if ( useSkinning ) {
  22910. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22911. } else if ( useMorphing ) {
  22912. material = _depthMaterialMorph;
  22913. } else {
  22914. material = _depthMaterial;
  22915. }
  22916. if ( buffer instanceof THREE.BufferGeometry ) {
  22917. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22918. } else {
  22919. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22920. }
  22921. }
  22922. }
  22923. // set matrices and render immediate objects
  22924. renderList = scene.__webglObjectsImmediate;
  22925. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22926. webglObject = renderList[ j ];
  22927. object = webglObject.object;
  22928. if ( object.visible ) {
  22929. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22930. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22931. }
  22932. }
  22933. // restore GL state
  22934. var clearColor = _renderer.getClearColor(),
  22935. clearAlpha = _renderer.getClearAlpha();
  22936. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22937. _gl.enable( _gl.BLEND );
  22938. };
  22939. // For the moment just ignore objects that have multiple materials with different animation methods
  22940. // Only the first material will be taken into account for deciding which depth material to use
  22941. function getObjectMaterial( object ) {
  22942. return object.material instanceof THREE.MeshFaceMaterial
  22943. ? object.material.materials[ 0 ]
  22944. : object.material;
  22945. };
  22946. };
  22947. /**
  22948. * @author mikael emtinger / http://gomo.se/
  22949. */
  22950. THREE.ShaderFlares = {
  22951. 'lensFlareVertexTexture': {
  22952. vertexShader: [
  22953. "uniform lowp int renderType;",
  22954. "uniform vec3 screenPosition;",
  22955. "uniform vec2 scale;",
  22956. "uniform float rotation;",
  22957. "uniform sampler2D occlusionMap;",
  22958. "attribute vec2 position;",
  22959. "attribute vec2 uv;",
  22960. "varying vec2 vUV;",
  22961. "varying float vVisibility;",
  22962. "void main() {",
  22963. "vUV = uv;",
  22964. "vec2 pos = position;",
  22965. "if( renderType == 2 ) {",
  22966. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22967. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22968. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22969. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22970. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22971. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22972. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22973. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22974. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22975. "vVisibility = visibility.r / 9.0;",
  22976. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22977. "vVisibility *= visibility.b / 9.0;",
  22978. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22979. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22980. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22981. "}",
  22982. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22983. "}"
  22984. ].join( "\n" ),
  22985. fragmentShader: [
  22986. "uniform lowp int renderType;",
  22987. "uniform sampler2D map;",
  22988. "uniform float opacity;",
  22989. "uniform vec3 color;",
  22990. "varying vec2 vUV;",
  22991. "varying float vVisibility;",
  22992. "void main() {",
  22993. // pink square
  22994. "if( renderType == 0 ) {",
  22995. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22996. // restore
  22997. "} else if( renderType == 1 ) {",
  22998. "gl_FragColor = texture2D( map, vUV );",
  22999. // flare
  23000. "} else {",
  23001. "vec4 texture = texture2D( map, vUV );",
  23002. "texture.a *= opacity * vVisibility;",
  23003. "gl_FragColor = texture;",
  23004. "gl_FragColor.rgb *= color;",
  23005. "}",
  23006. "}"
  23007. ].join( "\n" )
  23008. },
  23009. 'lensFlare': {
  23010. vertexShader: [
  23011. "uniform lowp int renderType;",
  23012. "uniform vec3 screenPosition;",
  23013. "uniform vec2 scale;",
  23014. "uniform float rotation;",
  23015. "attribute vec2 position;",
  23016. "attribute vec2 uv;",
  23017. "varying vec2 vUV;",
  23018. "void main() {",
  23019. "vUV = uv;",
  23020. "vec2 pos = position;",
  23021. "if( renderType == 2 ) {",
  23022. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  23023. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  23024. "}",
  23025. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  23026. "}"
  23027. ].join( "\n" ),
  23028. fragmentShader: [
  23029. "precision mediump float;",
  23030. "uniform lowp int renderType;",
  23031. "uniform sampler2D map;",
  23032. "uniform sampler2D occlusionMap;",
  23033. "uniform float opacity;",
  23034. "uniform vec3 color;",
  23035. "varying vec2 vUV;",
  23036. "void main() {",
  23037. // pink square
  23038. "if( renderType == 0 ) {",
  23039. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  23040. // restore
  23041. "} else if( renderType == 1 ) {",
  23042. "gl_FragColor = texture2D( map, vUV );",
  23043. // flare
  23044. "} else {",
  23045. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  23046. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  23047. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  23048. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  23049. "visibility = ( 1.0 - visibility / 4.0 );",
  23050. "vec4 texture = texture2D( map, vUV );",
  23051. "texture.a *= opacity * visibility;",
  23052. "gl_FragColor = texture;",
  23053. "gl_FragColor.rgb *= color;",
  23054. "}",
  23055. "}"
  23056. ].join( "\n" )
  23057. }
  23058. };