three.js 819 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720
  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 = THREE || { REVISION: '59dev' };
  7. self.console = self.console || {
  8. info: function () {},
  9. log: function () {},
  10. debug: function () {},
  11. warn: function () {},
  12. error: function () {}
  13. };
  14. self.Int32Array = self.Int32Array || Array;
  15. self.Float32Array = self.Float32Array || Array;
  16. String.prototype.trim = String.prototype.trim || function () {
  17. return this.replace( /^\s+|\s+$/g, '' );
  18. };
  19. // based on https://github.com/documentcloud/underscore/blob/bf657be243a075b5e72acc8a83e6f12a564d8f55/underscore.js#L767
  20. THREE.extend = function ( obj, source ) {
  21. // ECMAScript5 compatibility based on: http://www.nczonline.net/blog/2012/12/11/are-your-mixins-ecmascript-5-compatible/
  22. if ( Object.keys ) {
  23. var keys = Object.keys( source );
  24. for (var i = 0, il = keys.length; i < il; i++) {
  25. var prop = keys[i];
  26. Object.defineProperty( obj, prop, Object.getOwnPropertyDescriptor( source, prop ) );
  27. }
  28. } else {
  29. var safeHasOwnProperty = {}.hasOwnProperty;
  30. for ( var prop in source ) {
  31. if ( safeHasOwnProperty.call( source, prop ) ) {
  32. obj[prop] = source[prop];
  33. }
  34. }
  35. }
  36. return obj;
  37. };
  38. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  39. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  40. // requestAnimationFrame polyfill by Erik Möller
  41. // fixes from Paul Irish and Tino Zijdel
  42. // using 'self' instead of 'window' for compatibility with both NodeJS and IE10.
  43. ( function () {
  44. var lastTime = 0;
  45. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  46. for ( var x = 0; x < vendors.length && !self.requestAnimationFrame; ++ x ) {
  47. self.requestAnimationFrame = self[ vendors[ x ] + 'RequestAnimationFrame' ];
  48. self.cancelAnimationFrame = self[ vendors[ x ] + 'CancelAnimationFrame' ] || self[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  49. }
  50. if ( self.requestAnimationFrame === undefined && self['setTimeout'] !== undefined ) {
  51. self.requestAnimationFrame = function ( callback ) {
  52. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  53. var id = self.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  54. lastTime = currTime + timeToCall;
  55. return id;
  56. };
  57. }
  58. if( self.cancelAnimationFrame === undefined && self['clearTimeout'] !== undefined ) {
  59. self.cancelAnimationFrame = function ( id ) { self.clearTimeout( id ) };
  60. }
  61. }() );
  62. // GL STATE CONSTANTS
  63. THREE.CullFaceNone = 0;
  64. THREE.CullFaceBack = 1;
  65. THREE.CullFaceFront = 2;
  66. THREE.CullFaceFrontBack = 3;
  67. THREE.FrontFaceDirectionCW = 0;
  68. THREE.FrontFaceDirectionCCW = 1;
  69. // SHADOWING TYPES
  70. THREE.BasicShadowMap = 0;
  71. THREE.PCFShadowMap = 1;
  72. THREE.PCFSoftShadowMap = 2;
  73. // MATERIAL CONSTANTS
  74. // side
  75. THREE.FrontSide = 0;
  76. THREE.BackSide = 1;
  77. THREE.DoubleSide = 2;
  78. // shading
  79. THREE.NoShading = 0;
  80. THREE.FlatShading = 1;
  81. THREE.SmoothShading = 2;
  82. // colors
  83. THREE.NoColors = 0;
  84. THREE.FaceColors = 1;
  85. THREE.VertexColors = 2;
  86. // blending modes
  87. THREE.NoBlending = 0;
  88. THREE.NormalBlending = 1;
  89. THREE.AdditiveBlending = 2;
  90. THREE.SubtractiveBlending = 3;
  91. THREE.MultiplyBlending = 4;
  92. THREE.CustomBlending = 5;
  93. // custom blending equations
  94. // (numbers start from 100 not to clash with other
  95. // mappings to OpenGL constants defined in Texture.js)
  96. THREE.AddEquation = 100;
  97. THREE.SubtractEquation = 101;
  98. THREE.ReverseSubtractEquation = 102;
  99. // custom blending destination factors
  100. THREE.ZeroFactor = 200;
  101. THREE.OneFactor = 201;
  102. THREE.SrcColorFactor = 202;
  103. THREE.OneMinusSrcColorFactor = 203;
  104. THREE.SrcAlphaFactor = 204;
  105. THREE.OneMinusSrcAlphaFactor = 205;
  106. THREE.DstAlphaFactor = 206;
  107. THREE.OneMinusDstAlphaFactor = 207;
  108. // custom blending source factors
  109. //THREE.ZeroFactor = 200;
  110. //THREE.OneFactor = 201;
  111. //THREE.SrcAlphaFactor = 204;
  112. //THREE.OneMinusSrcAlphaFactor = 205;
  113. //THREE.DstAlphaFactor = 206;
  114. //THREE.OneMinusDstAlphaFactor = 207;
  115. THREE.DstColorFactor = 208;
  116. THREE.OneMinusDstColorFactor = 209;
  117. THREE.SrcAlphaSaturateFactor = 210;
  118. // TEXTURE CONSTANTS
  119. THREE.MultiplyOperation = 0;
  120. THREE.MixOperation = 1;
  121. THREE.AddOperation = 2;
  122. // Mapping modes
  123. THREE.UVMapping = function () {};
  124. THREE.CubeReflectionMapping = function () {};
  125. THREE.CubeRefractionMapping = function () {};
  126. THREE.SphericalReflectionMapping = function () {};
  127. THREE.SphericalRefractionMapping = function () {};
  128. // Wrapping modes
  129. THREE.RepeatWrapping = 1000;
  130. THREE.ClampToEdgeWrapping = 1001;
  131. THREE.MirroredRepeatWrapping = 1002;
  132. // Filters
  133. THREE.NearestFilter = 1003;
  134. THREE.NearestMipMapNearestFilter = 1004;
  135. THREE.NearestMipMapLinearFilter = 1005;
  136. THREE.LinearFilter = 1006;
  137. THREE.LinearMipMapNearestFilter = 1007;
  138. THREE.LinearMipMapLinearFilter = 1008;
  139. // Data types
  140. THREE.UnsignedByteType = 1009;
  141. THREE.ByteType = 1010;
  142. THREE.ShortType = 1011;
  143. THREE.UnsignedShortType = 1012;
  144. THREE.IntType = 1013;
  145. THREE.UnsignedIntType = 1014;
  146. THREE.FloatType = 1015;
  147. // Pixel types
  148. //THREE.UnsignedByteType = 1009;
  149. THREE.UnsignedShort4444Type = 1016;
  150. THREE.UnsignedShort5551Type = 1017;
  151. THREE.UnsignedShort565Type = 1018;
  152. // Pixel formats
  153. THREE.AlphaFormat = 1019;
  154. THREE.RGBFormat = 1020;
  155. THREE.RGBAFormat = 1021;
  156. THREE.LuminanceFormat = 1022;
  157. THREE.LuminanceAlphaFormat = 1023;
  158. // Compressed texture formats
  159. THREE.RGB_S3TC_DXT1_Format = 2001;
  160. THREE.RGBA_S3TC_DXT1_Format = 2002;
  161. THREE.RGBA_S3TC_DXT3_Format = 2003;
  162. THREE.RGBA_S3TC_DXT5_Format = 2004;
  163. /*
  164. // Potential future PVRTC compressed texture formats
  165. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  166. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  167. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  168. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  169. */
  170. /**
  171. * @author mrdoob / http://mrdoob.com/
  172. */
  173. THREE.Color = function ( value ) {
  174. if ( value !== undefined ) this.set( value );
  175. return this;
  176. };
  177. THREE.Color.prototype = {
  178. constructor: THREE.Color,
  179. r: 1, g: 1, b: 1,
  180. set: function ( value ) {
  181. if ( value instanceof THREE.Color ) {
  182. this.copy( value );
  183. } else if ( typeof value === 'number' ) {
  184. this.setHex( value );
  185. } else if ( typeof value === 'string' ) {
  186. this.setStyle( value );
  187. }
  188. return this;
  189. },
  190. setHex: function ( hex ) {
  191. hex = Math.floor( hex );
  192. this.r = ( hex >> 16 & 255 ) / 255;
  193. this.g = ( hex >> 8 & 255 ) / 255;
  194. this.b = ( hex & 255 ) / 255;
  195. return this;
  196. },
  197. setRGB: function ( r, g, b ) {
  198. this.r = r;
  199. this.g = g;
  200. this.b = b;
  201. return this;
  202. },
  203. setHSL: function ( h, s, l ) {
  204. // h,s,l ranges are in 0.0 - 1.0
  205. if ( s === 0 ) {
  206. this.r = this.g = this.b = l;
  207. } else {
  208. var hue2rgb = function ( p, q, t ) {
  209. if ( t < 0 ) t += 1;
  210. if ( t > 1 ) t -= 1;
  211. if ( t < 1 / 6 ) return p + ( q - p ) * 6 * t;
  212. if ( t < 1 / 2 ) return q;
  213. if ( t < 2 / 3 ) return p + ( q - p ) * 6 * ( 2 / 3 - t );
  214. return p;
  215. };
  216. var p = l <= 0.5 ? l * ( 1 + s ) : l + s - ( l * s );
  217. var q = ( 2 * l ) - p;
  218. this.r = hue2rgb( q, p, h + 1 / 3 );
  219. this.g = hue2rgb( q, p, h );
  220. this.b = hue2rgb( q, p, h - 1 / 3 );
  221. }
  222. return this;
  223. },
  224. setStyle: function ( style ) {
  225. // rgb(255,0,0)
  226. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  227. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  228. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  229. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  230. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  231. return this;
  232. }
  233. // rgb(100%,0%,0%)
  234. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  235. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  236. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  237. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  238. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  239. return this;
  240. }
  241. // #ff0000
  242. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  243. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  244. this.setHex( parseInt( color[ 1 ], 16 ) );
  245. return this;
  246. }
  247. // #f00
  248. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  249. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  250. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  251. return this;
  252. }
  253. // red
  254. if ( /^(\w+)$/i.test( style ) ) {
  255. this.setHex( THREE.ColorKeywords[ style ] );
  256. return this;
  257. }
  258. },
  259. copy: function ( color ) {
  260. this.r = color.r;
  261. this.g = color.g;
  262. this.b = color.b;
  263. return this;
  264. },
  265. copyGammaToLinear: function ( color ) {
  266. this.r = color.r * color.r;
  267. this.g = color.g * color.g;
  268. this.b = color.b * color.b;
  269. return this;
  270. },
  271. copyLinearToGamma: function ( color ) {
  272. this.r = Math.sqrt( color.r );
  273. this.g = Math.sqrt( color.g );
  274. this.b = Math.sqrt( color.b );
  275. return this;
  276. },
  277. convertGammaToLinear: function () {
  278. var r = this.r, g = this.g, b = this.b;
  279. this.r = r * r;
  280. this.g = g * g;
  281. this.b = b * b;
  282. return this;
  283. },
  284. convertLinearToGamma: function () {
  285. this.r = Math.sqrt( this.r );
  286. this.g = Math.sqrt( this.g );
  287. this.b = Math.sqrt( this.b );
  288. return this;
  289. },
  290. getHex: function () {
  291. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  292. },
  293. getHexString: function () {
  294. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  295. },
  296. getHSL: function () {
  297. var hsl = { h: 0, s: 0, l: 0 };
  298. return function () {
  299. // h,s,l ranges are in 0.0 - 1.0
  300. var r = this.r, g = this.g, b = this.b;
  301. var max = Math.max( r, g, b );
  302. var min = Math.min( r, g, b );
  303. var hue, saturation;
  304. var lightness = ( min + max ) / 2.0;
  305. if ( min === max ) {
  306. hue = 0;
  307. saturation = 0;
  308. } else {
  309. var delta = max - min;
  310. saturation = lightness <= 0.5 ? delta / ( max + min ) : delta / ( 2 - max - min );
  311. switch ( max ) {
  312. case r: hue = ( g - b ) / delta + ( g < b ? 6 : 0 ); break;
  313. case g: hue = ( b - r ) / delta + 2; break;
  314. case b: hue = ( r - g ) / delta + 4; break;
  315. }
  316. hue /= 6;
  317. }
  318. hsl.h = hue;
  319. hsl.s = saturation;
  320. hsl.l = lightness;
  321. return hsl;
  322. };
  323. }(),
  324. getStyle: function () {
  325. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  326. },
  327. offsetHSL: function ( h, s, l ) {
  328. var hsl = this.getHSL();
  329. hsl.h += h; hsl.s += s; hsl.l += l;
  330. this.setHSL( hsl.h, hsl.s, hsl.l );
  331. return this;
  332. },
  333. add: function ( color ) {
  334. this.r += color.r;
  335. this.g += color.g;
  336. this.b += color.b;
  337. return this;
  338. },
  339. addColors: function ( color1, color2 ) {
  340. this.r = color1.r + color2.r;
  341. this.g = color1.g + color2.g;
  342. this.b = color1.b + color2.b;
  343. return this;
  344. },
  345. addScalar: function ( s ) {
  346. this.r += s;
  347. this.g += s;
  348. this.b += s;
  349. return this;
  350. },
  351. multiply: function ( color ) {
  352. this.r *= color.r;
  353. this.g *= color.g;
  354. this.b *= color.b;
  355. return this;
  356. },
  357. multiplyScalar: function ( s ) {
  358. this.r *= s;
  359. this.g *= s;
  360. this.b *= s;
  361. return this;
  362. },
  363. lerp: function ( color, alpha ) {
  364. this.r += ( color.r - this.r ) * alpha;
  365. this.g += ( color.g - this.g ) * alpha;
  366. this.b += ( color.b - this.b ) * alpha;
  367. return this;
  368. },
  369. equals: function ( c ) {
  370. return ( c.r === this.r ) && ( c.g === this.g ) && ( c.b === this.b );
  371. },
  372. clone: function () {
  373. return new THREE.Color().setRGB( this.r, this.g, this.b );
  374. }
  375. };
  376. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF,
  377. "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2,
  378. "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50,
  379. "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B,
  380. "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B,
  381. "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F,
  382. "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3,
  383. "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222,
  384. "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700,
  385. "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4,
  386. "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00,
  387. "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3,
  388. "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA,
  389. "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32,
  390. "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3,
  391. "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC,
  392. "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD,
  393. "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6,
  394. "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9,
  395. "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F,
  396. "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE,
  397. "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA,
  398. "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0,
  399. "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  400. /**
  401. * @author mikael emtinger / http://gomo.se/
  402. * @author alteredq / http://alteredqualia.com/
  403. * @author WestLangley / http://github.com/WestLangley
  404. * @author bhouston / http://exocortex.com
  405. */
  406. THREE.Quaternion = function ( x, y, z, w ) {
  407. this._x = x || 0;
  408. this._y = y || 0;
  409. this._z = z || 0;
  410. this._w = ( w !== undefined ) ? w : 1;
  411. };
  412. THREE.Quaternion.prototype = {
  413. constructor: THREE.Quaternion,
  414. _x: 0,_y: 0, _z: 0, _w: 0,
  415. _euler: undefined,
  416. _updateEuler: function ( callback ) {
  417. if ( this._euler !== undefined ) {
  418. this._euler.setFromQuaternion( this, undefined, false );
  419. }
  420. },
  421. get x () {
  422. return this._x;
  423. },
  424. set x ( value ) {
  425. this._x = value;
  426. this._updateEuler();
  427. },
  428. get y () {
  429. return this._y;
  430. },
  431. set y ( value ) {
  432. this._y = value;
  433. this._updateEuler();
  434. },
  435. get z () {
  436. return this._z;
  437. },
  438. set z ( value ) {
  439. this._z = value;
  440. this._updateEuler();
  441. },
  442. get w () {
  443. return this._w;
  444. },
  445. set w ( value ) {
  446. this._w = value;
  447. this._updateEuler();
  448. },
  449. set: function ( x, y, z, w ) {
  450. this._x = x;
  451. this._y = y;
  452. this._z = z;
  453. this._w = w;
  454. this._updateEuler();
  455. return this;
  456. },
  457. copy: function ( quaternion ) {
  458. this._x = quaternion._x;
  459. this._y = quaternion._y;
  460. this._z = quaternion._z;
  461. this._w = quaternion._w;
  462. this._updateEuler();
  463. return this;
  464. },
  465. setFromEuler: function ( euler, update ) {
  466. if ( typeof euler['order'] === undefined ) {
  467. console.error( 'ERROR: Quaternion\'s .setFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  468. }
  469. // http://www.mathworks.com/matlabcentral/fileexchange/
  470. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  471. // content/SpinCalc.m
  472. var c1 = Math.cos( euler._x / 2 );
  473. var c2 = Math.cos( euler._y / 2 );
  474. var c3 = Math.cos( euler._z / 2 );
  475. var s1 = Math.sin( euler._x / 2 );
  476. var s2 = Math.sin( euler._y / 2 );
  477. var s3 = Math.sin( euler._z / 2 );
  478. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  479. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  480. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  481. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  482. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  483. } else if ( euler.order === 'YXZ' ) {
  484. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  485. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  486. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  487. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  488. } else if ( euler.order === 'ZXY' ) {
  489. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  490. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  491. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  492. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  493. } else if ( euler.order === 'ZYX' ) {
  494. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  495. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  496. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  497. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  498. } else if ( euler.order === 'YZX' ) {
  499. this._x = s1 * c2 * c3 + c1 * s2 * s3;
  500. this._y = c1 * s2 * c3 + s1 * c2 * s3;
  501. this._z = c1 * c2 * s3 - s1 * s2 * c3;
  502. this._w = c1 * c2 * c3 - s1 * s2 * s3;
  503. } else if ( euler.order === 'XZY' ) {
  504. this._x = s1 * c2 * c3 - c1 * s2 * s3;
  505. this._y = c1 * s2 * c3 - s1 * c2 * s3;
  506. this._z = c1 * c2 * s3 + s1 * s2 * c3;
  507. this._w = c1 * c2 * c3 + s1 * s2 * s3;
  508. }
  509. if ( update !== false ) this._updateEuler();
  510. return this;
  511. },
  512. setFromAxisAngle: function ( axis, angle ) {
  513. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  514. // axis have to be normalized
  515. var halfAngle = angle / 2, s = Math.sin( halfAngle );
  516. this._x = axis.x * s;
  517. this._y = axis.y * s;
  518. this._z = axis.z * s;
  519. this._w = Math.cos( halfAngle );
  520. this._updateEuler();
  521. return this;
  522. },
  523. setFromRotationMatrix: function ( m ) {
  524. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  525. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  526. var te = m.elements,
  527. m11 = te[0], m12 = te[4], m13 = te[8],
  528. m21 = te[1], m22 = te[5], m23 = te[9],
  529. m31 = te[2], m32 = te[6], m33 = te[10],
  530. trace = m11 + m22 + m33,
  531. s;
  532. if ( trace > 0 ) {
  533. s = 0.5 / Math.sqrt( trace + 1.0 );
  534. this._w = 0.25 / s;
  535. this._x = ( m32 - m23 ) * s;
  536. this._y = ( m13 - m31 ) * s;
  537. this._z = ( m21 - m12 ) * s;
  538. } else if ( m11 > m22 && m11 > m33 ) {
  539. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  540. this._w = (m32 - m23 ) / s;
  541. this._x = 0.25 * s;
  542. this._y = (m12 + m21 ) / s;
  543. this._z = (m13 + m31 ) / s;
  544. } else if ( m22 > m33 ) {
  545. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  546. this._w = (m13 - m31 ) / s;
  547. this._x = (m12 + m21 ) / s;
  548. this._y = 0.25 * s;
  549. this._z = (m23 + m32 ) / s;
  550. } else {
  551. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  552. this._w = ( m21 - m12 ) / s;
  553. this._x = ( m13 + m31 ) / s;
  554. this._y = ( m23 + m32 ) / s;
  555. this._z = 0.25 * s;
  556. }
  557. this._updateEuler();
  558. return this;
  559. },
  560. inverse: function () {
  561. this.conjugate().normalize();
  562. return this;
  563. },
  564. conjugate: function () {
  565. this._x *= -1;
  566. this._y *= -1;
  567. this._z *= -1;
  568. this._updateEuler();
  569. return this;
  570. },
  571. lengthSq: function () {
  572. return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w;
  573. },
  574. length: function () {
  575. return Math.sqrt( this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w );
  576. },
  577. normalize: function () {
  578. var l = this.length();
  579. if ( l === 0 ) {
  580. this._x = 0;
  581. this._y = 0;
  582. this._z = 0;
  583. this._w = 1;
  584. } else {
  585. l = 1 / l;
  586. this._x = this._x * l;
  587. this._y = this._y * l;
  588. this._z = this._z * l;
  589. this._w = this._w * l;
  590. }
  591. return this;
  592. },
  593. multiply: function ( q, p ) {
  594. if ( p !== undefined ) {
  595. console.warn( 'DEPRECATED: Quaternion\'s .multiply() now only accepts one argument. Use .multiplyQuaternions( a, b ) instead.' );
  596. return this.multiplyQuaternions( q, p );
  597. }
  598. return this.multiplyQuaternions( this, q );
  599. },
  600. multiplyQuaternions: function ( a, b ) {
  601. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  602. var qax = a._x, qay = a._y, qaz = a._z, qaw = a._w;
  603. var qbx = b._x, qby = b._y, qbz = b._z, qbw = b._w;
  604. this._x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  605. this._y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  606. this._z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  607. this._w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  608. this._updateEuler();
  609. return this;
  610. },
  611. multiplyVector3: function ( vector ) {
  612. console.warn( 'DEPRECATED: Quaternion\'s .multiplyVector3() has been removed. Use is now vector.applyQuaternion( quaternion ) instead.' );
  613. return vector.applyQuaternion( this );
  614. },
  615. slerp: function ( qb, t ) {
  616. var x = this._x, y = this._y, z = this._z, w = this._w;
  617. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  618. var cosHalfTheta = w * qb._w + x * qb._x + y * qb._y + z * qb._z;
  619. if ( cosHalfTheta < 0 ) {
  620. this._w = -qb._w;
  621. this._x = -qb._x;
  622. this._y = -qb._y;
  623. this._z = -qb._z;
  624. cosHalfTheta = -cosHalfTheta;
  625. } else {
  626. this.copy( qb );
  627. }
  628. if ( cosHalfTheta >= 1.0 ) {
  629. this._w = w;
  630. this._x = x;
  631. this._y = y;
  632. this._z = z;
  633. return this;
  634. }
  635. var halfTheta = Math.acos( cosHalfTheta );
  636. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  637. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  638. this._w = 0.5 * ( w + this._w );
  639. this._x = 0.5 * ( x + this._x );
  640. this._y = 0.5 * ( y + this._y );
  641. this._z = 0.5 * ( z + this._z );
  642. return this;
  643. }
  644. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  645. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  646. this._w = ( w * ratioA + this._w * ratioB );
  647. this._x = ( x * ratioA + this._x * ratioB );
  648. this._y = ( y * ratioA + this._y * ratioB );
  649. this._z = ( z * ratioA + this._z * ratioB );
  650. this._updateEuler();
  651. return this;
  652. },
  653. equals: function ( quaternion ) {
  654. return ( quaternion._x === this._x ) && ( quaternion._y === this._y ) && ( quaternion._z === this._z ) && ( quaternion._w === this._w );
  655. },
  656. fromArray: function ( array ) {
  657. this._x = array[ 0 ];
  658. this._y = array[ 1 ];
  659. this._z = array[ 2 ];
  660. this._w = array[ 3 ];
  661. this._updateEuler();
  662. return this;
  663. },
  664. toArray: function () {
  665. return [ this._x, this._y, this._z, this._w ];
  666. },
  667. clone: function () {
  668. return new THREE.Quaternion( this._x, this._y, this._z, this._w );
  669. }
  670. };
  671. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  672. return qm.copy( qa ).slerp( qb, t );
  673. }
  674. /**
  675. * @author mrdoob / http://mrdoob.com/
  676. * @author philogb / http://blog.thejit.org/
  677. * @author egraether / http://egraether.com/
  678. * @author zz85 / http://www.lab4games.net/zz85/blog
  679. */
  680. THREE.Vector2 = function ( x, y ) {
  681. this.x = x || 0;
  682. this.y = y || 0;
  683. };
  684. THREE.Vector2.prototype = {
  685. constructor: THREE.Vector2,
  686. set: function ( x, y ) {
  687. this.x = x;
  688. this.y = y;
  689. return this;
  690. },
  691. setX: function ( x ) {
  692. this.x = x;
  693. return this;
  694. },
  695. setY: function ( y ) {
  696. this.y = y;
  697. return this;
  698. },
  699. setComponent: function ( index, value ) {
  700. switch ( index ) {
  701. case 0: this.x = value; break;
  702. case 1: this.y = value; break;
  703. default: throw new Error( "index is out of range: " + index );
  704. }
  705. },
  706. getComponent: function ( index ) {
  707. switch ( index ) {
  708. case 0: return this.x;
  709. case 1: return this.y;
  710. default: throw new Error( "index is out of range: " + index );
  711. }
  712. },
  713. copy: function ( v ) {
  714. this.x = v.x;
  715. this.y = v.y;
  716. return this;
  717. },
  718. add: function ( v, w ) {
  719. if ( w !== undefined ) {
  720. console.warn( 'DEPRECATED: Vector2\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  721. return this.addVectors( v, w );
  722. }
  723. this.x += v.x;
  724. this.y += v.y;
  725. return this;
  726. },
  727. addVectors: function ( a, b ) {
  728. this.x = a.x + b.x;
  729. this.y = a.y + b.y;
  730. return this;
  731. },
  732. addScalar: function ( s ) {
  733. this.x += s;
  734. this.y += s;
  735. return this;
  736. },
  737. sub: function ( v, w ) {
  738. if ( w !== undefined ) {
  739. console.warn( 'DEPRECATED: Vector2\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  740. return this.subVectors( v, w );
  741. }
  742. this.x -= v.x;
  743. this.y -= v.y;
  744. return this;
  745. },
  746. subVectors: function ( a, b ) {
  747. this.x = a.x - b.x;
  748. this.y = a.y - b.y;
  749. return this;
  750. },
  751. multiplyScalar: function ( s ) {
  752. this.x *= s;
  753. this.y *= s;
  754. return this;
  755. },
  756. divideScalar: function ( s ) {
  757. if ( s !== 0 ) {
  758. this.x /= s;
  759. this.y /= s;
  760. } else {
  761. this.set( 0, 0 );
  762. }
  763. return this;
  764. },
  765. min: function ( v ) {
  766. if ( this.x > v.x ) {
  767. this.x = v.x;
  768. }
  769. if ( this.y > v.y ) {
  770. this.y = v.y;
  771. }
  772. return this;
  773. },
  774. max: function ( v ) {
  775. if ( this.x < v.x ) {
  776. this.x = v.x;
  777. }
  778. if ( this.y < v.y ) {
  779. this.y = v.y;
  780. }
  781. return this;
  782. },
  783. clamp: function ( min, max ) {
  784. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  785. if ( this.x < min.x ) {
  786. this.x = min.x;
  787. } else if ( this.x > max.x ) {
  788. this.x = max.x;
  789. }
  790. if ( this.y < min.y ) {
  791. this.y = min.y;
  792. } else if ( this.y > max.y ) {
  793. this.y = max.y;
  794. }
  795. return this;
  796. },
  797. negate: function() {
  798. return this.multiplyScalar( - 1 );
  799. },
  800. dot: function ( v ) {
  801. return this.x * v.x + this.y * v.y;
  802. },
  803. lengthSq: function () {
  804. return this.x * this.x + this.y * this.y;
  805. },
  806. length: function () {
  807. return Math.sqrt( this.x * this.x + this.y * this.y );
  808. },
  809. normalize: function () {
  810. return this.divideScalar( this.length() );
  811. },
  812. distanceTo: function ( v ) {
  813. return Math.sqrt( this.distanceToSquared( v ) );
  814. },
  815. distanceToSquared: function ( v ) {
  816. var dx = this.x - v.x, dy = this.y - v.y;
  817. return dx * dx + dy * dy;
  818. },
  819. setLength: function ( l ) {
  820. var oldLength = this.length();
  821. if ( oldLength !== 0 && l !== oldLength ) {
  822. this.multiplyScalar( l / oldLength );
  823. }
  824. return this;
  825. },
  826. lerp: function ( v, alpha ) {
  827. this.x += ( v.x - this.x ) * alpha;
  828. this.y += ( v.y - this.y ) * alpha;
  829. return this;
  830. },
  831. equals: function( v ) {
  832. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  833. },
  834. fromArray: function ( array ) {
  835. this.x = array[ 0 ];
  836. this.y = array[ 1 ];
  837. return this;
  838. },
  839. toArray: function () {
  840. return [ this.x, this.y ];
  841. },
  842. clone: function () {
  843. return new THREE.Vector2( this.x, this.y );
  844. }
  845. };
  846. /**
  847. * @author mrdoob / http://mrdoob.com/
  848. * @author *kile / http://kile.stravaganza.org/
  849. * @author philogb / http://blog.thejit.org/
  850. * @author mikael emtinger / http://gomo.se/
  851. * @author egraether / http://egraether.com/
  852. * @author WestLangley / http://github.com/WestLangley
  853. */
  854. THREE.Vector3 = function ( x, y, z ) {
  855. this.x = x || 0;
  856. this.y = y || 0;
  857. this.z = z || 0;
  858. };
  859. THREE.Vector3.prototype = {
  860. constructor: THREE.Vector3,
  861. set: function ( x, y, z ) {
  862. this.x = x;
  863. this.y = y;
  864. this.z = z;
  865. return this;
  866. },
  867. setX: function ( x ) {
  868. this.x = x;
  869. return this;
  870. },
  871. setY: function ( y ) {
  872. this.y = y;
  873. return this;
  874. },
  875. setZ: function ( z ) {
  876. this.z = z;
  877. return this;
  878. },
  879. setComponent: function ( index, value ) {
  880. switch ( index ) {
  881. case 0: this.x = value; break;
  882. case 1: this.y = value; break;
  883. case 2: this.z = value; break;
  884. default: throw new Error( "index is out of range: " + index );
  885. }
  886. },
  887. getComponent: function ( index ) {
  888. switch ( index ) {
  889. case 0: return this.x;
  890. case 1: return this.y;
  891. case 2: return this.z;
  892. default: throw new Error( "index is out of range: " + index );
  893. }
  894. },
  895. copy: function ( v ) {
  896. this.x = v.x;
  897. this.y = v.y;
  898. this.z = v.z;
  899. return this;
  900. },
  901. add: function ( v, w ) {
  902. if ( w !== undefined ) {
  903. console.warn( 'DEPRECATED: Vector3\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  904. return this.addVectors( v, w );
  905. }
  906. this.x += v.x;
  907. this.y += v.y;
  908. this.z += v.z;
  909. return this;
  910. },
  911. addScalar: function ( s ) {
  912. this.x += s;
  913. this.y += s;
  914. this.z += s;
  915. return this;
  916. },
  917. addVectors: function ( a, b ) {
  918. this.x = a.x + b.x;
  919. this.y = a.y + b.y;
  920. this.z = a.z + b.z;
  921. return this;
  922. },
  923. sub: function ( v, w ) {
  924. if ( w !== undefined ) {
  925. console.warn( 'DEPRECATED: Vector3\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  926. return this.subVectors( v, w );
  927. }
  928. this.x -= v.x;
  929. this.y -= v.y;
  930. this.z -= v.z;
  931. return this;
  932. },
  933. subVectors: function ( a, b ) {
  934. this.x = a.x - b.x;
  935. this.y = a.y - b.y;
  936. this.z = a.z - b.z;
  937. return this;
  938. },
  939. multiply: function ( v, w ) {
  940. if ( w !== undefined ) {
  941. console.warn( 'DEPRECATED: Vector3\'s .multiply() now only accepts one argument. Use .multiplyVectors( a, b ) instead.' );
  942. return this.multiplyVectors( v, w );
  943. }
  944. this.x *= v.x;
  945. this.y *= v.y;
  946. this.z *= v.z;
  947. return this;
  948. },
  949. multiplyScalar: function ( s ) {
  950. this.x *= s;
  951. this.y *= s;
  952. this.z *= s;
  953. return this;
  954. },
  955. multiplyVectors: function ( a, b ) {
  956. this.x = a.x * b.x;
  957. this.y = a.y * b.y;
  958. this.z = a.z * b.z;
  959. return this;
  960. },
  961. applyMatrix3: function ( m ) {
  962. var x = this.x;
  963. var y = this.y;
  964. var z = this.z;
  965. var e = m.elements;
  966. this.x = e[0] * x + e[3] * y + e[6] * z;
  967. this.y = e[1] * x + e[4] * y + e[7] * z;
  968. this.z = e[2] * x + e[5] * y + e[8] * z;
  969. return this;
  970. },
  971. applyMatrix4: function ( m ) {
  972. // input: THREE.Matrix4 affine matrix
  973. var x = this.x, y = this.y, z = this.z;
  974. var e = m.elements;
  975. this.x = e[0] * x + e[4] * y + e[8] * z + e[12];
  976. this.y = e[1] * x + e[5] * y + e[9] * z + e[13];
  977. this.z = e[2] * x + e[6] * y + e[10] * z + e[14];
  978. return this;
  979. },
  980. applyProjection: function ( m ) {
  981. // input: THREE.Matrix4 projection matrix
  982. var x = this.x, y = this.y, z = this.z;
  983. var e = m.elements;
  984. var d = 1 / ( e[3] * x + e[7] * y + e[11] * z + e[15] ); // perspective divide
  985. this.x = ( e[0] * x + e[4] * y + e[8] * z + e[12] ) * d;
  986. this.y = ( e[1] * x + e[5] * y + e[9] * z + e[13] ) * d;
  987. this.z = ( e[2] * x + e[6] * y + e[10] * z + e[14] ) * d;
  988. return this;
  989. },
  990. applyQuaternion: function ( q ) {
  991. var x = this.x;
  992. var y = this.y;
  993. var z = this.z;
  994. var qx = q.x;
  995. var qy = q.y;
  996. var qz = q.z;
  997. var qw = q.w;
  998. // calculate quat * vector
  999. var ix = qw * x + qy * z - qz * y;
  1000. var iy = qw * y + qz * x - qx * z;
  1001. var iz = qw * z + qx * y - qy * x;
  1002. var iw = -qx * x - qy * y - qz * z;
  1003. // calculate result * inverse quat
  1004. this.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  1005. this.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  1006. this.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  1007. return this;
  1008. },
  1009. transformDirection: function ( m ) {
  1010. // input: THREE.Matrix4 affine matrix
  1011. // vector interpreted as a direction
  1012. var x = this.x, y = this.y, z = this.z;
  1013. var e = m.elements;
  1014. this.x = e[0] * x + e[4] * y + e[8] * z;
  1015. this.y = e[1] * x + e[5] * y + e[9] * z;
  1016. this.z = e[2] * x + e[6] * y + e[10] * z;
  1017. this.normalize();
  1018. return this;
  1019. },
  1020. divide: function ( v ) {
  1021. this.x /= v.x;
  1022. this.y /= v.y;
  1023. this.z /= v.z;
  1024. return this;
  1025. },
  1026. divideScalar: function ( s ) {
  1027. if ( s !== 0 ) {
  1028. this.x /= s;
  1029. this.y /= s;
  1030. this.z /= s;
  1031. } else {
  1032. this.x = 0;
  1033. this.y = 0;
  1034. this.z = 0;
  1035. }
  1036. return this;
  1037. },
  1038. min: function ( v ) {
  1039. if ( this.x > v.x ) {
  1040. this.x = v.x;
  1041. }
  1042. if ( this.y > v.y ) {
  1043. this.y = v.y;
  1044. }
  1045. if ( this.z > v.z ) {
  1046. this.z = v.z;
  1047. }
  1048. return this;
  1049. },
  1050. max: function ( v ) {
  1051. if ( this.x < v.x ) {
  1052. this.x = v.x;
  1053. }
  1054. if ( this.y < v.y ) {
  1055. this.y = v.y;
  1056. }
  1057. if ( this.z < v.z ) {
  1058. this.z = v.z;
  1059. }
  1060. return this;
  1061. },
  1062. clamp: function ( min, max ) {
  1063. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1064. if ( this.x < min.x ) {
  1065. this.x = min.x;
  1066. } else if ( this.x > max.x ) {
  1067. this.x = max.x;
  1068. }
  1069. if ( this.y < min.y ) {
  1070. this.y = min.y;
  1071. } else if ( this.y > max.y ) {
  1072. this.y = max.y;
  1073. }
  1074. if ( this.z < min.z ) {
  1075. this.z = min.z;
  1076. } else if ( this.z > max.z ) {
  1077. this.z = max.z;
  1078. }
  1079. return this;
  1080. },
  1081. negate: function () {
  1082. return this.multiplyScalar( - 1 );
  1083. },
  1084. dot: function ( v ) {
  1085. return this.x * v.x + this.y * v.y + this.z * v.z;
  1086. },
  1087. lengthSq: function () {
  1088. return this.x * this.x + this.y * this.y + this.z * this.z;
  1089. },
  1090. length: function () {
  1091. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z );
  1092. },
  1093. lengthManhattan: function () {
  1094. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  1095. },
  1096. normalize: function () {
  1097. return this.divideScalar( this.length() );
  1098. },
  1099. setLength: function ( l ) {
  1100. var oldLength = this.length();
  1101. if ( oldLength !== 0 && l !== oldLength ) {
  1102. this.multiplyScalar( l / oldLength );
  1103. }
  1104. return this;
  1105. },
  1106. lerp: function ( v, alpha ) {
  1107. this.x += ( v.x - this.x ) * alpha;
  1108. this.y += ( v.y - this.y ) * alpha;
  1109. this.z += ( v.z - this.z ) * alpha;
  1110. return this;
  1111. },
  1112. cross: function ( v, w ) {
  1113. if ( w !== undefined ) {
  1114. console.warn( 'DEPRECATED: Vector3\'s .cross() now only accepts one argument. Use .crossVectors( a, b ) instead.' );
  1115. return this.crossVectors( v, w );
  1116. }
  1117. var x = this.x, y = this.y, z = this.z;
  1118. this.x = y * v.z - z * v.y;
  1119. this.y = z * v.x - x * v.z;
  1120. this.z = x * v.y - y * v.x;
  1121. return this;
  1122. },
  1123. crossVectors: function ( a, b ) {
  1124. this.x = a.y * b.z - a.z * b.y;
  1125. this.y = a.z * b.x - a.x * b.z;
  1126. this.z = a.x * b.y - a.y * b.x;
  1127. return this;
  1128. },
  1129. angleTo: function ( v ) {
  1130. var theta = this.dot( v ) / ( this.length() * v.length() );
  1131. // clamp, to handle numerical problems
  1132. return Math.acos( THREE.Math.clamp( theta, -1, 1 ) );
  1133. },
  1134. distanceTo: function ( v ) {
  1135. return Math.sqrt( this.distanceToSquared( v ) );
  1136. },
  1137. distanceToSquared: function ( v ) {
  1138. var dx = this.x - v.x;
  1139. var dy = this.y - v.y;
  1140. var dz = this.z - v.z;
  1141. return dx * dx + dy * dy + dz * dz;
  1142. },
  1143. setEulerFromRotationMatrix: function ( m, order ) {
  1144. console.error( "REMOVED: Vector3\'s setEulerFromRotationMatrix has been removed in favor of Euler.setFromRotationMatrix(), please update your code.");
  1145. },
  1146. setEulerFromQuaternion: function ( q, order ) {
  1147. console.error( "REMOVED: Vector3\'s setEulerFromQuaternion: has been removed in favor of Euler.setFromQuaternion(), please update your code.");
  1148. },
  1149. getPositionFromMatrix: function ( m ) {
  1150. this.x = m.elements[12];
  1151. this.y = m.elements[13];
  1152. this.z = m.elements[14];
  1153. return this;
  1154. },
  1155. getScaleFromMatrix: function ( m ) {
  1156. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  1157. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  1158. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  1159. this.x = sx;
  1160. this.y = sy;
  1161. this.z = sz;
  1162. return this;
  1163. },
  1164. getColumnFromMatrix: function ( index, matrix ) {
  1165. var offset = index * 4;
  1166. var me = matrix.elements;
  1167. this.x = me[ offset ];
  1168. this.y = me[ offset + 1 ];
  1169. this.z = me[ offset + 2 ];
  1170. return this;
  1171. },
  1172. equals: function ( v ) {
  1173. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  1174. },
  1175. fromArray: function ( array ) {
  1176. this.x = array[ 0 ];
  1177. this.y = array[ 1 ];
  1178. this.z = array[ 2 ];
  1179. return this;
  1180. },
  1181. toArray: function () {
  1182. return [ this.x, this.y, this.z ];
  1183. },
  1184. clone: function () {
  1185. return new THREE.Vector3( this.x, this.y, this.z );
  1186. }
  1187. };
  1188. THREE.extend( THREE.Vector3.prototype, {
  1189. applyEuler: function () {
  1190. var q1 = new THREE.Quaternion();
  1191. return function ( rotation ) {
  1192. if( typeof rotation['order'] === undefined ) {
  1193. console.error( 'ERROR: Vector3\'s .applyEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  1194. }
  1195. var quaternion = q1.setFromEuler( rotation );
  1196. this.applyQuaternion( quaternion );
  1197. return this;
  1198. };
  1199. }(),
  1200. applyAxisAngle: function () {
  1201. var q1 = new THREE.Quaternion();
  1202. return function ( axis, angle ) {
  1203. var quaternion = q1.setFromAxisAngle( axis, angle );
  1204. this.applyQuaternion( quaternion );
  1205. return this;
  1206. };
  1207. }(),
  1208. projectOnVector: function () {
  1209. var v1 = new THREE.Vector3();
  1210. return function ( vector ) {
  1211. v1.copy( vector ).normalize();
  1212. var d = this.dot( v1 );
  1213. return this.copy( v1 ).multiplyScalar( d );
  1214. };
  1215. }(),
  1216. projectOnPlane: function () {
  1217. var v1 = new THREE.Vector3();
  1218. return function ( planeNormal ) {
  1219. v1.copy( this ).projectOnVector( planeNormal );
  1220. return this.sub( v1 );
  1221. }
  1222. }(),
  1223. reflect: function () {
  1224. var v1 = new THREE.Vector3();
  1225. return function ( vector ) {
  1226. v1.copy( this ).projectOnVector( vector ).multiplyScalar( 2 );
  1227. return this.subVectors( v1, this );
  1228. }
  1229. }()
  1230. } );
  1231. /**
  1232. * @author supereggbert / http://www.paulbrunt.co.uk/
  1233. * @author philogb / http://blog.thejit.org/
  1234. * @author mikael emtinger / http://gomo.se/
  1235. * @author egraether / http://egraether.com/
  1236. * @author WestLangley / http://github.com/WestLangley
  1237. */
  1238. THREE.Vector4 = function ( x, y, z, w ) {
  1239. this.x = x || 0;
  1240. this.y = y || 0;
  1241. this.z = z || 0;
  1242. this.w = ( w !== undefined ) ? w : 1;
  1243. };
  1244. THREE.Vector4.prototype = {
  1245. constructor: THREE.Vector4,
  1246. set: function ( x, y, z, w ) {
  1247. this.x = x;
  1248. this.y = y;
  1249. this.z = z;
  1250. this.w = w;
  1251. return this;
  1252. },
  1253. setX: function ( x ) {
  1254. this.x = x;
  1255. return this;
  1256. },
  1257. setY: function ( y ) {
  1258. this.y = y;
  1259. return this;
  1260. },
  1261. setZ: function ( z ) {
  1262. this.z = z;
  1263. return this;
  1264. },
  1265. setW: function ( w ) {
  1266. this.w = w;
  1267. return this;
  1268. },
  1269. setComponent: function ( index, value ) {
  1270. switch ( index ) {
  1271. case 0: this.x = value; break;
  1272. case 1: this.y = value; break;
  1273. case 2: this.z = value; break;
  1274. case 3: this.w = value; break;
  1275. default: throw new Error( "index is out of range: " + index );
  1276. }
  1277. },
  1278. getComponent: function ( index ) {
  1279. switch ( index ) {
  1280. case 0: return this.x;
  1281. case 1: return this.y;
  1282. case 2: return this.z;
  1283. case 3: return this.w;
  1284. default: throw new Error( "index is out of range: " + index );
  1285. }
  1286. },
  1287. copy: function ( v ) {
  1288. this.x = v.x;
  1289. this.y = v.y;
  1290. this.z = v.z;
  1291. this.w = ( v.w !== undefined ) ? v.w : 1;
  1292. return this;
  1293. },
  1294. add: function ( v, w ) {
  1295. if ( w !== undefined ) {
  1296. console.warn( 'DEPRECATED: Vector4\'s .add() now only accepts one argument. Use .addVectors( a, b ) instead.' );
  1297. return this.addVectors( v, w );
  1298. }
  1299. this.x += v.x;
  1300. this.y += v.y;
  1301. this.z += v.z;
  1302. this.w += v.w;
  1303. return this;
  1304. },
  1305. addScalar: function ( s ) {
  1306. this.x += s;
  1307. this.y += s;
  1308. this.z += s;
  1309. this.w += s;
  1310. return this;
  1311. },
  1312. addVectors: function ( a, b ) {
  1313. this.x = a.x + b.x;
  1314. this.y = a.y + b.y;
  1315. this.z = a.z + b.z;
  1316. this.w = a.w + b.w;
  1317. return this;
  1318. },
  1319. sub: function ( v, w ) {
  1320. if ( w !== undefined ) {
  1321. console.warn( 'DEPRECATED: Vector4\'s .sub() now only accepts one argument. Use .subVectors( a, b ) instead.' );
  1322. return this.subVectors( v, w );
  1323. }
  1324. this.x -= v.x;
  1325. this.y -= v.y;
  1326. this.z -= v.z;
  1327. this.w -= v.w;
  1328. return this;
  1329. },
  1330. subVectors: function ( a, b ) {
  1331. this.x = a.x - b.x;
  1332. this.y = a.y - b.y;
  1333. this.z = a.z - b.z;
  1334. this.w = a.w - b.w;
  1335. return this;
  1336. },
  1337. multiplyScalar: function ( s ) {
  1338. this.x *= s;
  1339. this.y *= s;
  1340. this.z *= s;
  1341. this.w *= s;
  1342. return this;
  1343. },
  1344. applyMatrix4: function ( m ) {
  1345. var x = this.x;
  1346. var y = this.y;
  1347. var z = this.z;
  1348. var w = this.w;
  1349. var e = m.elements;
  1350. this.x = e[0] * x + e[4] * y + e[8] * z + e[12] * w;
  1351. this.y = e[1] * x + e[5] * y + e[9] * z + e[13] * w;
  1352. this.z = e[2] * x + e[6] * y + e[10] * z + e[14] * w;
  1353. this.w = e[3] * x + e[7] * y + e[11] * z + e[15] * w;
  1354. return this;
  1355. },
  1356. divideScalar: function ( s ) {
  1357. if ( s !== 0 ) {
  1358. this.x /= s;
  1359. this.y /= s;
  1360. this.z /= s;
  1361. this.w /= s;
  1362. } else {
  1363. this.x = 0;
  1364. this.y = 0;
  1365. this.z = 0;
  1366. this.w = 1;
  1367. }
  1368. return this;
  1369. },
  1370. setAxisAngleFromQuaternion: function ( q ) {
  1371. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1372. // q is assumed to be normalized
  1373. this.w = 2 * Math.acos( q.w );
  1374. var s = Math.sqrt( 1 - q.w * q.w );
  1375. if ( s < 0.0001 ) {
  1376. this.x = 1;
  1377. this.y = 0;
  1378. this.z = 0;
  1379. } else {
  1380. this.x = q.x / s;
  1381. this.y = q.y / s;
  1382. this.z = q.z / s;
  1383. }
  1384. return this;
  1385. },
  1386. setAxisAngleFromRotationMatrix: function ( m ) {
  1387. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1388. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1389. var angle, x, y, z, // variables for result
  1390. epsilon = 0.01, // margin to allow for rounding errors
  1391. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1392. te = m.elements,
  1393. m11 = te[0], m12 = te[4], m13 = te[8],
  1394. m21 = te[1], m22 = te[5], m23 = te[9],
  1395. m31 = te[2], m32 = te[6], m33 = te[10];
  1396. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1397. && ( Math.abs( m13 - m31 ) < epsilon )
  1398. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1399. // singularity found
  1400. // first check for identity matrix which must have +1 for all terms
  1401. // in leading diagonal and zero in other terms
  1402. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1403. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1404. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1405. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1406. // this singularity is identity matrix so angle = 0
  1407. this.set( 1, 0, 0, 0 );
  1408. return this; // zero angle, arbitrary axis
  1409. }
  1410. // otherwise this singularity is angle = 180
  1411. angle = Math.PI;
  1412. var xx = ( m11 + 1 ) / 2;
  1413. var yy = ( m22 + 1 ) / 2;
  1414. var zz = ( m33 + 1 ) / 2;
  1415. var xy = ( m12 + m21 ) / 4;
  1416. var xz = ( m13 + m31 ) / 4;
  1417. var yz = ( m23 + m32 ) / 4;
  1418. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1419. if ( xx < epsilon ) {
  1420. x = 0;
  1421. y = 0.707106781;
  1422. z = 0.707106781;
  1423. } else {
  1424. x = Math.sqrt( xx );
  1425. y = xy / x;
  1426. z = xz / x;
  1427. }
  1428. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1429. if ( yy < epsilon ) {
  1430. x = 0.707106781;
  1431. y = 0;
  1432. z = 0.707106781;
  1433. } else {
  1434. y = Math.sqrt( yy );
  1435. x = xy / y;
  1436. z = yz / y;
  1437. }
  1438. } else { // m33 is the largest diagonal term so base result on this
  1439. if ( zz < epsilon ) {
  1440. x = 0.707106781;
  1441. y = 0.707106781;
  1442. z = 0;
  1443. } else {
  1444. z = Math.sqrt( zz );
  1445. x = xz / z;
  1446. y = yz / z;
  1447. }
  1448. }
  1449. this.set( x, y, z, angle );
  1450. return this; // return 180 deg rotation
  1451. }
  1452. // as we have reached here there are no singularities so we can handle normally
  1453. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1454. + ( m13 - m31 ) * ( m13 - m31 )
  1455. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1456. if ( Math.abs( s ) < 0.001 ) s = 1;
  1457. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1458. // caught by singularity test above, but I've left it in just in case
  1459. this.x = ( m32 - m23 ) / s;
  1460. this.y = ( m13 - m31 ) / s;
  1461. this.z = ( m21 - m12 ) / s;
  1462. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1463. return this;
  1464. },
  1465. min: function ( v ) {
  1466. if ( this.x > v.x ) {
  1467. this.x = v.x;
  1468. }
  1469. if ( this.y > v.y ) {
  1470. this.y = v.y;
  1471. }
  1472. if ( this.z > v.z ) {
  1473. this.z = v.z;
  1474. }
  1475. if ( this.w > v.w ) {
  1476. this.w = v.w;
  1477. }
  1478. return this;
  1479. },
  1480. max: function ( v ) {
  1481. if ( this.x < v.x ) {
  1482. this.x = v.x;
  1483. }
  1484. if ( this.y < v.y ) {
  1485. this.y = v.y;
  1486. }
  1487. if ( this.z < v.z ) {
  1488. this.z = v.z;
  1489. }
  1490. if ( this.w < v.w ) {
  1491. this.w = v.w;
  1492. }
  1493. return this;
  1494. },
  1495. clamp: function ( min, max ) {
  1496. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  1497. if ( this.x < min.x ) {
  1498. this.x = min.x;
  1499. } else if ( this.x > max.x ) {
  1500. this.x = max.x;
  1501. }
  1502. if ( this.y < min.y ) {
  1503. this.y = min.y;
  1504. } else if ( this.y > max.y ) {
  1505. this.y = max.y;
  1506. }
  1507. if ( this.z < min.z ) {
  1508. this.z = min.z;
  1509. } else if ( this.z > max.z ) {
  1510. this.z = max.z;
  1511. }
  1512. if ( this.w < min.w ) {
  1513. this.w = min.w;
  1514. } else if ( this.w > max.w ) {
  1515. this.w = max.w;
  1516. }
  1517. return this;
  1518. },
  1519. negate: function() {
  1520. return this.multiplyScalar( -1 );
  1521. },
  1522. dot: function ( v ) {
  1523. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1524. },
  1525. lengthSq: function () {
  1526. return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
  1527. },
  1528. length: function () {
  1529. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  1530. },
  1531. lengthManhattan: function () {
  1532. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1533. },
  1534. normalize: function () {
  1535. return this.divideScalar( this.length() );
  1536. },
  1537. setLength: function ( l ) {
  1538. var oldLength = this.length();
  1539. if ( oldLength !== 0 && l !== oldLength ) {
  1540. this.multiplyScalar( l / oldLength );
  1541. }
  1542. return this;
  1543. },
  1544. lerp: function ( v, alpha ) {
  1545. this.x += ( v.x - this.x ) * alpha;
  1546. this.y += ( v.y - this.y ) * alpha;
  1547. this.z += ( v.z - this.z ) * alpha;
  1548. this.w += ( v.w - this.w ) * alpha;
  1549. return this;
  1550. },
  1551. equals: function ( v ) {
  1552. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1553. },
  1554. fromArray: function ( array ) {
  1555. this.x = array[ 0 ];
  1556. this.y = array[ 1 ];
  1557. this.z = array[ 2 ];
  1558. this.w = array[ 3 ];
  1559. return this;
  1560. },
  1561. toArray: function () {
  1562. return [ this.x, this.y, this.z, this.w ];
  1563. },
  1564. clone: function () {
  1565. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1566. }
  1567. };
  1568. /**
  1569. * @author mrdoob / http://mrdoob.com/
  1570. * @author WestLangley / http://github.com/WestLangley
  1571. * @author bhouston / http://exocortex.com
  1572. */
  1573. THREE.Euler = function ( x, y, z, order ) {
  1574. this._x = x || 0;
  1575. this._y = y || 0;
  1576. this._z = z || 0;
  1577. this._order = order || THREE.Euler.DefaultOrder;
  1578. };
  1579. THREE.Euler.RotationOrders = [ 'XYZ', 'YZX', 'ZXY', 'XZY', 'YXZ', 'ZYX' ];
  1580. THREE.Euler.DefaultOrder = 'XYZ';
  1581. THREE.Euler.prototype = {
  1582. constructor: THREE.Euler,
  1583. _x: 0, _y: 0, _z: 0, _order: THREE.Euler.DefaultOrder,
  1584. _quaternion: undefined,
  1585. _updateQuaternion: function () {
  1586. if ( this._quaternion !== undefined ) {
  1587. this._quaternion.setFromEuler( this, false );
  1588. }
  1589. },
  1590. get x () {
  1591. return this._x;
  1592. },
  1593. set x ( value ) {
  1594. this._x = value;
  1595. this._updateQuaternion();
  1596. },
  1597. get y () {
  1598. return this._y;
  1599. },
  1600. set y ( value ) {
  1601. this._y = value;
  1602. this._updateQuaternion();
  1603. },
  1604. get z () {
  1605. return this._z;
  1606. },
  1607. set z ( value ) {
  1608. this._z = value;
  1609. this._updateQuaternion();
  1610. },
  1611. get order () {
  1612. return this._order;
  1613. },
  1614. set order ( value ) {
  1615. this._order = value;
  1616. this._updateQuaternion();
  1617. },
  1618. set: function ( x, y, z, order ) {
  1619. this._x = x;
  1620. this._y = y;
  1621. this._z = z;
  1622. this._order = order || this._order;
  1623. this._updateQuaternion();
  1624. return this;
  1625. },
  1626. copy: function ( euler ) {
  1627. this._x = euler._x;
  1628. this._y = euler._y;
  1629. this._z = euler._z;
  1630. this._order = euler._order;
  1631. this._updateQuaternion();
  1632. return this;
  1633. },
  1634. setFromRotationMatrix: function ( m, order ) {
  1635. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1636. // clamp, to handle numerical problems
  1637. function clamp( x ) {
  1638. return Math.min( Math.max( x, -1 ), 1 );
  1639. }
  1640. var te = m.elements;
  1641. var m11 = te[0], m12 = te[4], m13 = te[8];
  1642. var m21 = te[1], m22 = te[5], m23 = te[9];
  1643. var m31 = te[2], m32 = te[6], m33 = te[10];
  1644. order = order || this._order;
  1645. if ( order === 'XYZ' ) {
  1646. this._y = Math.asin( clamp( m13 ) );
  1647. if ( Math.abs( m13 ) < 0.99999 ) {
  1648. this._x = Math.atan2( - m23, m33 );
  1649. this._z = Math.atan2( - m12, m11 );
  1650. } else {
  1651. this._x = Math.atan2( m32, m22 );
  1652. this._z = 0;
  1653. }
  1654. } else if ( order === 'YXZ' ) {
  1655. this._x = Math.asin( - clamp( m23 ) );
  1656. if ( Math.abs( m23 ) < 0.99999 ) {
  1657. this._y = Math.atan2( m13, m33 );
  1658. this._z = Math.atan2( m21, m22 );
  1659. } else {
  1660. this._y = Math.atan2( - m31, m11 );
  1661. this._z = 0;
  1662. }
  1663. } else if ( order === 'ZXY' ) {
  1664. this._x = Math.asin( clamp( m32 ) );
  1665. if ( Math.abs( m32 ) < 0.99999 ) {
  1666. this._y = Math.atan2( - m31, m33 );
  1667. this._z = Math.atan2( - m12, m22 );
  1668. } else {
  1669. this._y = 0;
  1670. this._z = Math.atan2( m21, m11 );
  1671. }
  1672. } else if ( order === 'ZYX' ) {
  1673. this._y = Math.asin( - clamp( m31 ) );
  1674. if ( Math.abs( m31 ) < 0.99999 ) {
  1675. this._x = Math.atan2( m32, m33 );
  1676. this._z = Math.atan2( m21, m11 );
  1677. } else {
  1678. this._x = 0;
  1679. this._z = Math.atan2( - m12, m22 );
  1680. }
  1681. } else if ( order === 'YZX' ) {
  1682. this._z = Math.asin( clamp( m21 ) );
  1683. if ( Math.abs( m21 ) < 0.99999 ) {
  1684. this._x = Math.atan2( - m23, m22 );
  1685. this._y = Math.atan2( - m31, m11 );
  1686. } else {
  1687. this._x = 0;
  1688. this._y = Math.atan2( m13, m33 );
  1689. }
  1690. } else if ( order === 'XZY' ) {
  1691. this._z = Math.asin( - clamp( m12 ) );
  1692. if ( Math.abs( m12 ) < 0.99999 ) {
  1693. this._x = Math.atan2( m32, m22 );
  1694. this._y = Math.atan2( m13, m11 );
  1695. } else {
  1696. this._x = Math.atan2( - m23, m33 );
  1697. this._y = 0;
  1698. }
  1699. } else {
  1700. console.warn( 'WARNING: Euler.setFromRotationMatrix() given unsupported order: ' + order )
  1701. }
  1702. this._order = order;
  1703. this._updateQuaternion();
  1704. return this;
  1705. },
  1706. setFromQuaternion: function ( q, order, update ) {
  1707. // q is assumed to be normalized
  1708. // clamp, to handle numerical problems
  1709. function clamp( x ) {
  1710. return Math.min( Math.max( x, -1 ), 1 );
  1711. }
  1712. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  1713. var sqx = q.x * q.x;
  1714. var sqy = q.y * q.y;
  1715. var sqz = q.z * q.z;
  1716. var sqw = q.w * q.w;
  1717. order = order || this._order;
  1718. if ( order === 'XYZ' ) {
  1719. this._x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  1720. this._y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  1721. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  1722. } else if ( order === 'YXZ' ) {
  1723. this._x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  1724. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  1725. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  1726. } else if ( order === 'ZXY' ) {
  1727. this._x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  1728. this._y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  1729. this._z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  1730. } else if ( order === 'ZYX' ) {
  1731. this._x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  1732. this._y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  1733. this._z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  1734. } else if ( order === 'YZX' ) {
  1735. this._x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  1736. this._y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  1737. this._z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  1738. } else if ( order === 'XZY' ) {
  1739. this._x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  1740. this._y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  1741. this._z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  1742. } else {
  1743. console.warn( 'WARNING: Euler.setFromQuaternion() given unsupported order: ' + order )
  1744. }
  1745. this._order = order;
  1746. if ( update !== false ) this._updateQuaternion();
  1747. return this;
  1748. },
  1749. reorder: function () {
  1750. // WARNING: this discards revolution information -bhouston
  1751. var q = new THREE.Quaternion();
  1752. return function ( newOrder ) {
  1753. q.setFromEuler( this );
  1754. this.setFromQuaternion( q, newOrder );
  1755. };
  1756. }(),
  1757. fromArray: function ( array ) {
  1758. this._x = array[ 0 ];
  1759. this._y = array[ 1 ];
  1760. this._z = array[ 2 ];
  1761. this._order = array[ 3 ];
  1762. this._updateQuaternion();
  1763. return this;
  1764. },
  1765. toArray: function () {
  1766. return [ this._x, this._y, this._z, this._order ];
  1767. },
  1768. equals: function ( euler ) {
  1769. return ( euler._x === this._x ) && ( euler._y === this._y ) && ( euler._z === this._z ) && ( euler._order === this._order );
  1770. },
  1771. clone: function () {
  1772. return new THREE.Euler( this._x, this._y, this._z, this._order );
  1773. }
  1774. };
  1775. /**
  1776. * @author bhouston / http://exocortex.com
  1777. */
  1778. THREE.Line3 = function ( start, end ) {
  1779. this.start = ( start !== undefined ) ? start : new THREE.Vector3();
  1780. this.end = ( end !== undefined ) ? end : new THREE.Vector3();
  1781. };
  1782. THREE.Line3.prototype = {
  1783. constructor: THREE.Line3,
  1784. set: function ( start, end ) {
  1785. this.start.copy( start );
  1786. this.end.copy( end );
  1787. return this;
  1788. },
  1789. copy: function ( line ) {
  1790. this.start.copy( line.start );
  1791. this.end.copy( line.end );
  1792. return this;
  1793. },
  1794. center: function ( optionalTarget ) {
  1795. var result = optionalTarget || new THREE.Vector3();
  1796. return result.addVectors( this.start, this.end ).multiplyScalar( 0.5 );
  1797. },
  1798. delta: function ( optionalTarget ) {
  1799. var result = optionalTarget || new THREE.Vector3();
  1800. return result.subVectors( this.end, this.start );
  1801. },
  1802. distanceSq: function () {
  1803. return this.start.distanceToSquared( this.end );
  1804. },
  1805. distance: function () {
  1806. return this.start.distanceTo( this.end );
  1807. },
  1808. at: function ( t, optionalTarget ) {
  1809. var result = optionalTarget || new THREE.Vector3();
  1810. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1811. },
  1812. closestPointToPointParameter: function() {
  1813. var startP = new THREE.Vector3();
  1814. var startEnd = new THREE.Vector3();
  1815. return function ( point, clampToLine ) {
  1816. startP.subVectors( point, this.start );
  1817. startEnd.subVectors( this.end, this.start );
  1818. var startEnd2 = startEnd.dot( startEnd );
  1819. var startEnd_startP = startEnd.dot( startP );
  1820. var t = startEnd_startP / startEnd2;
  1821. if ( clampToLine ) {
  1822. t = THREE.Math.clamp( t, 0, 1 );
  1823. }
  1824. return t;
  1825. };
  1826. }(),
  1827. closestPointToPoint: function ( point, clampToLine, optionalTarget ) {
  1828. var t = this.closestPointToPointParameter( point, clampToLine );
  1829. var result = optionalTarget || new THREE.Vector3();
  1830. return this.delta( result ).multiplyScalar( t ).add( this.start );
  1831. },
  1832. applyMatrix4: function ( matrix ) {
  1833. this.start.applyMatrix4( matrix );
  1834. this.end.applyMatrix4( matrix );
  1835. return this;
  1836. },
  1837. equals: function ( line ) {
  1838. return line.start.equals( this.start ) && line.end.equals( this.end );
  1839. },
  1840. clone: function () {
  1841. return new THREE.Line3().copy( this );
  1842. }
  1843. };
  1844. /**
  1845. * @author bhouston / http://exocortex.com
  1846. */
  1847. THREE.Box2 = function ( min, max ) {
  1848. this.min = ( min !== undefined ) ? min : new THREE.Vector2( Infinity, Infinity );
  1849. this.max = ( max !== undefined ) ? max : new THREE.Vector2( -Infinity, -Infinity );
  1850. };
  1851. THREE.Box2.prototype = {
  1852. constructor: THREE.Box2,
  1853. set: function ( min, max ) {
  1854. this.min.copy( min );
  1855. this.max.copy( max );
  1856. return this;
  1857. },
  1858. setFromPoints: function ( points ) {
  1859. if ( points.length > 0 ) {
  1860. var point = points[ 0 ];
  1861. this.min.copy( point );
  1862. this.max.copy( point );
  1863. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1864. point = points[ i ];
  1865. if ( point.x < this.min.x ) {
  1866. this.min.x = point.x;
  1867. } else if ( point.x > this.max.x ) {
  1868. this.max.x = point.x;
  1869. }
  1870. if ( point.y < this.min.y ) {
  1871. this.min.y = point.y;
  1872. } else if ( point.y > this.max.y ) {
  1873. this.max.y = point.y;
  1874. }
  1875. }
  1876. } else {
  1877. this.makeEmpty();
  1878. }
  1879. return this;
  1880. },
  1881. setFromCenterAndSize: function () {
  1882. var v1 = new THREE.Vector2();
  1883. return function ( center, size ) {
  1884. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  1885. this.min.copy( center ).sub( halfSize );
  1886. this.max.copy( center ).add( halfSize );
  1887. return this;
  1888. };
  1889. }(),
  1890. copy: function ( box ) {
  1891. this.min.copy( box.min );
  1892. this.max.copy( box.max );
  1893. return this;
  1894. },
  1895. makeEmpty: function () {
  1896. this.min.x = this.min.y = Infinity;
  1897. this.max.x = this.max.y = -Infinity;
  1898. return this;
  1899. },
  1900. empty: function () {
  1901. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1902. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1903. },
  1904. center: function ( optionalTarget ) {
  1905. var result = optionalTarget || new THREE.Vector2();
  1906. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  1907. },
  1908. size: function ( optionalTarget ) {
  1909. var result = optionalTarget || new THREE.Vector2();
  1910. return result.subVectors( this.max, this.min );
  1911. },
  1912. expandByPoint: function ( point ) {
  1913. this.min.min( point );
  1914. this.max.max( point );
  1915. return this;
  1916. },
  1917. expandByVector: function ( vector ) {
  1918. this.min.sub( vector );
  1919. this.max.add( vector );
  1920. return this;
  1921. },
  1922. expandByScalar: function ( scalar ) {
  1923. this.min.addScalar( -scalar );
  1924. this.max.addScalar( scalar );
  1925. return this;
  1926. },
  1927. containsPoint: function ( point ) {
  1928. if ( point.x < this.min.x || point.x > this.max.x ||
  1929. point.y < this.min.y || point.y > this.max.y ) {
  1930. return false;
  1931. }
  1932. return true;
  1933. },
  1934. containsBox: function ( box ) {
  1935. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1936. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1937. return true;
  1938. }
  1939. return false;
  1940. },
  1941. getParameter: function ( point ) {
  1942. // This can potentially have a divide by zero if the box
  1943. // has a size dimension of 0.
  1944. return new THREE.Vector2(
  1945. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1946. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1947. );
  1948. },
  1949. isIntersectionBox: function ( box ) {
  1950. // using 6 splitting planes to rule out intersections.
  1951. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  1952. box.max.y < this.min.y || box.min.y > this.max.y ) {
  1953. return false;
  1954. }
  1955. return true;
  1956. },
  1957. clampPoint: function ( point, optionalTarget ) {
  1958. var result = optionalTarget || new THREE.Vector2();
  1959. return result.copy( point ).clamp( this.min, this.max );
  1960. },
  1961. distanceToPoint: function () {
  1962. var v1 = new THREE.Vector2();
  1963. return function ( point ) {
  1964. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  1965. return clampedPoint.sub( point ).length();
  1966. };
  1967. }(),
  1968. intersect: function ( box ) {
  1969. this.min.max( box.min );
  1970. this.max.min( box.max );
  1971. return this;
  1972. },
  1973. union: function ( box ) {
  1974. this.min.min( box.min );
  1975. this.max.max( box.max );
  1976. return this;
  1977. },
  1978. translate: function ( offset ) {
  1979. this.min.add( offset );
  1980. this.max.add( offset );
  1981. return this;
  1982. },
  1983. equals: function ( box ) {
  1984. return box.min.equals( this.min ) && box.max.equals( this.max );
  1985. },
  1986. clone: function () {
  1987. return new THREE.Box2().copy( this );
  1988. }
  1989. };
  1990. /**
  1991. * @author bhouston / http://exocortex.com
  1992. * @author WestLangley / http://github.com/WestLangley
  1993. */
  1994. THREE.Box3 = function ( min, max ) {
  1995. this.min = ( min !== undefined ) ? min : new THREE.Vector3( Infinity, Infinity, Infinity );
  1996. this.max = ( max !== undefined ) ? max : new THREE.Vector3( -Infinity, -Infinity, -Infinity );
  1997. };
  1998. THREE.Box3.prototype = {
  1999. constructor: THREE.Box3,
  2000. set: function ( min, max ) {
  2001. this.min.copy( min );
  2002. this.max.copy( max );
  2003. return this;
  2004. },
  2005. setFromPoints: function ( points ) {
  2006. if ( points.length > 0 ) {
  2007. var point = points[ 0 ];
  2008. this.min.copy( point );
  2009. this.max.copy( point );
  2010. for ( var i = 1, il = points.length; i < il; i ++ ) {
  2011. point = points[ i ];
  2012. if ( point.x < this.min.x ) {
  2013. this.min.x = point.x;
  2014. } else if ( point.x > this.max.x ) {
  2015. this.max.x = point.x;
  2016. }
  2017. if ( point.y < this.min.y ) {
  2018. this.min.y = point.y;
  2019. } else if ( point.y > this.max.y ) {
  2020. this.max.y = point.y;
  2021. }
  2022. if ( point.z < this.min.z ) {
  2023. this.min.z = point.z;
  2024. } else if ( point.z > this.max.z ) {
  2025. this.max.z = point.z;
  2026. }
  2027. }
  2028. } else {
  2029. this.makeEmpty();
  2030. }
  2031. return this;
  2032. },
  2033. setFromCenterAndSize: function() {
  2034. var v1 = new THREE.Vector3();
  2035. return function ( center, size ) {
  2036. var halfSize = v1.copy( size ).multiplyScalar( 0.5 );
  2037. this.min.copy( center ).sub( halfSize );
  2038. this.max.copy( center ).add( halfSize );
  2039. return this;
  2040. };
  2041. }(),
  2042. setFromObject: function() {
  2043. // Computes the world-axis-aligned bounding box of an object (including its children),
  2044. // accounting for both the object's, and childrens', world transforms
  2045. var v1 = new THREE.Vector3();
  2046. return function( object ) {
  2047. var scope = this;
  2048. object.updateMatrixWorld( true );
  2049. this.makeEmpty();
  2050. object.traverse( function ( node ) {
  2051. if ( node.geometry !== undefined && node.geometry.vertices !== undefined ) {
  2052. var vertices = node.geometry.vertices;
  2053. for ( var i = 0, il = vertices.length; i < il; i++ ) {
  2054. v1.copy( vertices[ i ] );
  2055. v1.applyMatrix4( node.matrixWorld );
  2056. scope.expandByPoint( v1 );
  2057. }
  2058. }
  2059. } );
  2060. return this;
  2061. };
  2062. }(),
  2063. copy: function ( box ) {
  2064. this.min.copy( box.min );
  2065. this.max.copy( box.max );
  2066. return this;
  2067. },
  2068. makeEmpty: function () {
  2069. this.min.x = this.min.y = this.min.z = Infinity;
  2070. this.max.x = this.max.y = this.max.z = -Infinity;
  2071. return this;
  2072. },
  2073. empty: function () {
  2074. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  2075. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  2076. },
  2077. center: function ( optionalTarget ) {
  2078. var result = optionalTarget || new THREE.Vector3();
  2079. return result.addVectors( this.min, this.max ).multiplyScalar( 0.5 );
  2080. },
  2081. size: function ( optionalTarget ) {
  2082. var result = optionalTarget || new THREE.Vector3();
  2083. return result.subVectors( this.max, this.min );
  2084. },
  2085. expandByPoint: function ( point ) {
  2086. this.min.min( point );
  2087. this.max.max( point );
  2088. return this;
  2089. },
  2090. expandByVector: function ( vector ) {
  2091. this.min.sub( vector );
  2092. this.max.add( vector );
  2093. return this;
  2094. },
  2095. expandByScalar: function ( scalar ) {
  2096. this.min.addScalar( -scalar );
  2097. this.max.addScalar( scalar );
  2098. return this;
  2099. },
  2100. containsPoint: function ( point ) {
  2101. if ( point.x < this.min.x || point.x > this.max.x ||
  2102. point.y < this.min.y || point.y > this.max.y ||
  2103. point.z < this.min.z || point.z > this.max.z ) {
  2104. return false;
  2105. }
  2106. return true;
  2107. },
  2108. containsBox: function ( box ) {
  2109. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  2110. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  2111. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  2112. return true;
  2113. }
  2114. return false;
  2115. },
  2116. getParameter: function ( point ) {
  2117. // This can potentially have a divide by zero if the box
  2118. // has a size dimension of 0.
  2119. return new THREE.Vector3(
  2120. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  2121. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  2122. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  2123. );
  2124. },
  2125. isIntersectionBox: function ( box ) {
  2126. // using 6 splitting planes to rule out intersections.
  2127. if ( box.max.x < this.min.x || box.min.x > this.max.x ||
  2128. box.max.y < this.min.y || box.min.y > this.max.y ||
  2129. box.max.z < this.min.z || box.min.z > this.max.z ) {
  2130. return false;
  2131. }
  2132. return true;
  2133. },
  2134. clampPoint: function ( point, optionalTarget ) {
  2135. var result = optionalTarget || new THREE.Vector3();
  2136. return result.copy( point ).clamp( this.min, this.max );
  2137. },
  2138. distanceToPoint: function() {
  2139. var v1 = new THREE.Vector3();
  2140. return function ( point ) {
  2141. var clampedPoint = v1.copy( point ).clamp( this.min, this.max );
  2142. return clampedPoint.sub( point ).length();
  2143. };
  2144. }(),
  2145. getBoundingSphere: function() {
  2146. var v1 = new THREE.Vector3();
  2147. return function ( optionalTarget ) {
  2148. var result = optionalTarget || new THREE.Sphere();
  2149. result.center = this.center();
  2150. result.radius = this.size( v1 ).length() * 0.5;
  2151. return result;
  2152. };
  2153. }(),
  2154. intersect: function ( box ) {
  2155. this.min.max( box.min );
  2156. this.max.min( box.max );
  2157. return this;
  2158. },
  2159. union: function ( box ) {
  2160. this.min.min( box.min );
  2161. this.max.max( box.max );
  2162. return this;
  2163. },
  2164. applyMatrix4: function() {
  2165. var points = [
  2166. new THREE.Vector3(),
  2167. new THREE.Vector3(),
  2168. new THREE.Vector3(),
  2169. new THREE.Vector3(),
  2170. new THREE.Vector3(),
  2171. new THREE.Vector3(),
  2172. new THREE.Vector3(),
  2173. new THREE.Vector3()
  2174. ];
  2175. return function ( matrix ) {
  2176. // NOTE: I am using a binary pattern to specify all 2^3 combinations below
  2177. points[0].set( this.min.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 000
  2178. points[1].set( this.min.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 001
  2179. points[2].set( this.min.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 010
  2180. points[3].set( this.min.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 011
  2181. points[4].set( this.max.x, this.min.y, this.min.z ).applyMatrix4( matrix ); // 100
  2182. points[5].set( this.max.x, this.min.y, this.max.z ).applyMatrix4( matrix ); // 101
  2183. points[6].set( this.max.x, this.max.y, this.min.z ).applyMatrix4( matrix ); // 110
  2184. points[7].set( this.max.x, this.max.y, this.max.z ).applyMatrix4( matrix ); // 111
  2185. this.makeEmpty();
  2186. this.setFromPoints( points );
  2187. return this;
  2188. };
  2189. }(),
  2190. translate: function ( offset ) {
  2191. this.min.add( offset );
  2192. this.max.add( offset );
  2193. return this;
  2194. },
  2195. equals: function ( box ) {
  2196. return box.min.equals( this.min ) && box.max.equals( this.max );
  2197. },
  2198. clone: function () {
  2199. return new THREE.Box3().copy( this );
  2200. }
  2201. };
  2202. /**
  2203. * @author alteredq / http://alteredqualia.com/
  2204. * @author WestLangley / http://github.com/WestLangley
  2205. * @author bhouston / http://exocortex.com
  2206. */
  2207. THREE.Matrix3 = function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2208. this.elements = new Float32Array(9);
  2209. this.set(
  2210. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0,
  2211. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0,
  2212. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1
  2213. );
  2214. };
  2215. THREE.Matrix3.prototype = {
  2216. constructor: THREE.Matrix3,
  2217. set: function ( n11, n12, n13, n21, n22, n23, n31, n32, n33 ) {
  2218. var te = this.elements;
  2219. te[0] = n11; te[3] = n12; te[6] = n13;
  2220. te[1] = n21; te[4] = n22; te[7] = n23;
  2221. te[2] = n31; te[5] = n32; te[8] = n33;
  2222. return this;
  2223. },
  2224. identity: function () {
  2225. this.set(
  2226. 1, 0, 0,
  2227. 0, 1, 0,
  2228. 0, 0, 1
  2229. );
  2230. return this;
  2231. },
  2232. copy: function ( m ) {
  2233. var me = m.elements;
  2234. this.set(
  2235. me[0], me[3], me[6],
  2236. me[1], me[4], me[7],
  2237. me[2], me[5], me[8]
  2238. );
  2239. return this;
  2240. },
  2241. multiplyVector3: function ( vector ) {
  2242. console.warn( 'DEPRECATED: Matrix3\'s .multiplyVector3() has been removed. Use vector.applyMatrix3( matrix ) instead.' );
  2243. return vector.applyMatrix3( this );
  2244. },
  2245. multiplyVector3Array: function() {
  2246. var v1 = new THREE.Vector3();
  2247. return function ( a ) {
  2248. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2249. v1.x = a[ i ];
  2250. v1.y = a[ i + 1 ];
  2251. v1.z = a[ i + 2 ];
  2252. v1.applyMatrix3(this);
  2253. a[ i ] = v1.x;
  2254. a[ i + 1 ] = v1.y;
  2255. a[ i + 2 ] = v1.z;
  2256. }
  2257. return a;
  2258. };
  2259. }(),
  2260. multiplyScalar: function ( s ) {
  2261. var te = this.elements;
  2262. te[0] *= s; te[3] *= s; te[6] *= s;
  2263. te[1] *= s; te[4] *= s; te[7] *= s;
  2264. te[2] *= s; te[5] *= s; te[8] *= s;
  2265. return this;
  2266. },
  2267. determinant: function () {
  2268. var te = this.elements;
  2269. var a = te[0], b = te[1], c = te[2],
  2270. d = te[3], e = te[4], f = te[5],
  2271. g = te[6], h = te[7], i = te[8];
  2272. return a*e*i - a*f*h - b*d*i + b*f*g + c*d*h - c*e*g;
  2273. },
  2274. getInverse: function ( matrix, throwOnInvertible ) {
  2275. // input: THREE.Matrix4
  2276. // ( based on http://code.google.com/p/webgl-mjs/ )
  2277. var me = matrix.elements;
  2278. var te = this.elements;
  2279. te[ 0 ] = me[10] * me[5] - me[6] * me[9];
  2280. te[ 1 ] = - me[10] * me[1] + me[2] * me[9];
  2281. te[ 2 ] = me[6] * me[1] - me[2] * me[5];
  2282. te[ 3 ] = - me[10] * me[4] + me[6] * me[8];
  2283. te[ 4 ] = me[10] * me[0] - me[2] * me[8];
  2284. te[ 5 ] = - me[6] * me[0] + me[2] * me[4];
  2285. te[ 6 ] = me[9] * me[4] - me[5] * me[8];
  2286. te[ 7 ] = - me[9] * me[0] + me[1] * me[8];
  2287. te[ 8 ] = me[5] * me[0] - me[1] * me[4];
  2288. var det = me[ 0 ] * te[ 0 ] + me[ 1 ] * te[ 3 ] + me[ 2 ] * te[ 6 ];
  2289. // no inverse
  2290. if ( det === 0 ) {
  2291. var msg = "Matrix3.getInverse(): can't invert matrix, determinant is 0";
  2292. if ( throwOnInvertible || false ) {
  2293. throw new Error( msg );
  2294. } else {
  2295. console.warn( msg );
  2296. }
  2297. this.identity();
  2298. return this;
  2299. }
  2300. this.multiplyScalar( 1.0 / det );
  2301. return this;
  2302. },
  2303. transpose: function () {
  2304. var tmp, m = this.elements;
  2305. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  2306. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  2307. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  2308. return this;
  2309. },
  2310. getNormalMatrix: function ( m ) {
  2311. // input: THREE.Matrix4
  2312. this.getInverse( m ).transpose();
  2313. return this;
  2314. },
  2315. transposeIntoArray: function ( r ) {
  2316. var m = this.elements;
  2317. r[ 0 ] = m[ 0 ];
  2318. r[ 1 ] = m[ 3 ];
  2319. r[ 2 ] = m[ 6 ];
  2320. r[ 3 ] = m[ 1 ];
  2321. r[ 4 ] = m[ 4 ];
  2322. r[ 5 ] = m[ 7 ];
  2323. r[ 6 ] = m[ 2 ];
  2324. r[ 7 ] = m[ 5 ];
  2325. r[ 8 ] = m[ 8 ];
  2326. return this;
  2327. },
  2328. clone: function () {
  2329. var te = this.elements;
  2330. return new THREE.Matrix3(
  2331. te[0], te[3], te[6],
  2332. te[1], te[4], te[7],
  2333. te[2], te[5], te[8]
  2334. );
  2335. }
  2336. };
  2337. /**
  2338. * @author mrdoob / http://mrdoob.com/
  2339. * @author supereggbert / http://www.paulbrunt.co.uk/
  2340. * @author philogb / http://blog.thejit.org/
  2341. * @author jordi_ros / http://plattsoft.com
  2342. * @author D1plo1d / http://github.com/D1plo1d
  2343. * @author alteredq / http://alteredqualia.com/
  2344. * @author mikael emtinger / http://gomo.se/
  2345. * @author timknip / http://www.floorplanner.com/
  2346. * @author bhouston / http://exocortex.com
  2347. * @author WestLangley / http://github.com/WestLangley
  2348. */
  2349. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2350. this.elements = new Float32Array( 16 );
  2351. // TODO: if n11 is undefined, then just set to identity, otherwise copy all other values into matrix
  2352. // we should not support semi specification of Matrix4, it is just weird.
  2353. var te = this.elements;
  2354. te[0] = ( n11 !== undefined ) ? n11 : 1; te[4] = n12 || 0; te[8] = n13 || 0; te[12] = n14 || 0;
  2355. te[1] = n21 || 0; te[5] = ( n22 !== undefined ) ? n22 : 1; te[9] = n23 || 0; te[13] = n24 || 0;
  2356. te[2] = n31 || 0; te[6] = n32 || 0; te[10] = ( n33 !== undefined ) ? n33 : 1; te[14] = n34 || 0;
  2357. te[3] = n41 || 0; te[7] = n42 || 0; te[11] = n43 || 0; te[15] = ( n44 !== undefined ) ? n44 : 1;
  2358. };
  2359. THREE.Matrix4.prototype = {
  2360. constructor: THREE.Matrix4,
  2361. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  2362. var te = this.elements;
  2363. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  2364. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  2365. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  2366. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  2367. return this;
  2368. },
  2369. identity: function () {
  2370. this.set(
  2371. 1, 0, 0, 0,
  2372. 0, 1, 0, 0,
  2373. 0, 0, 1, 0,
  2374. 0, 0, 0, 1
  2375. );
  2376. return this;
  2377. },
  2378. copy: function ( m ) {
  2379. this.elements.set( m.elements );
  2380. return this;
  2381. },
  2382. extractPosition: function ( m ) {
  2383. console.warn( 'DEPRECATED: Matrix4\'s .extractPosition() has been renamed to .copyPosition().' );
  2384. return this.copyPosition( m );
  2385. },
  2386. copyPosition: function ( m ) {
  2387. var te = this.elements;
  2388. var me = m.elements;
  2389. te[12] = me[12];
  2390. te[13] = me[13];
  2391. te[14] = me[14];
  2392. return this;
  2393. },
  2394. extractRotation: function () {
  2395. var v1 = new THREE.Vector3();
  2396. return function ( m ) {
  2397. var te = this.elements;
  2398. var me = m.elements;
  2399. var scaleX = 1 / v1.set( me[0], me[1], me[2] ).length();
  2400. var scaleY = 1 / v1.set( me[4], me[5], me[6] ).length();
  2401. var scaleZ = 1 / v1.set( me[8], me[9], me[10] ).length();
  2402. te[0] = me[0] * scaleX;
  2403. te[1] = me[1] * scaleX;
  2404. te[2] = me[2] * scaleX;
  2405. te[4] = me[4] * scaleY;
  2406. te[5] = me[5] * scaleY;
  2407. te[6] = me[6] * scaleY;
  2408. te[8] = me[8] * scaleZ;
  2409. te[9] = me[9] * scaleZ;
  2410. te[10] = me[10] * scaleZ;
  2411. return this;
  2412. };
  2413. }(),
  2414. makeRotationFromEuler: function ( euler ) {
  2415. if ( typeof euler['order'] === undefined ) {
  2416. console.error( 'ERROR: Matrix\'s .makeRotationFromEuler() now expects a Euler rotation rather than a Vector3 and order. Please update your code.' );
  2417. }
  2418. var te = this.elements;
  2419. var x = euler.x, y = euler.y, z = euler.z;
  2420. var a = Math.cos( x ), b = Math.sin( x );
  2421. var c = Math.cos( y ), d = Math.sin( y );
  2422. var e = Math.cos( z ), f = Math.sin( z );
  2423. if ( euler.order === undefined || euler.order === 'XYZ' ) {
  2424. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2425. te[0] = c * e;
  2426. te[4] = - c * f;
  2427. te[8] = d;
  2428. te[1] = af + be * d;
  2429. te[5] = ae - bf * d;
  2430. te[9] = - b * c;
  2431. te[2] = bf - ae * d;
  2432. te[6] = be + af * d;
  2433. te[10] = a * c;
  2434. } else if ( euler.order === 'YXZ' ) {
  2435. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2436. te[0] = ce + df * b;
  2437. te[4] = de * b - cf;
  2438. te[8] = a * d;
  2439. te[1] = a * f;
  2440. te[5] = a * e;
  2441. te[9] = - b;
  2442. te[2] = cf * b - de;
  2443. te[6] = df + ce * b;
  2444. te[10] = a * c;
  2445. } else if ( euler.order === 'ZXY' ) {
  2446. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  2447. te[0] = ce - df * b;
  2448. te[4] = - a * f;
  2449. te[8] = de + cf * b;
  2450. te[1] = cf + de * b;
  2451. te[5] = a * e;
  2452. te[9] = df - ce * b;
  2453. te[2] = - a * d;
  2454. te[6] = b;
  2455. te[10] = a * c;
  2456. } else if ( euler.order === 'ZYX' ) {
  2457. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  2458. te[0] = c * e;
  2459. te[4] = be * d - af;
  2460. te[8] = ae * d + bf;
  2461. te[1] = c * f;
  2462. te[5] = bf * d + ae;
  2463. te[9] = af * d - be;
  2464. te[2] = - d;
  2465. te[6] = b * c;
  2466. te[10] = a * c;
  2467. } else if ( euler.order === 'YZX' ) {
  2468. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2469. te[0] = c * e;
  2470. te[4] = bd - ac * f;
  2471. te[8] = bc * f + ad;
  2472. te[1] = f;
  2473. te[5] = a * e;
  2474. te[9] = - b * e;
  2475. te[2] = - d * e;
  2476. te[6] = ad * f + bc;
  2477. te[10] = ac - bd * f;
  2478. } else if ( euler.order === 'XZY' ) {
  2479. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  2480. te[0] = c * e;
  2481. te[4] = - f;
  2482. te[8] = d * e;
  2483. te[1] = ac * f + bd;
  2484. te[5] = a * e;
  2485. te[9] = ad * f - bc;
  2486. te[2] = bc * f - ad;
  2487. te[6] = b * e;
  2488. te[10] = bd * f + ac;
  2489. }
  2490. // last column
  2491. te[3] = 0;
  2492. te[7] = 0;
  2493. te[11] = 0;
  2494. // bottom row
  2495. te[12] = 0;
  2496. te[13] = 0;
  2497. te[14] = 0;
  2498. te[15] = 1;
  2499. return this;
  2500. },
  2501. setRotationFromQuaternion: function ( q ) {
  2502. console.warn( 'DEPRECATED: Matrix4\'s .setRotationFromQuaternion() has been deprecated in favor of makeRotationFromQuaternion. Please update your code.' );
  2503. return this.makeRotationFromQuaternion( q );
  2504. },
  2505. makeRotationFromQuaternion: function ( q ) {
  2506. var te = this.elements;
  2507. var x = q.x, y = q.y, z = q.z, w = q.w;
  2508. var x2 = x + x, y2 = y + y, z2 = z + z;
  2509. var xx = x * x2, xy = x * y2, xz = x * z2;
  2510. var yy = y * y2, yz = y * z2, zz = z * z2;
  2511. var wx = w * x2, wy = w * y2, wz = w * z2;
  2512. te[0] = 1 - ( yy + zz );
  2513. te[4] = xy - wz;
  2514. te[8] = xz + wy;
  2515. te[1] = xy + wz;
  2516. te[5] = 1 - ( xx + zz );
  2517. te[9] = yz - wx;
  2518. te[2] = xz - wy;
  2519. te[6] = yz + wx;
  2520. te[10] = 1 - ( xx + yy );
  2521. // last column
  2522. te[3] = 0;
  2523. te[7] = 0;
  2524. te[11] = 0;
  2525. // bottom row
  2526. te[12] = 0;
  2527. te[13] = 0;
  2528. te[14] = 0;
  2529. te[15] = 1;
  2530. return this;
  2531. },
  2532. lookAt: function() {
  2533. var x = new THREE.Vector3();
  2534. var y = new THREE.Vector3();
  2535. var z = new THREE.Vector3();
  2536. return function ( eye, target, up ) {
  2537. var te = this.elements;
  2538. z.subVectors( eye, target ).normalize();
  2539. if ( z.length() === 0 ) {
  2540. z.z = 1;
  2541. }
  2542. x.crossVectors( up, z ).normalize();
  2543. if ( x.length() === 0 ) {
  2544. z.x += 0.0001;
  2545. x.crossVectors( up, z ).normalize();
  2546. }
  2547. y.crossVectors( z, x );
  2548. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  2549. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  2550. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  2551. return this;
  2552. };
  2553. }(),
  2554. multiply: function ( m, n ) {
  2555. if ( n !== undefined ) {
  2556. console.warn( 'DEPRECATED: Matrix4\'s .multiply() now only accepts one argument. Use .multiplyMatrices( a, b ) instead.' );
  2557. return this.multiplyMatrices( m, n );
  2558. }
  2559. return this.multiplyMatrices( this, m );
  2560. },
  2561. multiplyMatrices: function ( a, b ) {
  2562. var ae = a.elements;
  2563. var be = b.elements;
  2564. var te = this.elements;
  2565. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  2566. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  2567. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  2568. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  2569. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  2570. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  2571. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  2572. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  2573. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  2574. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  2575. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  2576. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  2577. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  2578. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  2579. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  2580. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  2581. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  2582. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  2583. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  2584. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  2585. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  2586. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  2587. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  2588. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  2589. return this;
  2590. },
  2591. multiplyToArray: function ( a, b, r ) {
  2592. var te = this.elements;
  2593. this.multiplyMatrices( a, b );
  2594. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  2595. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  2596. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  2597. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  2598. return this;
  2599. },
  2600. multiplyScalar: function ( s ) {
  2601. var te = this.elements;
  2602. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  2603. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  2604. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  2605. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  2606. return this;
  2607. },
  2608. multiplyVector3: function ( vector ) {
  2609. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector3() has been removed. Use vector.applyMatrix4( matrix ) or vector.applyProjection( matrix ) instead.' );
  2610. return vector.applyProjection( this );
  2611. },
  2612. multiplyVector4: function ( vector ) {
  2613. console.warn( 'DEPRECATED: Matrix4\'s .multiplyVector4() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2614. return vector.applyMatrix4( this );
  2615. },
  2616. multiplyVector3Array: function() {
  2617. var v1 = new THREE.Vector3();
  2618. return function ( a ) {
  2619. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  2620. v1.x = a[ i ];
  2621. v1.y = a[ i + 1 ];
  2622. v1.z = a[ i + 2 ];
  2623. v1.applyProjection( this );
  2624. a[ i ] = v1.x;
  2625. a[ i + 1 ] = v1.y;
  2626. a[ i + 2 ] = v1.z;
  2627. }
  2628. return a;
  2629. };
  2630. }(),
  2631. rotateAxis: function ( v ) {
  2632. console.warn( 'DEPRECATED: Matrix4\'s .rotateAxis() has been removed. Use Vector3.transformDirection( matrix ) instead.' );
  2633. v.transformDirection( this );
  2634. },
  2635. crossVector: function ( vector ) {
  2636. console.warn( 'DEPRECATED: Matrix4\'s .crossVector() has been removed. Use vector.applyMatrix4( matrix ) instead.' );
  2637. return vector.applyMatrix4( this );
  2638. },
  2639. determinant: function () {
  2640. var te = this.elements;
  2641. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  2642. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  2643. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  2644. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  2645. //TODO: make this more efficient
  2646. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  2647. return (
  2648. n41 * (
  2649. +n14 * n23 * n32
  2650. -n13 * n24 * n32
  2651. -n14 * n22 * n33
  2652. +n12 * n24 * n33
  2653. +n13 * n22 * n34
  2654. -n12 * n23 * n34
  2655. ) +
  2656. n42 * (
  2657. +n11 * n23 * n34
  2658. -n11 * n24 * n33
  2659. +n14 * n21 * n33
  2660. -n13 * n21 * n34
  2661. +n13 * n24 * n31
  2662. -n14 * n23 * n31
  2663. ) +
  2664. n43 * (
  2665. +n11 * n24 * n32
  2666. -n11 * n22 * n34
  2667. -n14 * n21 * n32
  2668. +n12 * n21 * n34
  2669. +n14 * n22 * n31
  2670. -n12 * n24 * n31
  2671. ) +
  2672. n44 * (
  2673. -n13 * n22 * n31
  2674. -n11 * n23 * n32
  2675. +n11 * n22 * n33
  2676. +n13 * n21 * n32
  2677. -n12 * n21 * n33
  2678. +n12 * n23 * n31
  2679. )
  2680. );
  2681. },
  2682. transpose: function () {
  2683. var te = this.elements;
  2684. var tmp;
  2685. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  2686. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  2687. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  2688. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  2689. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  2690. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  2691. return this;
  2692. },
  2693. flattenToArray: function ( flat ) {
  2694. var te = this.elements;
  2695. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  2696. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  2697. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  2698. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  2699. return flat;
  2700. },
  2701. flattenToArrayOffset: function( flat, offset ) {
  2702. var te = this.elements;
  2703. flat[ offset ] = te[0];
  2704. flat[ offset + 1 ] = te[1];
  2705. flat[ offset + 2 ] = te[2];
  2706. flat[ offset + 3 ] = te[3];
  2707. flat[ offset + 4 ] = te[4];
  2708. flat[ offset + 5 ] = te[5];
  2709. flat[ offset + 6 ] = te[6];
  2710. flat[ offset + 7 ] = te[7];
  2711. flat[ offset + 8 ] = te[8];
  2712. flat[ offset + 9 ] = te[9];
  2713. flat[ offset + 10 ] = te[10];
  2714. flat[ offset + 11 ] = te[11];
  2715. flat[ offset + 12 ] = te[12];
  2716. flat[ offset + 13 ] = te[13];
  2717. flat[ offset + 14 ] = te[14];
  2718. flat[ offset + 15 ] = te[15];
  2719. return flat;
  2720. },
  2721. getPosition: function() {
  2722. var v1 = new THREE.Vector3();
  2723. return function () {
  2724. console.warn( 'DEPRECATED: Matrix4\'s .getPosition() has been removed. Use Vector3.getPositionFromMatrix( matrix ) instead.' );
  2725. var te = this.elements;
  2726. return v1.set( te[12], te[13], te[14] );
  2727. };
  2728. }(),
  2729. setPosition: function ( v ) {
  2730. var te = this.elements;
  2731. te[12] = v.x;
  2732. te[13] = v.y;
  2733. te[14] = v.z;
  2734. return this;
  2735. },
  2736. getInverse: function ( m, throwOnInvertible ) {
  2737. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  2738. var te = this.elements;
  2739. var me = m.elements;
  2740. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  2741. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  2742. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  2743. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  2744. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  2745. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  2746. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  2747. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  2748. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  2749. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  2750. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  2751. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  2752. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  2753. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  2754. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  2755. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  2756. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  2757. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  2758. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  2759. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  2760. var det = n11 * te[ 0 ] + n21 * te[ 4 ] + n31 * te[ 8 ] + n41 * te[ 12 ];
  2761. if ( det == 0 ) {
  2762. var msg = "Matrix4.getInverse(): can't invert matrix, determinant is 0";
  2763. if ( throwOnInvertible || false ) {
  2764. throw new Error( msg );
  2765. } else {
  2766. console.warn( msg );
  2767. }
  2768. this.identity();
  2769. return this;
  2770. }
  2771. this.multiplyScalar( 1 / det );
  2772. return this;
  2773. },
  2774. translate: function ( v ) {
  2775. console.warn( 'DEPRECATED: Matrix4\'s .translate() has been removed.');
  2776. },
  2777. rotateX: function ( angle ) {
  2778. console.warn( 'DEPRECATED: Matrix4\'s .rotateX() has been removed.');
  2779. },
  2780. rotateY: function ( angle ) {
  2781. console.warn( 'DEPRECATED: Matrix4\'s .rotateY() has been removed.');
  2782. },
  2783. rotateZ: function ( angle ) {
  2784. console.warn( 'DEPRECATED: Matrix4\'s .rotateZ() has been removed.');
  2785. },
  2786. rotateByAxis: function ( axis, angle ) {
  2787. console.warn( 'DEPRECATED: Matrix4\'s .rotateByAxis() has been removed.');
  2788. },
  2789. scale: function ( v ) {
  2790. var te = this.elements;
  2791. var x = v.x, y = v.y, z = v.z;
  2792. te[0] *= x; te[4] *= y; te[8] *= z;
  2793. te[1] *= x; te[5] *= y; te[9] *= z;
  2794. te[2] *= x; te[6] *= y; te[10] *= z;
  2795. te[3] *= x; te[7] *= y; te[11] *= z;
  2796. return this;
  2797. },
  2798. getMaxScaleOnAxis: function () {
  2799. var te = this.elements;
  2800. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2801. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2802. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2803. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2804. },
  2805. makeTranslation: function ( x, y, z ) {
  2806. this.set(
  2807. 1, 0, 0, x,
  2808. 0, 1, 0, y,
  2809. 0, 0, 1, z,
  2810. 0, 0, 0, 1
  2811. );
  2812. return this;
  2813. },
  2814. makeRotationX: function ( theta ) {
  2815. var c = Math.cos( theta ), s = Math.sin( theta );
  2816. this.set(
  2817. 1, 0, 0, 0,
  2818. 0, c, -s, 0,
  2819. 0, s, c, 0,
  2820. 0, 0, 0, 1
  2821. );
  2822. return this;
  2823. },
  2824. makeRotationY: function ( theta ) {
  2825. var c = Math.cos( theta ), s = Math.sin( theta );
  2826. this.set(
  2827. c, 0, s, 0,
  2828. 0, 1, 0, 0,
  2829. -s, 0, c, 0,
  2830. 0, 0, 0, 1
  2831. );
  2832. return this;
  2833. },
  2834. makeRotationZ: function ( theta ) {
  2835. var c = Math.cos( theta ), s = Math.sin( theta );
  2836. this.set(
  2837. c, -s, 0, 0,
  2838. s, c, 0, 0,
  2839. 0, 0, 1, 0,
  2840. 0, 0, 0, 1
  2841. );
  2842. return this;
  2843. },
  2844. makeRotationAxis: function ( axis, angle ) {
  2845. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2846. var c = Math.cos( angle );
  2847. var s = Math.sin( angle );
  2848. var t = 1 - c;
  2849. var x = axis.x, y = axis.y, z = axis.z;
  2850. var tx = t * x, ty = t * y;
  2851. this.set(
  2852. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2853. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2854. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2855. 0, 0, 0, 1
  2856. );
  2857. return this;
  2858. },
  2859. makeScale: function ( x, y, z ) {
  2860. this.set(
  2861. x, 0, 0, 0,
  2862. 0, y, 0, 0,
  2863. 0, 0, z, 0,
  2864. 0, 0, 0, 1
  2865. );
  2866. return this;
  2867. },
  2868. compose: function ( position, quaternion, scale ) {
  2869. this.makeRotationFromQuaternion( quaternion );
  2870. this.scale( scale );
  2871. this.setPosition( position );
  2872. return this;
  2873. },
  2874. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2875. var te = this.elements;
  2876. var x = 2 * near / ( right - left );
  2877. var y = 2 * near / ( top - bottom );
  2878. var a = ( right + left ) / ( right - left );
  2879. var b = ( top + bottom ) / ( top - bottom );
  2880. var c = - ( far + near ) / ( far - near );
  2881. var d = - 2 * far * near / ( far - near );
  2882. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2883. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2884. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2885. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2886. return this;
  2887. },
  2888. makePerspective: function ( fov, aspect, near, far ) {
  2889. var ymax = near * Math.tan( THREE.Math.degToRad( fov * 0.5 ) );
  2890. var ymin = - ymax;
  2891. var xmin = ymin * aspect;
  2892. var xmax = ymax * aspect;
  2893. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2894. },
  2895. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2896. var te = this.elements;
  2897. var w = right - left;
  2898. var h = top - bottom;
  2899. var p = far - near;
  2900. var x = ( right + left ) / w;
  2901. var y = ( top + bottom ) / h;
  2902. var z = ( far + near ) / p;
  2903. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2904. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2905. te[2] = 0; te[6] = 0; te[10] = -2/p; te[14] = -z;
  2906. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2907. return this;
  2908. },
  2909. fromArray: function ( array ) {
  2910. this.elements.set( array );
  2911. return this;
  2912. },
  2913. toArray: function () {
  2914. var te = this.elements;
  2915. return [
  2916. te[ 0 ], te[ 1 ], te[ 2 ], te[ 3 ],
  2917. te[ 4 ], te[ 5 ], te[ 6 ], te[ 7 ],
  2918. te[ 8 ], te[ 9 ], te[ 10 ], te[ 11 ],
  2919. te[ 12 ], te[ 13 ], te[ 14 ], te[ 15 ]
  2920. ];
  2921. },
  2922. clone: function () {
  2923. var te = this.elements;
  2924. return new THREE.Matrix4(
  2925. te[0], te[4], te[8], te[12],
  2926. te[1], te[5], te[9], te[13],
  2927. te[2], te[6], te[10], te[14],
  2928. te[3], te[7], te[11], te[15]
  2929. );
  2930. }
  2931. };
  2932. THREE.extend( THREE.Matrix4.prototype, {
  2933. decompose: function () {
  2934. var x = new THREE.Vector3();
  2935. var y = new THREE.Vector3();
  2936. var z = new THREE.Vector3();
  2937. var matrix = new THREE.Matrix4();
  2938. return function ( position, quaternion, scale ) {
  2939. var te = this.elements;
  2940. // grab the axis vectors
  2941. x.set( te[0], te[1], te[2] );
  2942. y.set( te[4], te[5], te[6] );
  2943. z.set( te[8], te[9], te[10] );
  2944. position = ( position instanceof THREE.Vector3 ) ? position : new THREE.Vector3();
  2945. quaternion = ( quaternion instanceof THREE.Quaternion ) ? quaternion : new THREE.Quaternion();
  2946. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  2947. scale.x = x.length();
  2948. scale.y = y.length();
  2949. scale.z = z.length();
  2950. position.x = te[12];
  2951. position.y = te[13];
  2952. position.z = te[14];
  2953. // scale the rotation part
  2954. matrix.copy( this );
  2955. matrix.elements[0] /= scale.x;
  2956. matrix.elements[1] /= scale.x;
  2957. matrix.elements[2] /= scale.x;
  2958. matrix.elements[4] /= scale.y;
  2959. matrix.elements[5] /= scale.y;
  2960. matrix.elements[6] /= scale.y;
  2961. matrix.elements[8] /= scale.z;
  2962. matrix.elements[9] /= scale.z;
  2963. matrix.elements[10] /= scale.z;
  2964. quaternion.setFromRotationMatrix( matrix );
  2965. return [ position, quaternion, scale ];
  2966. };
  2967. }()
  2968. } );
  2969. /**
  2970. * @author bhouston / http://exocortex.com
  2971. */
  2972. THREE.Ray = function ( origin, direction ) {
  2973. this.origin = ( origin !== undefined ) ? origin : new THREE.Vector3();
  2974. this.direction = ( direction !== undefined ) ? direction : new THREE.Vector3();
  2975. };
  2976. THREE.Ray.prototype = {
  2977. constructor: THREE.Ray,
  2978. set: function ( origin, direction ) {
  2979. this.origin.copy( origin );
  2980. this.direction.copy( direction );
  2981. return this;
  2982. },
  2983. copy: function ( ray ) {
  2984. this.origin.copy( ray.origin );
  2985. this.direction.copy( ray.direction );
  2986. return this;
  2987. },
  2988. at: function( t, optionalTarget ) {
  2989. var result = optionalTarget || new THREE.Vector3();
  2990. return result.copy( this.direction ).multiplyScalar( t ).add( this.origin );
  2991. },
  2992. recast: function() {
  2993. var v1 = new THREE.Vector3();
  2994. return function ( t ) {
  2995. this.origin.copy( this.at( t, v1 ) );
  2996. return this;
  2997. };
  2998. }(),
  2999. closestPointToPoint: function ( point, optionalTarget ) {
  3000. var result = optionalTarget || new THREE.Vector3();
  3001. result.subVectors( point, this.origin );
  3002. var directionDistance = result.dot( this.direction );
  3003. return result.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3004. },
  3005. distanceToPoint: function() {
  3006. var v1 = new THREE.Vector3();
  3007. return function ( point ) {
  3008. var directionDistance = v1.subVectors( point, this.origin ).dot( this.direction );
  3009. v1.copy( this.direction ).multiplyScalar( directionDistance ).add( this.origin );
  3010. return v1.distanceTo( point );
  3011. };
  3012. }(),
  3013. isIntersectionSphere: function( sphere ) {
  3014. return ( this.distanceToPoint( sphere.center ) <= sphere.radius );
  3015. },
  3016. isIntersectionPlane: function ( plane ) {
  3017. // check if the line and plane are non-perpendicular, if they
  3018. // eventually they will intersect.
  3019. var denominator = plane.normal.dot( this.direction );
  3020. if ( denominator != 0 ) {
  3021. return true;
  3022. }
  3023. // line is coplanar, return origin
  3024. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3025. return true;
  3026. }
  3027. return false;
  3028. },
  3029. distanceToPlane: function ( plane ) {
  3030. var denominator = plane.normal.dot( this.direction );
  3031. if ( denominator == 0 ) {
  3032. // line is coplanar, return origin
  3033. if( plane.distanceToPoint( this.origin ) == 0 ) {
  3034. return 0;
  3035. }
  3036. // Unsure if this is the correct method to handle this case.
  3037. return undefined;
  3038. }
  3039. var t = - ( this.origin.dot( plane.normal ) + plane.constant ) / denominator;
  3040. return t;
  3041. },
  3042. intersectPlane: function ( plane, optionalTarget ) {
  3043. var t = this.distanceToPlane( plane );
  3044. if ( t === undefined ) {
  3045. return undefined;
  3046. }
  3047. return this.at( t, optionalTarget );
  3048. },
  3049. applyMatrix4: function ( matrix4 ) {
  3050. this.direction.add( this.origin ).applyMatrix4( matrix4 );
  3051. this.origin.applyMatrix4( matrix4 );
  3052. this.direction.sub( this.origin );
  3053. return this;
  3054. },
  3055. equals: function ( ray ) {
  3056. return ray.origin.equals( this.origin ) && ray.direction.equals( this.direction );
  3057. },
  3058. clone: function () {
  3059. return new THREE.Ray().copy( this );
  3060. }
  3061. };
  3062. /**
  3063. * @author bhouston / http://exocortex.com
  3064. * @author mrdoob / http://mrdoob.com/
  3065. */
  3066. THREE.Sphere = function ( center, radius ) {
  3067. this.center = ( center !== undefined ) ? center : new THREE.Vector3();
  3068. this.radius = ( radius !== undefined ) ? radius : 0;
  3069. };
  3070. THREE.Sphere.prototype = {
  3071. constructor: THREE.Sphere,
  3072. set: function ( center, radius ) {
  3073. this.center.copy( center );
  3074. this.radius = radius;
  3075. return this;
  3076. },
  3077. setFromPoints: function ( points ) {
  3078. var radiusSq, maxRadiusSq = 0;
  3079. for ( var i = 0, il = points.length; i < il; i ++ ) {
  3080. radiusSq = points[ i ].lengthSq();
  3081. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  3082. }
  3083. this.center.set( 0, 0, 0 );
  3084. this.radius = Math.sqrt( maxRadiusSq );
  3085. return this;
  3086. },
  3087. copy: function ( sphere ) {
  3088. this.center.copy( sphere.center );
  3089. this.radius = sphere.radius;
  3090. return this;
  3091. },
  3092. empty: function () {
  3093. return ( this.radius <= 0 );
  3094. },
  3095. containsPoint: function ( point ) {
  3096. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  3097. },
  3098. distanceToPoint: function ( point ) {
  3099. return ( point.distanceTo( this.center ) - this.radius );
  3100. },
  3101. intersectsSphere: function ( sphere ) {
  3102. var radiusSum = this.radius + sphere.radius;
  3103. return sphere.center.distanceToSquared( this.center ) <= ( radiusSum * radiusSum );
  3104. },
  3105. clampPoint: function ( point, optionalTarget ) {
  3106. var deltaLengthSq = this.center.distanceToSquared( point );
  3107. var result = optionalTarget || new THREE.Vector3();
  3108. result.copy( point );
  3109. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  3110. result.sub( this.center ).normalize();
  3111. result.multiplyScalar( this.radius ).add( this.center );
  3112. }
  3113. return result;
  3114. },
  3115. getBoundingBox: function ( optionalTarget ) {
  3116. var box = optionalTarget || new THREE.Box3();
  3117. box.set( this.center, this.center );
  3118. box.expandByScalar( this.radius );
  3119. return box;
  3120. },
  3121. applyMatrix4: function ( matrix ) {
  3122. this.center.applyMatrix4( matrix );
  3123. this.radius = this.radius * matrix.getMaxScaleOnAxis();
  3124. return this;
  3125. },
  3126. translate: function ( offset ) {
  3127. this.center.add( offset );
  3128. return this;
  3129. },
  3130. equals: function ( sphere ) {
  3131. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  3132. },
  3133. clone: function () {
  3134. return new THREE.Sphere().copy( this );
  3135. }
  3136. };
  3137. /**
  3138. * @author mrdoob / http://mrdoob.com/
  3139. * @author alteredq / http://alteredqualia.com/
  3140. * @author bhouston / http://exocortex.com
  3141. */
  3142. THREE.Frustum = function ( p0, p1, p2, p3, p4, p5 ) {
  3143. this.planes = [
  3144. ( p0 !== undefined ) ? p0 : new THREE.Plane(),
  3145. ( p1 !== undefined ) ? p1 : new THREE.Plane(),
  3146. ( p2 !== undefined ) ? p2 : new THREE.Plane(),
  3147. ( p3 !== undefined ) ? p3 : new THREE.Plane(),
  3148. ( p4 !== undefined ) ? p4 : new THREE.Plane(),
  3149. ( p5 !== undefined ) ? p5 : new THREE.Plane()
  3150. ];
  3151. };
  3152. THREE.Frustum.prototype = {
  3153. constructor: THREE.Frustum,
  3154. set: function ( p0, p1, p2, p3, p4, p5 ) {
  3155. var planes = this.planes;
  3156. planes[0].copy( p0 );
  3157. planes[1].copy( p1 );
  3158. planes[2].copy( p2 );
  3159. planes[3].copy( p3 );
  3160. planes[4].copy( p4 );
  3161. planes[5].copy( p5 );
  3162. return this;
  3163. },
  3164. copy: function ( frustum ) {
  3165. var planes = this.planes;
  3166. for( var i = 0; i < 6; i ++ ) {
  3167. planes[i].copy( frustum.planes[i] );
  3168. }
  3169. return this;
  3170. },
  3171. setFromMatrix: function ( m ) {
  3172. var planes = this.planes;
  3173. var me = m.elements;
  3174. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  3175. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  3176. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  3177. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  3178. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 ).normalize();
  3179. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 ).normalize();
  3180. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 ).normalize();
  3181. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 ).normalize();
  3182. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 ).normalize();
  3183. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 ).normalize();
  3184. return this;
  3185. },
  3186. intersectsObject: function () {
  3187. var center = new THREE.Vector3();
  3188. return function ( object ) {
  3189. // this method is expanded inlined for performance reasons.
  3190. var matrix = object.matrixWorld;
  3191. var planes = this.planes;
  3192. var negRadius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  3193. center.getPositionFromMatrix( matrix );
  3194. for ( var i = 0; i < 6; i ++ ) {
  3195. var distance = planes[ i ].distanceToPoint( center );
  3196. if ( distance < negRadius ) {
  3197. return false;
  3198. }
  3199. }
  3200. return true;
  3201. };
  3202. }(),
  3203. intersectsSphere: function ( sphere ) {
  3204. var planes = this.planes;
  3205. var center = sphere.center;
  3206. var negRadius = -sphere.radius;
  3207. for ( var i = 0; i < 6; i ++ ) {
  3208. var distance = planes[ i ].distanceToPoint( center );
  3209. if ( distance < negRadius ) {
  3210. return false;
  3211. }
  3212. }
  3213. return true;
  3214. },
  3215. containsPoint: function ( point ) {
  3216. var planes = this.planes;
  3217. for ( var i = 0; i < 6; i ++ ) {
  3218. if ( planes[ i ].distanceToPoint( point ) < 0 ) {
  3219. return false;
  3220. }
  3221. }
  3222. return true;
  3223. },
  3224. clone: function () {
  3225. return new THREE.Frustum().copy( this );
  3226. }
  3227. };
  3228. /**
  3229. * @author bhouston / http://exocortex.com
  3230. */
  3231. THREE.Plane = function ( normal, constant ) {
  3232. this.normal = ( normal !== undefined ) ? normal : new THREE.Vector3( 1, 0, 0 );
  3233. this.constant = ( constant !== undefined ) ? constant : 0;
  3234. };
  3235. THREE.Plane.prototype = {
  3236. constructor: THREE.Plane,
  3237. set: function ( normal, constant ) {
  3238. this.normal.copy( normal );
  3239. this.constant = constant;
  3240. return this;
  3241. },
  3242. setComponents: function ( x, y, z, w ) {
  3243. this.normal.set( x, y, z );
  3244. this.constant = w;
  3245. return this;
  3246. },
  3247. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  3248. this.normal.copy( normal );
  3249. this.constant = - point.dot( this.normal ); // must be this.normal, not normal, as this.normal is normalized
  3250. return this;
  3251. },
  3252. setFromCoplanarPoints: function() {
  3253. var v1 = new THREE.Vector3();
  3254. var v2 = new THREE.Vector3();
  3255. return function ( a, b, c ) {
  3256. var normal = v1.subVectors( c, b ).cross( v2.subVectors( a, b ) ).normalize();
  3257. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  3258. this.setFromNormalAndCoplanarPoint( normal, a );
  3259. return this;
  3260. };
  3261. }(),
  3262. copy: function ( plane ) {
  3263. this.normal.copy( plane.normal );
  3264. this.constant = plane.constant;
  3265. return this;
  3266. },
  3267. normalize: function () {
  3268. // Note: will lead to a divide by zero if the plane is invalid.
  3269. var inverseNormalLength = 1.0 / this.normal.length();
  3270. this.normal.multiplyScalar( inverseNormalLength );
  3271. this.constant *= inverseNormalLength;
  3272. return this;
  3273. },
  3274. negate: function () {
  3275. this.constant *= -1;
  3276. this.normal.negate();
  3277. return this;
  3278. },
  3279. distanceToPoint: function ( point ) {
  3280. return this.normal.dot( point ) + this.constant;
  3281. },
  3282. distanceToSphere: function ( sphere ) {
  3283. return this.distanceToPoint( sphere.center ) - sphere.radius;
  3284. },
  3285. projectPoint: function ( point, optionalTarget ) {
  3286. return this.orthoPoint( point, optionalTarget ).sub( point ).negate();
  3287. },
  3288. orthoPoint: function ( point, optionalTarget ) {
  3289. var perpendicularMagnitude = this.distanceToPoint( point );
  3290. var result = optionalTarget || new THREE.Vector3();
  3291. return result.copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  3292. },
  3293. isIntersectionLine: function ( line ) {
  3294. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  3295. var startSign = this.distanceToPoint( line.start );
  3296. var endSign = this.distanceToPoint( line.end );
  3297. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  3298. },
  3299. intersectLine: function() {
  3300. var v1 = new THREE.Vector3();
  3301. return function ( line, optionalTarget ) {
  3302. var result = optionalTarget || new THREE.Vector3();
  3303. var direction = line.delta( v1 );
  3304. var denominator = this.normal.dot( direction );
  3305. if ( denominator == 0 ) {
  3306. // line is coplanar, return origin
  3307. if( this.distanceToPoint( line.start ) == 0 ) {
  3308. return result.copy( line.start );
  3309. }
  3310. // Unsure if this is the correct method to handle this case.
  3311. return undefined;
  3312. }
  3313. var t = - ( line.start.dot( this.normal ) + this.constant ) / denominator;
  3314. if( t < 0 || t > 1 ) {
  3315. return undefined;
  3316. }
  3317. return result.copy( direction ).multiplyScalar( t ).add( line.start );
  3318. };
  3319. }(),
  3320. coplanarPoint: function ( optionalTarget ) {
  3321. var result = optionalTarget || new THREE.Vector3();
  3322. return result.copy( this.normal ).multiplyScalar( - this.constant );
  3323. },
  3324. applyMatrix4: function() {
  3325. var v1 = new THREE.Vector3();
  3326. var v2 = new THREE.Vector3();
  3327. return function ( matrix, optionalNormalMatrix ) {
  3328. // compute new normal based on theory here:
  3329. // http://www.songho.ca/opengl/gl_normaltransform.html
  3330. optionalNormalMatrix = optionalNormalMatrix || new THREE.Matrix3().getNormalMatrix( matrix );
  3331. var newNormal = v1.copy( this.normal ).applyMatrix3( optionalNormalMatrix );
  3332. var newCoplanarPoint = this.coplanarPoint( v2 );
  3333. newCoplanarPoint.applyMatrix4( matrix );
  3334. this.setFromNormalAndCoplanarPoint( newNormal, newCoplanarPoint );
  3335. return this;
  3336. };
  3337. }(),
  3338. translate: function ( offset ) {
  3339. this.constant = this.constant - offset.dot( this.normal );
  3340. return this;
  3341. },
  3342. equals: function ( plane ) {
  3343. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  3344. },
  3345. clone: function () {
  3346. return new THREE.Plane().copy( this );
  3347. }
  3348. };
  3349. /**
  3350. * @author alteredq / http://alteredqualia.com/
  3351. * @author mrdoob / http://mrdoob.com/
  3352. */
  3353. THREE.Math = {
  3354. PI2: Math.PI * 2,
  3355. generateUUID: function () {
  3356. // http://www.broofa.com/Tools/Math.uuid.htm
  3357. var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
  3358. var uuid = new Array(36);
  3359. var rnd = 0, r;
  3360. return function () {
  3361. for ( var i = 0; i < 36; i ++ ) {
  3362. if ( i == 8 || i == 13 || i == 18 || i == 23 ) {
  3363. uuid[ i ] = '-';
  3364. } else if ( i == 14 ) {
  3365. uuid[ i ] = '4';
  3366. } else {
  3367. if (rnd <= 0x02) rnd = 0x2000000 + (Math.random()*0x1000000)|0;
  3368. r = rnd & 0xf;
  3369. rnd = rnd >> 4;
  3370. uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
  3371. }
  3372. }
  3373. return uuid.join('');
  3374. };
  3375. }(),
  3376. // Clamp value to range <a, b>
  3377. clamp: function ( x, a, b ) {
  3378. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  3379. },
  3380. // Clamp value to range <a, inf)
  3381. clampBottom: function ( x, a ) {
  3382. return x < a ? a : x;
  3383. },
  3384. // Linear mapping from range <a1, a2> to range <b1, b2>
  3385. mapLinear: function ( x, a1, a2, b1, b2 ) {
  3386. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  3387. },
  3388. // http://en.wikipedia.org/wiki/Smoothstep
  3389. smoothstep: function ( x, min, max ) {
  3390. if ( x <= min ) return 0;
  3391. if ( x >= max ) return 1;
  3392. x = ( x - min )/( max - min );
  3393. return x*x*(3 - 2*x);
  3394. },
  3395. smootherstep: function ( x, min, max ) {
  3396. if ( x <= min ) return 0;
  3397. if ( x >= max ) return 1;
  3398. x = ( x - min )/( max - min );
  3399. return x*x*x*(x*(x*6 - 15) + 10);
  3400. },
  3401. // Random float from <0, 1> with 16 bits of randomness
  3402. // (standard Math.random() creates repetitive patterns when applied over larger space)
  3403. random16: function () {
  3404. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  3405. },
  3406. // Random integer from <low, high> interval
  3407. randInt: function ( low, high ) {
  3408. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  3409. },
  3410. // Random float from <low, high> interval
  3411. randFloat: function ( low, high ) {
  3412. return low + Math.random() * ( high - low );
  3413. },
  3414. // Random float from <-range/2, range/2> interval
  3415. randFloatSpread: function ( range ) {
  3416. return range * ( 0.5 - Math.random() );
  3417. },
  3418. sign: function ( x ) {
  3419. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  3420. },
  3421. degToRad: function() {
  3422. var degreeToRadiansFactor = Math.PI / 180;
  3423. return function ( degrees ) {
  3424. return degrees * degreeToRadiansFactor;
  3425. };
  3426. }(),
  3427. radToDeg: function() {
  3428. var radianToDegreesFactor = 180 / Math.PI;
  3429. return function ( radians ) {
  3430. return radians * radianToDegreesFactor;
  3431. };
  3432. }()
  3433. };
  3434. /**
  3435. * Spline from Tween.js, slightly optimized (and trashed)
  3436. * http://sole.github.com/tween.js/examples/05_spline.html
  3437. *
  3438. * @author mrdoob / http://mrdoob.com/
  3439. * @author alteredq / http://alteredqualia.com/
  3440. */
  3441. THREE.Spline = function ( points ) {
  3442. this.points = points;
  3443. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3444. point, intPoint, weight, w2, w3,
  3445. pa, pb, pc, pd;
  3446. this.initFromArray = function( a ) {
  3447. this.points = [];
  3448. for ( var i = 0; i < a.length; i++ ) {
  3449. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3450. }
  3451. };
  3452. this.getPoint = function ( k ) {
  3453. point = ( this.points.length - 1 ) * k;
  3454. intPoint = Math.floor( point );
  3455. weight = point - intPoint;
  3456. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3457. c[ 1 ] = intPoint;
  3458. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3459. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3460. pa = this.points[ c[ 0 ] ];
  3461. pb = this.points[ c[ 1 ] ];
  3462. pc = this.points[ c[ 2 ] ];
  3463. pd = this.points[ c[ 3 ] ];
  3464. w2 = weight * weight;
  3465. w3 = weight * w2;
  3466. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3467. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3468. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3469. return v3;
  3470. };
  3471. this.getControlPointsArray = function () {
  3472. var i, p, l = this.points.length,
  3473. coords = [];
  3474. for ( i = 0; i < l; i ++ ) {
  3475. p = this.points[ i ];
  3476. coords[ i ] = [ p.x, p.y, p.z ];
  3477. }
  3478. return coords;
  3479. };
  3480. // approximate length by summing linear segments
  3481. this.getLength = function ( nSubDivisions ) {
  3482. var i, index, nSamples, position,
  3483. point = 0, intPoint = 0, oldIntPoint = 0,
  3484. oldPosition = new THREE.Vector3(),
  3485. tmpVec = new THREE.Vector3(),
  3486. chunkLengths = [],
  3487. totalLength = 0;
  3488. // first point has 0 length
  3489. chunkLengths[ 0 ] = 0;
  3490. if ( !nSubDivisions ) nSubDivisions = 100;
  3491. nSamples = this.points.length * nSubDivisions;
  3492. oldPosition.copy( this.points[ 0 ] );
  3493. for ( i = 1; i < nSamples; i ++ ) {
  3494. index = i / nSamples;
  3495. position = this.getPoint( index );
  3496. tmpVec.copy( position );
  3497. totalLength += tmpVec.distanceTo( oldPosition );
  3498. oldPosition.copy( position );
  3499. point = ( this.points.length - 1 ) * index;
  3500. intPoint = Math.floor( point );
  3501. if ( intPoint != oldIntPoint ) {
  3502. chunkLengths[ intPoint ] = totalLength;
  3503. oldIntPoint = intPoint;
  3504. }
  3505. }
  3506. // last point ends with total length
  3507. chunkLengths[ chunkLengths.length ] = totalLength;
  3508. return { chunks: chunkLengths, total: totalLength };
  3509. };
  3510. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3511. var i, j,
  3512. index, indexCurrent, indexNext,
  3513. linearDistance, realDistance,
  3514. sampling, position,
  3515. newpoints = [],
  3516. tmpVec = new THREE.Vector3(),
  3517. sl = this.getLength();
  3518. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3519. for ( i = 1; i < this.points.length; i++ ) {
  3520. //tmpVec.copy( this.points[ i - 1 ] );
  3521. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3522. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3523. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3524. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3525. indexNext = i / ( this.points.length - 1 );
  3526. for ( j = 1; j < sampling - 1; j++ ) {
  3527. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3528. position = this.getPoint( index );
  3529. newpoints.push( tmpVec.copy( position ).clone() );
  3530. }
  3531. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3532. }
  3533. this.points = newpoints;
  3534. };
  3535. // Catmull-Rom
  3536. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3537. var v0 = ( p2 - p0 ) * 0.5,
  3538. v1 = ( p3 - p1 ) * 0.5;
  3539. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3540. };
  3541. };
  3542. /**
  3543. * @author bhouston / http://exocortex.com
  3544. * @author mrdoob / http://mrdoob.com/
  3545. */
  3546. THREE.Triangle = function ( a, b, c ) {
  3547. this.a = ( a !== undefined ) ? a : new THREE.Vector3();
  3548. this.b = ( b !== undefined ) ? b : new THREE.Vector3();
  3549. this.c = ( c !== undefined ) ? c : new THREE.Vector3();
  3550. };
  3551. THREE.Triangle.normal = function() {
  3552. var v0 = new THREE.Vector3();
  3553. return function ( a, b, c, optionalTarget ) {
  3554. var result = optionalTarget || new THREE.Vector3();
  3555. result.subVectors( c, b );
  3556. v0.subVectors( a, b );
  3557. result.cross( v0 );
  3558. var resultLengthSq = result.lengthSq();
  3559. if( resultLengthSq > 0 ) {
  3560. return result.multiplyScalar( 1 / Math.sqrt( resultLengthSq ) );
  3561. }
  3562. return result.set( 0, 0, 0 );
  3563. };
  3564. }();
  3565. // static/instance method to calculate barycoordinates
  3566. // based on: http://www.blackpawn.com/texts/pointinpoly/default.html
  3567. THREE.Triangle.barycoordFromPoint = function() {
  3568. var v0 = new THREE.Vector3();
  3569. var v1 = new THREE.Vector3();
  3570. var v2 = new THREE.Vector3();
  3571. return function ( point, a, b, c, optionalTarget ) {
  3572. v0.subVectors( c, a );
  3573. v1.subVectors( b, a );
  3574. v2.subVectors( point, a );
  3575. var dot00 = v0.dot( v0 );
  3576. var dot01 = v0.dot( v1 );
  3577. var dot02 = v0.dot( v2 );
  3578. var dot11 = v1.dot( v1 );
  3579. var dot12 = v1.dot( v2 );
  3580. var denom = ( dot00 * dot11 - dot01 * dot01 );
  3581. var result = optionalTarget || new THREE.Vector3();
  3582. // colinear or singular triangle
  3583. if( denom == 0 ) {
  3584. // arbitrary location outside of triangle?
  3585. // not sure if this is the best idea, maybe should be returning undefined
  3586. return result.set( -2, -1, -1 );
  3587. }
  3588. var invDenom = 1 / denom;
  3589. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  3590. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  3591. // barycoordinates must always sum to 1
  3592. return result.set( 1 - u - v, v, u );
  3593. };
  3594. }();
  3595. THREE.Triangle.containsPoint = function() {
  3596. var v1 = new THREE.Vector3();
  3597. return function ( point, a, b, c ) {
  3598. var result = THREE.Triangle.barycoordFromPoint( point, a, b, c, v1 );
  3599. return ( result.x >= 0 ) && ( result.y >= 0 ) && ( ( result.x + result.y ) <= 1 );
  3600. };
  3601. }();
  3602. THREE.Triangle.prototype = {
  3603. constructor: THREE.Triangle,
  3604. set: function ( a, b, c ) {
  3605. this.a.copy( a );
  3606. this.b.copy( b );
  3607. this.c.copy( c );
  3608. return this;
  3609. },
  3610. setFromPointsAndIndices: function ( points, i0, i1, i2 ) {
  3611. this.a.copy( points[i0] );
  3612. this.b.copy( points[i1] );
  3613. this.c.copy( points[i2] );
  3614. return this;
  3615. },
  3616. copy: function ( triangle ) {
  3617. this.a.copy( triangle.a );
  3618. this.b.copy( triangle.b );
  3619. this.c.copy( triangle.c );
  3620. return this;
  3621. },
  3622. area: function() {
  3623. var v0 = new THREE.Vector3();
  3624. var v1 = new THREE.Vector3();
  3625. return function () {
  3626. v0.subVectors( this.c, this.b );
  3627. v1.subVectors( this.a, this.b );
  3628. return v0.cross( v1 ).length() * 0.5;
  3629. };
  3630. }(),
  3631. midpoint: function ( optionalTarget ) {
  3632. var result = optionalTarget || new THREE.Vector3();
  3633. return result.addVectors( this.a, this.b ).add( this.c ).multiplyScalar( 1 / 3 );
  3634. },
  3635. normal: function ( optionalTarget ) {
  3636. return THREE.Triangle.normal( this.a, this.b, this.c, optionalTarget );
  3637. },
  3638. plane: function ( optionalTarget ) {
  3639. var result = optionalTarget || new THREE.Plane();
  3640. return result.setFromCoplanarPoints( this.a, this.b, this.c );
  3641. },
  3642. barycoordFromPoint: function ( point, optionalTarget ) {
  3643. return THREE.Triangle.barycoordFromPoint( point, this.a, this.b, this.c, optionalTarget );
  3644. },
  3645. containsPoint: function ( point ) {
  3646. return THREE.Triangle.containsPoint( point, this.a, this.b, this.c );
  3647. },
  3648. equals: function ( triangle ) {
  3649. return triangle.a.equals( this.a ) && triangle.b.equals( this.b ) && triangle.c.equals( this.c );
  3650. },
  3651. clone: function () {
  3652. return new THREE.Triangle().copy( this );
  3653. }
  3654. };
  3655. /**
  3656. * @author mrdoob / http://mrdoob.com/
  3657. */
  3658. THREE.Vertex = function ( v ) {
  3659. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3660. return v;
  3661. };
  3662. /**
  3663. * @author mrdoob / http://mrdoob.com/
  3664. */
  3665. THREE.UV = function ( u, v ) {
  3666. console.warn( 'THREE.UV has been DEPRECATED. Use THREE.Vector2 instead.')
  3667. return new THREE.Vector2( u, v );
  3668. };
  3669. /**
  3670. * @author alteredq / http://alteredqualia.com/
  3671. */
  3672. THREE.Clock = function ( autoStart ) {
  3673. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  3674. this.startTime = 0;
  3675. this.oldTime = 0;
  3676. this.elapsedTime = 0;
  3677. this.running = false;
  3678. };
  3679. THREE.Clock.prototype = {
  3680. constructor: THREE.Clock,
  3681. start: function () {
  3682. this.startTime = self.performance !== undefined && self.performance.now !== undefined
  3683. ? self.performance.now()
  3684. : Date.now();
  3685. this.oldTime = this.startTime;
  3686. this.running = true;
  3687. },
  3688. stop: function () {
  3689. this.getElapsedTime();
  3690. this.running = false;
  3691. },
  3692. getElapsedTime: function () {
  3693. this.getDelta();
  3694. return this.elapsedTime;
  3695. },
  3696. getDelta: function () {
  3697. var diff = 0;
  3698. if ( this.autoStart && ! this.running ) {
  3699. this.start();
  3700. }
  3701. if ( this.running ) {
  3702. var newTime = self.performance !== undefined && self.performance.now !== undefined
  3703. ? self.performance.now()
  3704. : Date.now();
  3705. diff = 0.001 * ( newTime - this.oldTime );
  3706. this.oldTime = newTime;
  3707. this.elapsedTime += diff;
  3708. }
  3709. return diff;
  3710. }
  3711. };
  3712. /**
  3713. * https://github.com/mrdoob/eventdispatcher.js/
  3714. */
  3715. THREE.EventDispatcher = function () {}
  3716. THREE.EventDispatcher.prototype = {
  3717. constructor: THREE.EventDispatcher,
  3718. addEventListener: function ( type, listener ) {
  3719. if ( this._listeners === undefined ) this._listeners = {};
  3720. var listeners = this._listeners;
  3721. if ( listeners[ type ] === undefined ) {
  3722. listeners[ type ] = [];
  3723. }
  3724. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  3725. listeners[ type ].push( listener );
  3726. }
  3727. },
  3728. hasEventListener: function ( type, listener ) {
  3729. if ( this._listeners === undefined ) return false;
  3730. var listeners = this._listeners;
  3731. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  3732. return true;
  3733. }
  3734. return false;
  3735. },
  3736. removeEventListener: function ( type, listener ) {
  3737. if ( this._listeners === undefined ) return;
  3738. var listeners = this._listeners;
  3739. var index = listeners[ type ].indexOf( listener );
  3740. if ( index !== - 1 ) {
  3741. listeners[ type ].splice( index, 1 );
  3742. }
  3743. },
  3744. dispatchEvent: function ( event ) {
  3745. if ( this._listeners === undefined ) return;
  3746. var listeners = this._listeners;
  3747. var listenerArray = listeners[ event.type ];
  3748. if ( listenerArray !== undefined ) {
  3749. event.target = this;
  3750. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  3751. listenerArray[ i ].call( this, event );
  3752. }
  3753. }
  3754. }
  3755. };
  3756. /**
  3757. * @author mrdoob / http://mrdoob.com/
  3758. * @author bhouston / http://exocortex.com/
  3759. */
  3760. ( function ( THREE ) {
  3761. THREE.Raycaster = function ( origin, direction, near, far ) {
  3762. this.ray = new THREE.Ray( origin, direction );
  3763. // normalized ray.direction required for accurate distance calculations
  3764. if ( this.ray.direction.lengthSq() > 0 ) {
  3765. this.ray.direction.normalize();
  3766. }
  3767. this.near = near || 0;
  3768. this.far = far || Infinity;
  3769. };
  3770. var sphere = new THREE.Sphere();
  3771. var localRay = new THREE.Ray();
  3772. var facePlane = new THREE.Plane();
  3773. var intersectPoint = new THREE.Vector3();
  3774. var matrixPosition = new THREE.Vector3();
  3775. var inverseMatrix = new THREE.Matrix4();
  3776. var descSort = function ( a, b ) {
  3777. return a.distance - b.distance;
  3778. };
  3779. var intersectObject = function ( object, raycaster, intersects ) {
  3780. if ( object instanceof THREE.Particle ) {
  3781. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3782. var distance = raycaster.ray.distanceToPoint( matrixPosition );
  3783. if ( distance > object.scale.x ) {
  3784. return intersects;
  3785. }
  3786. intersects.push( {
  3787. distance: distance,
  3788. point: object.position,
  3789. face: null,
  3790. object: object
  3791. } );
  3792. } else if ( object instanceof THREE.LOD ) {
  3793. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3794. var distance = raycaster.ray.origin.distanceTo( matrixPosition );
  3795. intersectObject( object.getObjectForDistance( distance ), raycaster, intersects );
  3796. } else if (object instanceof THREE.Mesh ) {
  3797. // Checking boundingSphere distance to ray
  3798. matrixPosition.getPositionFromMatrix( object.matrixWorld );
  3799. sphere.set( matrixPosition, object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis() );
  3800. if ( raycaster.ray.isIntersectionSphere( sphere ) === false ) {
  3801. return intersects;
  3802. }
  3803. var geometry = object.geometry;
  3804. var vertices = geometry.vertices;
  3805. if ( geometry instanceof THREE.BufferGeometry ) {
  3806. var material = object.material;
  3807. if ( material === undefined ) return intersects;
  3808. if ( ! geometry.dynamic ) return intersects;
  3809. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3810. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3811. var side = object.material.side;
  3812. var a, b, c;
  3813. var precision = raycaster.precision;
  3814. inverseMatrix.getInverse( object.matrixWorld );
  3815. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3816. var fl;
  3817. var indexed = false;
  3818. if ( geometry.attributes.index ) {
  3819. indexed = true;
  3820. fl = geometry.attributes.index.numItems / 3;
  3821. } else {
  3822. fl = geometry.attributes.position.numItems / 9;
  3823. }
  3824. var vA = new THREE.Vector3();
  3825. var vB = new THREE.Vector3();
  3826. var vC = new THREE.Vector3();
  3827. var vCB = new THREE.Vector3();
  3828. var vAB = new THREE.Vector3();
  3829. for ( var oi = 0; oi < geometry.offsets.length; ++oi ) {
  3830. var start = geometry.offsets[ oi ].start;
  3831. var count = geometry.offsets[ oi ].count;
  3832. var index = geometry.offsets[ oi ].index;
  3833. for ( var i = start, il = start + count; i < il; i += 3 ) {
  3834. if ( indexed ) {
  3835. a = index + geometry.attributes.index.array[ i ];
  3836. b = index + geometry.attributes.index.array[ i + 1 ];
  3837. c = index + geometry.attributes.index.array[ i + 2 ];
  3838. } else {
  3839. a = index;
  3840. b = index + 1;
  3841. c = index + 2;
  3842. }
  3843. vA.set( geometry.attributes.position.array[ a * 3 ],
  3844. geometry.attributes.position.array[ a * 3 + 1 ],
  3845. geometry.attributes.position.array[ a * 3 + 2] );
  3846. vB.set( geometry.attributes.position.array[ b * 3 ],
  3847. geometry.attributes.position.array[ b * 3 + 1 ],
  3848. geometry.attributes.position.array[ b * 3 + 2] );
  3849. vC.set( geometry.attributes.position.array[ c * 3 ],
  3850. geometry.attributes.position.array[ c * 3 + 1 ],
  3851. geometry.attributes.position.array[ c * 3 + 2 ] );
  3852. facePlane.setFromCoplanarPoints( vA, vB, vC );
  3853. var planeDistance = localRay.distanceToPlane( facePlane );
  3854. // bail if raycaster and plane are parallel
  3855. if ( Math.abs( planeDistance ) < precision ) continue;
  3856. // if negative distance, then plane is behind raycaster
  3857. if ( planeDistance < 0 ) continue;
  3858. // check if we hit the wrong side of a single sided face
  3859. side = material.side;
  3860. if ( side !== THREE.DoubleSide ) {
  3861. var planeSign = localRay.direction.dot( facePlane.normal );
  3862. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3863. }
  3864. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3865. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3866. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3867. if ( ! THREE.Triangle.containsPoint( intersectPoint, vA, vB, vC ) ) continue;
  3868. intersects.push( {
  3869. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3870. point: raycaster.ray.at(planeDistance),
  3871. face: null,
  3872. faceIndex: null,
  3873. object: object
  3874. } );
  3875. }
  3876. }
  3877. } else if ( geometry instanceof THREE.Geometry ) {
  3878. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3879. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  3880. var side = object.material.side;
  3881. var a, b, c, d;
  3882. var precision = raycaster.precision;
  3883. inverseMatrix.getInverse( object.matrixWorld );
  3884. localRay.copy( raycaster.ray ).applyMatrix4( inverseMatrix );
  3885. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  3886. var face = geometry.faces[ f ];
  3887. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  3888. if ( material === undefined ) continue;
  3889. facePlane.setFromNormalAndCoplanarPoint( face.normal, vertices[face.a] );
  3890. var planeDistance = localRay.distanceToPlane( facePlane );
  3891. // bail if raycaster and plane are parallel
  3892. if ( Math.abs( planeDistance ) < precision ) continue;
  3893. // if negative distance, then plane is behind raycaster
  3894. if ( planeDistance < 0 ) continue;
  3895. // check if we hit the wrong side of a single sided face
  3896. side = material.side;
  3897. if ( side !== THREE.DoubleSide ) {
  3898. var planeSign = localRay.direction.dot( facePlane.normal );
  3899. if ( ! ( side === THREE.FrontSide ? planeSign < 0 : planeSign > 0 ) ) continue;
  3900. }
  3901. // this can be done using the planeDistance from localRay because localRay wasn't normalized, but ray was
  3902. if ( planeDistance < raycaster.near || planeDistance > raycaster.far ) continue;
  3903. intersectPoint = localRay.at( planeDistance, intersectPoint ); // passing in intersectPoint avoids a copy
  3904. if ( face instanceof THREE.Face3 ) {
  3905. a = vertices[ face.a ];
  3906. b = vertices[ face.b ];
  3907. c = vertices[ face.c ];
  3908. if ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, c ) ) continue;
  3909. } else if ( face instanceof THREE.Face4 ) {
  3910. a = vertices[ face.a ];
  3911. b = vertices[ face.b ];
  3912. c = vertices[ face.c ];
  3913. d = vertices[ face.d ];
  3914. if ( ( ! THREE.Triangle.containsPoint( intersectPoint, a, b, d ) ) &&
  3915. ( ! THREE.Triangle.containsPoint( intersectPoint, b, c, d ) ) ) continue;
  3916. } else {
  3917. // This is added because if we call out of this if/else group when none of the cases
  3918. // match it will add a point to the intersection list erroneously.
  3919. throw Error( "face type not supported" );
  3920. }
  3921. intersects.push( {
  3922. distance: planeDistance, // this works because the original ray was normalized, and the transformed localRay wasn't
  3923. point: raycaster.ray.at( planeDistance ),
  3924. face: face,
  3925. faceIndex: f,
  3926. object: object
  3927. } );
  3928. }
  3929. }
  3930. }
  3931. };
  3932. var intersectDescendants = function ( object, raycaster, intersects ) {
  3933. var descendants = object.getDescendants();
  3934. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  3935. intersectObject( descendants[ i ], raycaster, intersects );
  3936. }
  3937. };
  3938. //
  3939. THREE.Raycaster.prototype.precision = 0.0001;
  3940. THREE.Raycaster.prototype.set = function ( origin, direction ) {
  3941. this.ray.set( origin, direction );
  3942. // normalized ray.direction required for accurate distance calculations
  3943. if ( this.ray.direction.length() > 0 ) {
  3944. this.ray.direction.normalize();
  3945. }
  3946. };
  3947. THREE.Raycaster.prototype.intersectObject = function ( object, recursive ) {
  3948. var intersects = [];
  3949. if ( recursive === true ) {
  3950. intersectDescendants( object, this, intersects );
  3951. }
  3952. intersectObject( object, this, intersects );
  3953. intersects.sort( descSort );
  3954. return intersects;
  3955. };
  3956. THREE.Raycaster.prototype.intersectObjects = function ( objects, recursive ) {
  3957. var intersects = [];
  3958. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  3959. intersectObject( objects[ i ], this, intersects );
  3960. if ( recursive === true ) {
  3961. intersectDescendants( objects[ i ], this, intersects );
  3962. }
  3963. }
  3964. intersects.sort( descSort );
  3965. return intersects;
  3966. };
  3967. }( THREE ) );
  3968. /**
  3969. * @author mrdoob / http://mrdoob.com/
  3970. * @author mikael emtinger / http://gomo.se/
  3971. * @author alteredq / http://alteredqualia.com/
  3972. * @author WestLangley / http://github.com/WestLangley
  3973. */
  3974. THREE.Object3D = function () {
  3975. this.id = THREE.Math.generateUUID();
  3976. this.name = '';
  3977. this.parent = undefined;
  3978. this.children = [];
  3979. this.up = new THREE.Vector3( 0, 1, 0 );
  3980. this.position = new THREE.Vector3();
  3981. this.rotation = new THREE.Euler();
  3982. this.quaternion = new THREE.Quaternion();
  3983. this.scale = new THREE.Vector3( 1, 1, 1 );
  3984. // keep rotation and quaternion in sync
  3985. this.rotation._quaternion = this.quaternion;
  3986. this.quaternion._euler = this.rotation;
  3987. this.renderDepth = null;
  3988. this.rotationAutoUpdate = true;
  3989. this.matrix = new THREE.Matrix4();
  3990. this.matrixWorld = new THREE.Matrix4();
  3991. this.matrixAutoUpdate = true;
  3992. this.matrixWorldNeedsUpdate = true;
  3993. this.visible = true;
  3994. this.castShadow = false;
  3995. this.receiveShadow = false;
  3996. this.frustumCulled = true;
  3997. this.userData = {};
  3998. };
  3999. THREE.Object3D.prototype = {
  4000. constructor: THREE.Object3D,
  4001. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4002. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4003. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4004. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4005. applyMatrix: function () {
  4006. var m1 = new THREE.Matrix4();
  4007. return function ( matrix ) {
  4008. this.matrix.multiplyMatrices( matrix, this.matrix );
  4009. this.position.getPositionFromMatrix( this.matrix );
  4010. this.scale.getScaleFromMatrix( this.matrix );
  4011. m1.extractRotation( this.matrix );
  4012. this.quaternion.setFromRotationMatrix( m1 );
  4013. }
  4014. }(),
  4015. rotateOnAxis: function() {
  4016. // rotate object on axis in object space
  4017. // axis is assumed to be normalized
  4018. var q1 = new THREE.Quaternion();
  4019. var q2 = new THREE.Quaternion();
  4020. return function ( axis, angle ) {
  4021. q1.setFromAxisAngle( axis, angle );
  4022. this.quaternion.multiply( q1 );
  4023. return this;
  4024. }
  4025. }(),
  4026. translateOnAxis: function () {
  4027. // translate object by distance along axis in object space
  4028. // axis is assumed to be normalized
  4029. var v1 = new THREE.Vector3();
  4030. return function ( axis, distance ) {
  4031. v1.copy( axis );
  4032. v1.applyQuaternion( this.quaternion );
  4033. this.position.add( v1.multiplyScalar( distance ) );
  4034. return this;
  4035. }
  4036. }(),
  4037. translate: function ( distance, axis ) {
  4038. console.warn( 'DEPRECATED: Object3D\'s .translate() has been removed. Use .translateOnAxis( axis, distance ) instead. Note args have been changed.' );
  4039. return this.translateOnAxis( axis, distance );
  4040. },
  4041. translateX: function () {
  4042. var v1 = new THREE.Vector3( 1, 0, 0 );
  4043. return function ( distance ) {
  4044. return this.translateOnAxis( v1, distance );
  4045. };
  4046. }(),
  4047. translateY: function () {
  4048. var v1 = new THREE.Vector3( 0, 1, 0 );
  4049. return function ( distance ) {
  4050. return this.translateOnAxis( v1, distance );
  4051. };
  4052. }(),
  4053. translateZ: function () {
  4054. var v1 = new THREE.Vector3( 0, 0, 1 );
  4055. return function ( distance ) {
  4056. return this.translateOnAxis( v1, distance );
  4057. };
  4058. }(),
  4059. localToWorld: function ( vector ) {
  4060. return vector.applyMatrix4( this.matrixWorld );
  4061. },
  4062. worldToLocal: function () {
  4063. var m1 = new THREE.Matrix4();
  4064. return function ( vector ) {
  4065. return vector.applyMatrix4( m1.getInverse( this.matrixWorld ) );
  4066. };
  4067. }(),
  4068. lookAt: function () {
  4069. // This routine does not support objects with rotated and/or translated parent(s)
  4070. var m1 = new THREE.Matrix4();
  4071. return function ( vector ) {
  4072. m1.lookAt( vector, this.position, this.up );
  4073. this.quaternion.setFromRotationMatrix( m1 );
  4074. };
  4075. }(),
  4076. add: function ( object ) {
  4077. if ( object === this ) {
  4078. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  4079. return;
  4080. }
  4081. if ( object instanceof THREE.Object3D ) {
  4082. if ( object.parent !== undefined ) {
  4083. object.parent.remove( object );
  4084. }
  4085. object.parent = this;
  4086. this.children.push( object );
  4087. // add to scene
  4088. var scene = this;
  4089. while ( scene.parent !== undefined ) {
  4090. scene = scene.parent;
  4091. }
  4092. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4093. scene.__addObject( object );
  4094. }
  4095. }
  4096. },
  4097. remove: function ( object ) {
  4098. var index = this.children.indexOf( object );
  4099. if ( index !== - 1 ) {
  4100. object.parent = undefined;
  4101. this.children.splice( index, 1 );
  4102. // remove from scene
  4103. var scene = this;
  4104. while ( scene.parent !== undefined ) {
  4105. scene = scene.parent;
  4106. }
  4107. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  4108. scene.__removeObject( object );
  4109. }
  4110. }
  4111. },
  4112. traverse: function ( callback ) {
  4113. callback( this );
  4114. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4115. this.children[ i ].traverse( callback );
  4116. }
  4117. },
  4118. getObjectById: function ( id, recursive ) {
  4119. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4120. var child = this.children[ i ];
  4121. if ( child.id === id ) {
  4122. return child;
  4123. }
  4124. if ( recursive === true ) {
  4125. child = child.getObjectById( id, recursive );
  4126. if ( child !== undefined ) {
  4127. return child;
  4128. }
  4129. }
  4130. }
  4131. return undefined;
  4132. },
  4133. getObjectByName: function ( name, recursive ) {
  4134. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4135. var child = this.children[ i ];
  4136. if ( child.name === name ) {
  4137. return child;
  4138. }
  4139. if ( recursive === true ) {
  4140. child = child.getObjectByName( name, recursive );
  4141. if ( child !== undefined ) {
  4142. return child;
  4143. }
  4144. }
  4145. }
  4146. return undefined;
  4147. },
  4148. getChildByName: function ( name, recursive ) {
  4149. console.warn( 'DEPRECATED: Object3D\'s .getChildByName() has been renamed to .getObjectByName().' );
  4150. return this.getObjectByName( name, recursive );
  4151. },
  4152. getDescendants: function ( array ) {
  4153. if ( array === undefined ) array = [];
  4154. Array.prototype.push.apply( array, this.children );
  4155. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4156. this.children[ i ].getDescendants( array );
  4157. }
  4158. return array;
  4159. },
  4160. updateMatrix: function () {
  4161. this.matrix.compose( this.position, this.quaternion, this.scale );
  4162. this.matrixWorldNeedsUpdate = true;
  4163. },
  4164. updateMatrixWorld: function ( force ) {
  4165. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  4166. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  4167. if ( this.parent === undefined ) {
  4168. this.matrixWorld.copy( this.matrix );
  4169. } else {
  4170. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  4171. }
  4172. this.matrixWorldNeedsUpdate = false;
  4173. force = true;
  4174. }
  4175. // update children
  4176. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  4177. this.children[ i ].updateMatrixWorld( force );
  4178. }
  4179. },
  4180. clone: function ( object, recursive ) {
  4181. if ( object === undefined ) object = new THREE.Object3D();
  4182. if ( recursive === undefined ) recursive = true;
  4183. object.name = this.name;
  4184. object.up.copy( this.up );
  4185. object.position.copy( this.position );
  4186. object.quaternion.copy( this.quaternion );
  4187. object.scale.copy( this.scale );
  4188. object.renderDepth = this.renderDepth;
  4189. object.rotationAutoUpdate = this.rotationAutoUpdate;
  4190. object.matrix.copy( this.matrix );
  4191. object.matrixWorld.copy( this.matrixWorld );
  4192. object.matrixAutoUpdate = this.matrixAutoUpdate;
  4193. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  4194. object.visible = this.visible;
  4195. object.castShadow = this.castShadow;
  4196. object.receiveShadow = this.receiveShadow;
  4197. object.frustumCulled = this.frustumCulled;
  4198. object.userData = JSON.parse( JSON.stringify( this.userData ) );
  4199. if ( recursive === true ) {
  4200. for ( var i = 0; i < this.children.length; i ++ ) {
  4201. var child = this.children[ i ];
  4202. object.add( child.clone() );
  4203. }
  4204. }
  4205. return object;
  4206. }
  4207. };
  4208. THREE.Object3D.defaultEulerOrder = 'XYZ';
  4209. /**
  4210. * @author mrdoob / http://mrdoob.com/
  4211. * @author supereggbert / http://www.paulbrunt.co.uk/
  4212. * @author julianwa / https://github.com/julianwa
  4213. */
  4214. THREE.Projector = function () {
  4215. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  4216. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  4217. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  4218. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  4219. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  4220. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  4221. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  4222. _vector3 = new THREE.Vector3(),
  4223. _vector4 = new THREE.Vector4(),
  4224. _clipBox = new THREE.Box3( new THREE.Vector3( -1, -1, -1 ), new THREE.Vector3( 1, 1, 1 ) ),
  4225. _boundingBox = new THREE.Box3(),
  4226. _points3 = new Array( 3 ),
  4227. _points4 = new Array( 4 ),
  4228. _viewMatrix = new THREE.Matrix4(),
  4229. _viewProjectionMatrix = new THREE.Matrix4(),
  4230. _modelMatrix,
  4231. _modelViewProjectionMatrix = new THREE.Matrix4(),
  4232. _normalMatrix = new THREE.Matrix3(),
  4233. _normalViewMatrix = new THREE.Matrix3(),
  4234. _centroid = new THREE.Vector3(),
  4235. _frustum = new THREE.Frustum(),
  4236. _clippedVertex1PositionScreen = new THREE.Vector4(),
  4237. _clippedVertex2PositionScreen = new THREE.Vector4();
  4238. this.projectVector = function ( vector, camera ) {
  4239. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4240. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  4241. return vector.applyProjection( _viewProjectionMatrix );
  4242. };
  4243. this.unprojectVector = function ( vector, camera ) {
  4244. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  4245. _viewProjectionMatrix.multiplyMatrices( camera.matrixWorld, camera.projectionMatrixInverse );
  4246. return vector.applyProjection( _viewProjectionMatrix );
  4247. };
  4248. this.pickingRay = function ( vector, camera ) {
  4249. // set two vectors with opposing z values
  4250. vector.z = -1.0;
  4251. var end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  4252. this.unprojectVector( vector, camera );
  4253. this.unprojectVector( end, camera );
  4254. // find direction from vector to end
  4255. end.sub( vector ).normalize();
  4256. return new THREE.Raycaster( vector, end );
  4257. };
  4258. var getObject = function ( object ) {
  4259. _object = getNextObjectInPool();
  4260. _object.object = object;
  4261. if ( object.renderDepth !== null ) {
  4262. _object.z = object.renderDepth;
  4263. } else {
  4264. _vector3.getPositionFromMatrix( object.matrixWorld );
  4265. _vector3.applyProjection( _viewProjectionMatrix );
  4266. _object.z = _vector3.z;
  4267. }
  4268. return _object;
  4269. };
  4270. var projectObject = function ( object ) {
  4271. if ( object.visible === false ) return;
  4272. if ( object instanceof THREE.Light ) {
  4273. _renderData.lights.push( object );
  4274. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  4275. if ( object.frustumCulled === false || _frustum.intersectsObject( object ) === true ) {
  4276. _renderData.objects.push( getObject( object ) );
  4277. }
  4278. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  4279. _renderData.sprites.push( getObject( object ) );
  4280. }
  4281. for ( var i = 0, l = object.children.length; i < l; i ++ ) {
  4282. projectObject( object.children[ i ] );
  4283. }
  4284. };
  4285. var projectGraph = function ( root, sortObjects ) {
  4286. _objectCount = 0;
  4287. _renderData.objects.length = 0;
  4288. _renderData.sprites.length = 0;
  4289. _renderData.lights.length = 0;
  4290. projectObject( root );
  4291. if ( sortObjects === true ) {
  4292. _renderData.objects.sort( painterSort );
  4293. }
  4294. };
  4295. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  4296. var visible = false,
  4297. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  4298. geometry, vertices, faces, face, faceVertexNormals, faceVertexUvs, uvs,
  4299. v1, v2, v3, v4, isFaceMaterial, objectMaterials;
  4300. _face3Count = 0;
  4301. _face4Count = 0;
  4302. _lineCount = 0;
  4303. _particleCount = 0;
  4304. _renderData.elements.length = 0;
  4305. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  4306. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  4307. _viewMatrix.copy( camera.matrixWorldInverse.getInverse( camera.matrixWorld ) );
  4308. _viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, _viewMatrix );
  4309. _normalViewMatrix.getNormalMatrix( _viewMatrix );
  4310. _frustum.setFromMatrix( _viewProjectionMatrix );
  4311. projectGraph( scene, sortObjects );
  4312. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  4313. object = _renderData.objects[ o ].object;
  4314. _modelMatrix = object.matrixWorld;
  4315. _vertexCount = 0;
  4316. if ( object instanceof THREE.Mesh ) {
  4317. geometry = object.geometry;
  4318. vertices = geometry.vertices;
  4319. faces = geometry.faces;
  4320. faceVertexUvs = geometry.faceVertexUvs;
  4321. _normalMatrix.getNormalMatrix( _modelMatrix );
  4322. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  4323. objectMaterials = isFaceMaterial === true ? object.material : null;
  4324. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  4325. _vertex = getNextVertexInPool();
  4326. _vertex.positionWorld.copy( vertices[ v ] ).applyMatrix4( _modelMatrix );
  4327. _vertex.positionScreen.copy( _vertex.positionWorld ).applyMatrix4( _viewProjectionMatrix );
  4328. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  4329. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  4330. _vertex.positionScreen.z /= _vertex.positionScreen.w;
  4331. _vertex.visible = ! ( _vertex.positionScreen.x < -1 || _vertex.positionScreen.x > 1 ||
  4332. _vertex.positionScreen.y < -1 || _vertex.positionScreen.y > 1 ||
  4333. _vertex.positionScreen.z < -1 || _vertex.positionScreen.z > 1 );
  4334. }
  4335. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  4336. face = faces[ f ];
  4337. var material = isFaceMaterial === true
  4338. ? objectMaterials.materials[ face.materialIndex ]
  4339. : object.material;
  4340. if ( material === undefined ) continue;
  4341. var side = material.side;
  4342. if ( face instanceof THREE.Face3 ) {
  4343. v1 = _vertexPool[ face.a ];
  4344. v2 = _vertexPool[ face.b ];
  4345. v3 = _vertexPool[ face.c ];
  4346. _points3[ 0 ] = v1.positionScreen;
  4347. _points3[ 1 ] = v2.positionScreen;
  4348. _points3[ 2 ] = v3.positionScreen;
  4349. if ( v1.visible === true || v2.visible === true || v3.visible === true ||
  4350. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points3 ) ) ) {
  4351. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4352. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  4353. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4354. _face = getNextFace3InPool();
  4355. _face.v1.copy( v1 );
  4356. _face.v2.copy( v2 );
  4357. _face.v3.copy( v3 );
  4358. } else {
  4359. continue;
  4360. }
  4361. } else {
  4362. continue;
  4363. }
  4364. } else if ( face instanceof THREE.Face4 ) {
  4365. v1 = _vertexPool[ face.a ];
  4366. v2 = _vertexPool[ face.b ];
  4367. v3 = _vertexPool[ face.c ];
  4368. v4 = _vertexPool[ face.d ];
  4369. _points4[ 0 ] = v1.positionScreen;
  4370. _points4[ 1 ] = v2.positionScreen;
  4371. _points4[ 2 ] = v3.positionScreen;
  4372. _points4[ 3 ] = v4.positionScreen;
  4373. if ( v1.visible === true || v2.visible === true || v3.visible === true || v4.visible === true ||
  4374. _clipBox.isIntersectionBox( _boundingBox.setFromPoints( _points4 ) ) ) {
  4375. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  4376. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  4377. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  4378. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  4379. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  4380. _face = getNextFace4InPool();
  4381. _face.v1.copy( v1 );
  4382. _face.v2.copy( v2 );
  4383. _face.v3.copy( v3 );
  4384. _face.v4.copy( v4 );
  4385. } else {
  4386. continue;
  4387. }
  4388. } else {
  4389. continue;
  4390. }
  4391. }
  4392. _face.normalModel.copy( face.normal );
  4393. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4394. _face.normalModel.negate();
  4395. }
  4396. _face.normalModel.applyMatrix3( _normalMatrix ).normalize();
  4397. _face.normalModelView.copy( _face.normalModel ).applyMatrix3( _normalViewMatrix );
  4398. _face.centroidModel.copy( face.centroid ).applyMatrix4( _modelMatrix );
  4399. faceVertexNormals = face.vertexNormals;
  4400. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  4401. var normalModel = _face.vertexNormalsModel[ n ];
  4402. normalModel.copy( faceVertexNormals[ n ] );
  4403. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) {
  4404. normalModel.negate();
  4405. }
  4406. normalModel.applyMatrix3( _normalMatrix ).normalize();
  4407. var normalModelView = _face.vertexNormalsModelView[ n ];
  4408. normalModelView.copy( normalModel ).applyMatrix3( _normalViewMatrix );
  4409. }
  4410. _face.vertexNormalsLength = faceVertexNormals.length;
  4411. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  4412. uvs = faceVertexUvs[ c ][ f ];
  4413. if ( uvs === undefined ) continue;
  4414. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  4415. _face.uvs[ c ][ u ] = uvs[ u ];
  4416. }
  4417. }
  4418. _face.color = face.color;
  4419. _face.material = material;
  4420. _centroid.copy( _face.centroidModel ).applyProjection( _viewProjectionMatrix );
  4421. _face.z = _centroid.z;
  4422. _renderData.elements.push( _face );
  4423. }
  4424. } else if ( object instanceof THREE.Line ) {
  4425. _modelViewProjectionMatrix.multiplyMatrices( _viewProjectionMatrix, _modelMatrix );
  4426. vertices = object.geometry.vertices;
  4427. v1 = getNextVertexInPool();
  4428. v1.positionScreen.copy( vertices[ 0 ] ).applyMatrix4( _modelViewProjectionMatrix );
  4429. // Handle LineStrip and LinePieces
  4430. var step = object.type === THREE.LinePieces ? 2 : 1;
  4431. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  4432. v1 = getNextVertexInPool();
  4433. v1.positionScreen.copy( vertices[ v ] ).applyMatrix4( _modelViewProjectionMatrix );
  4434. if ( ( v + 1 ) % step > 0 ) continue;
  4435. v2 = _vertexPool[ _vertexCount - 2 ];
  4436. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  4437. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  4438. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  4439. // Perform the perspective divide
  4440. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  4441. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  4442. _line = getNextLineInPool();
  4443. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  4444. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  4445. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  4446. _line.material = object.material;
  4447. if ( object.material.vertexColors === THREE.VertexColors ) {
  4448. _line.vertexColors[ 0 ].copy( object.geometry.colors[ v ] );
  4449. _line.vertexColors[ 1 ].copy( object.geometry.colors[ v - 1 ] );
  4450. }
  4451. _renderData.elements.push( _line );
  4452. }
  4453. }
  4454. }
  4455. }
  4456. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  4457. object = _renderData.sprites[ o ].object;
  4458. _modelMatrix = object.matrixWorld;
  4459. if ( object instanceof THREE.Particle ) {
  4460. _vector4.set( _modelMatrix.elements[12], _modelMatrix.elements[13], _modelMatrix.elements[14], 1 );
  4461. _vector4.applyMatrix4( _viewProjectionMatrix );
  4462. _vector4.z /= _vector4.w;
  4463. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  4464. _particle = getNextParticleInPool();
  4465. _particle.object = object;
  4466. _particle.x = _vector4.x / _vector4.w;
  4467. _particle.y = _vector4.y / _vector4.w;
  4468. _particle.z = _vector4.z;
  4469. _particle.rotation = object.rotation.z;
  4470. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  4471. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  4472. _particle.material = object.material;
  4473. _renderData.elements.push( _particle );
  4474. }
  4475. }
  4476. }
  4477. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  4478. return _renderData;
  4479. };
  4480. // Pools
  4481. function getNextObjectInPool() {
  4482. if ( _objectCount === _objectPoolLength ) {
  4483. var object = new THREE.RenderableObject();
  4484. _objectPool.push( object );
  4485. _objectPoolLength ++;
  4486. _objectCount ++;
  4487. return object;
  4488. }
  4489. return _objectPool[ _objectCount ++ ];
  4490. }
  4491. function getNextVertexInPool() {
  4492. if ( _vertexCount === _vertexPoolLength ) {
  4493. var vertex = new THREE.RenderableVertex();
  4494. _vertexPool.push( vertex );
  4495. _vertexPoolLength ++;
  4496. _vertexCount ++;
  4497. return vertex;
  4498. }
  4499. return _vertexPool[ _vertexCount ++ ];
  4500. }
  4501. function getNextFace3InPool() {
  4502. if ( _face3Count === _face3PoolLength ) {
  4503. var face = new THREE.RenderableFace3();
  4504. _face3Pool.push( face );
  4505. _face3PoolLength ++;
  4506. _face3Count ++;
  4507. return face;
  4508. }
  4509. return _face3Pool[ _face3Count ++ ];
  4510. }
  4511. function getNextFace4InPool() {
  4512. if ( _face4Count === _face4PoolLength ) {
  4513. var face = new THREE.RenderableFace4();
  4514. _face4Pool.push( face );
  4515. _face4PoolLength ++;
  4516. _face4Count ++;
  4517. return face;
  4518. }
  4519. return _face4Pool[ _face4Count ++ ];
  4520. }
  4521. function getNextLineInPool() {
  4522. if ( _lineCount === _linePoolLength ) {
  4523. var line = new THREE.RenderableLine();
  4524. _linePool.push( line );
  4525. _linePoolLength ++;
  4526. _lineCount ++
  4527. return line;
  4528. }
  4529. return _linePool[ _lineCount ++ ];
  4530. }
  4531. function getNextParticleInPool() {
  4532. if ( _particleCount === _particlePoolLength ) {
  4533. var particle = new THREE.RenderableParticle();
  4534. _particlePool.push( particle );
  4535. _particlePoolLength ++;
  4536. _particleCount ++
  4537. return particle;
  4538. }
  4539. return _particlePool[ _particleCount ++ ];
  4540. }
  4541. //
  4542. function painterSort( a, b ) {
  4543. return b.z - a.z;
  4544. }
  4545. function clipLine( s1, s2 ) {
  4546. var alpha1 = 0, alpha2 = 1,
  4547. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  4548. // Z = -1 and Z = +1, respectively.
  4549. bc1near = s1.z + s1.w,
  4550. bc2near = s2.z + s2.w,
  4551. bc1far = - s1.z + s1.w,
  4552. bc2far = - s2.z + s2.w;
  4553. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  4554. // Both vertices lie entirely within all clip planes.
  4555. return true;
  4556. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  4557. // Both vertices lie entirely outside one of the clip planes.
  4558. return false;
  4559. } else {
  4560. // The line segment spans at least one clip plane.
  4561. if ( bc1near < 0 ) {
  4562. // v1 lies outside the near plane, v2 inside
  4563. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  4564. } else if ( bc2near < 0 ) {
  4565. // v2 lies outside the near plane, v1 inside
  4566. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  4567. }
  4568. if ( bc1far < 0 ) {
  4569. // v1 lies outside the far plane, v2 inside
  4570. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  4571. } else if ( bc2far < 0 ) {
  4572. // v2 lies outside the far plane, v2 inside
  4573. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  4574. }
  4575. if ( alpha2 < alpha1 ) {
  4576. // The line segment spans two boundaries, but is outside both of them.
  4577. // (This can't happen when we're only clipping against just near/far but good
  4578. // to leave the check here for future usage if other clip planes are added.)
  4579. return false;
  4580. } else {
  4581. // Update the s1 and s2 vertices to match the clipped line segment.
  4582. s1.lerp( s2, alpha1 );
  4583. s2.lerp( s1, 1 - alpha2 );
  4584. return true;
  4585. }
  4586. }
  4587. }
  4588. };
  4589. /**
  4590. * @author mrdoob / http://mrdoob.com/
  4591. * @author alteredq / http://alteredqualia.com/
  4592. */
  4593. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  4594. this.a = a;
  4595. this.b = b;
  4596. this.c = c;
  4597. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4598. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4599. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4600. this.vertexColors = color instanceof Array ? color : [];
  4601. this.vertexTangents = [];
  4602. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4603. this.centroid = new THREE.Vector3();
  4604. };
  4605. THREE.Face3.prototype = {
  4606. constructor: THREE.Face3,
  4607. clone: function () {
  4608. var face = new THREE.Face3( this.a, this.b, this.c );
  4609. face.normal.copy( this.normal );
  4610. face.color.copy( this.color );
  4611. face.centroid.copy( this.centroid );
  4612. face.materialIndex = this.materialIndex;
  4613. var i, il;
  4614. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4615. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4616. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4617. return face;
  4618. }
  4619. };
  4620. /**
  4621. * @author mrdoob / http://mrdoob.com/
  4622. * @author alteredq / http://alteredqualia.com/
  4623. */
  4624. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  4625. this.a = a;
  4626. this.b = b;
  4627. this.c = c;
  4628. this.d = d;
  4629. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  4630. this.vertexNormals = normal instanceof Array ? normal : [ ];
  4631. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  4632. this.vertexColors = color instanceof Array ? color : [];
  4633. this.vertexTangents = [];
  4634. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  4635. this.centroid = new THREE.Vector3();
  4636. };
  4637. THREE.Face4.prototype = {
  4638. constructor: THREE.Face4,
  4639. clone: function () {
  4640. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  4641. face.normal.copy( this.normal );
  4642. face.color.copy( this.color );
  4643. face.centroid.copy( this.centroid );
  4644. face.materialIndex = this.materialIndex;
  4645. var i, il;
  4646. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  4647. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  4648. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  4649. return face;
  4650. }
  4651. };
  4652. /**
  4653. * @author mrdoob / http://mrdoob.com/
  4654. * @author kile / http://kile.stravaganza.org/
  4655. * @author alteredq / http://alteredqualia.com/
  4656. * @author mikael emtinger / http://gomo.se/
  4657. * @author zz85 / http://www.lab4games.net/zz85/blog
  4658. * @author bhouston / http://exocortex.com
  4659. */
  4660. THREE.Geometry = function () {
  4661. this.id = THREE.Math.generateUUID();
  4662. this.name = '';
  4663. this.vertices = [];
  4664. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  4665. this.normals = []; // one-to-one vertex normals, used in Ribbon
  4666. this.faces = [];
  4667. this.faceUvs = [[]];
  4668. this.faceVertexUvs = [[]];
  4669. this.morphTargets = [];
  4670. this.morphColors = [];
  4671. this.morphNormals = [];
  4672. this.skinWeights = [];
  4673. this.skinIndices = [];
  4674. this.lineDistances = [];
  4675. this.boundingBox = null;
  4676. this.boundingSphere = null;
  4677. this.hasTangents = false;
  4678. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  4679. // update flags
  4680. this.verticesNeedUpdate = false;
  4681. this.elementsNeedUpdate = false;
  4682. this.uvsNeedUpdate = false;
  4683. this.normalsNeedUpdate = false;
  4684. this.tangentsNeedUpdate = false;
  4685. this.colorsNeedUpdate = false;
  4686. this.lineDistancesNeedUpdate = false;
  4687. this.buffersNeedUpdate = false;
  4688. };
  4689. THREE.Geometry.prototype = {
  4690. constructor: THREE.Geometry,
  4691. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  4692. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  4693. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  4694. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  4695. applyMatrix: function ( matrix ) {
  4696. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  4697. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  4698. var vertex = this.vertices[ i ];
  4699. vertex.applyMatrix4( matrix );
  4700. }
  4701. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  4702. var face = this.faces[ i ];
  4703. face.normal.applyMatrix3( normalMatrix ).normalize();
  4704. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  4705. face.vertexNormals[ j ].applyMatrix3( normalMatrix ).normalize();
  4706. }
  4707. face.centroid.applyMatrix4( matrix );
  4708. }
  4709. if ( this.boundingBox instanceof THREE.Box3 ) {
  4710. this.computeBoundingBox();
  4711. }
  4712. if ( this.boundingSphere instanceof THREE.Sphere ) {
  4713. this.computeBoundingSphere();
  4714. }
  4715. },
  4716. computeCentroids: function () {
  4717. var f, fl, face;
  4718. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4719. face = this.faces[ f ];
  4720. face.centroid.set( 0, 0, 0 );
  4721. if ( face instanceof THREE.Face3 ) {
  4722. face.centroid.add( this.vertices[ face.a ] );
  4723. face.centroid.add( this.vertices[ face.b ] );
  4724. face.centroid.add( this.vertices[ face.c ] );
  4725. face.centroid.divideScalar( 3 );
  4726. } else if ( face instanceof THREE.Face4 ) {
  4727. face.centroid.add( this.vertices[ face.a ] );
  4728. face.centroid.add( this.vertices[ face.b ] );
  4729. face.centroid.add( this.vertices[ face.c ] );
  4730. face.centroid.add( this.vertices[ face.d ] );
  4731. face.centroid.divideScalar( 4 );
  4732. }
  4733. }
  4734. },
  4735. computeFaceNormals: function () {
  4736. var cb = new THREE.Vector3(), ab = new THREE.Vector3();
  4737. for ( var f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4738. var face = this.faces[ f ];
  4739. var vA = this.vertices[ face.a ];
  4740. var vB = this.vertices[ face.b ];
  4741. var vC = this.vertices[ face.c ];
  4742. cb.subVectors( vC, vB );
  4743. ab.subVectors( vA, vB );
  4744. cb.cross( ab );
  4745. cb.normalize();
  4746. face.normal.copy( cb );
  4747. }
  4748. },
  4749. computeVertexNormals: function ( areaWeighted ) {
  4750. var v, vl, f, fl, face, vertices;
  4751. // create internal buffers for reuse when calling this method repeatedly
  4752. // (otherwise memory allocation / deallocation every frame is big resource hog)
  4753. if ( this.__tmpVertices === undefined ) {
  4754. this.__tmpVertices = new Array( this.vertices.length );
  4755. vertices = this.__tmpVertices;
  4756. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4757. vertices[ v ] = new THREE.Vector3();
  4758. }
  4759. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4760. face = this.faces[ f ];
  4761. if ( face instanceof THREE.Face3 ) {
  4762. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4763. } else if ( face instanceof THREE.Face4 ) {
  4764. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  4765. }
  4766. }
  4767. } else {
  4768. vertices = this.__tmpVertices;
  4769. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4770. vertices[ v ].set( 0, 0, 0 );
  4771. }
  4772. }
  4773. if ( areaWeighted ) {
  4774. // vertex normals weighted by triangle areas
  4775. // http://www.iquilezles.org/www/articles/normals/normals.htm
  4776. var vA, vB, vC, vD;
  4777. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  4778. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  4779. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4780. face = this.faces[ f ];
  4781. if ( face instanceof THREE.Face3 ) {
  4782. vA = this.vertices[ face.a ];
  4783. vB = this.vertices[ face.b ];
  4784. vC = this.vertices[ face.c ];
  4785. cb.subVectors( vC, vB );
  4786. ab.subVectors( vA, vB );
  4787. cb.cross( ab );
  4788. vertices[ face.a ].add( cb );
  4789. vertices[ face.b ].add( cb );
  4790. vertices[ face.c ].add( cb );
  4791. } else if ( face instanceof THREE.Face4 ) {
  4792. vA = this.vertices[ face.a ];
  4793. vB = this.vertices[ face.b ];
  4794. vC = this.vertices[ face.c ];
  4795. vD = this.vertices[ face.d ];
  4796. // abd
  4797. db.subVectors( vD, vB );
  4798. ab.subVectors( vA, vB );
  4799. db.cross( ab );
  4800. vertices[ face.a ].add( db );
  4801. vertices[ face.b ].add( db );
  4802. vertices[ face.d ].add( db );
  4803. // bcd
  4804. dc.subVectors( vD, vC );
  4805. bc.subVectors( vB, vC );
  4806. dc.cross( bc );
  4807. vertices[ face.b ].add( dc );
  4808. vertices[ face.c ].add( dc );
  4809. vertices[ face.d ].add( dc );
  4810. }
  4811. }
  4812. } else {
  4813. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4814. face = this.faces[ f ];
  4815. if ( face instanceof THREE.Face3 ) {
  4816. vertices[ face.a ].add( face.normal );
  4817. vertices[ face.b ].add( face.normal );
  4818. vertices[ face.c ].add( face.normal );
  4819. } else if ( face instanceof THREE.Face4 ) {
  4820. vertices[ face.a ].add( face.normal );
  4821. vertices[ face.b ].add( face.normal );
  4822. vertices[ face.c ].add( face.normal );
  4823. vertices[ face.d ].add( face.normal );
  4824. }
  4825. }
  4826. }
  4827. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4828. vertices[ v ].normalize();
  4829. }
  4830. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4831. face = this.faces[ f ];
  4832. if ( face instanceof THREE.Face3 ) {
  4833. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4834. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4835. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4836. } else if ( face instanceof THREE.Face4 ) {
  4837. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  4838. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  4839. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  4840. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  4841. }
  4842. }
  4843. },
  4844. computeMorphNormals: function () {
  4845. var i, il, f, fl, face;
  4846. // save original normals
  4847. // - create temp variables on first access
  4848. // otherwise just copy (for faster repeated calls)
  4849. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4850. face = this.faces[ f ];
  4851. if ( ! face.__originalFaceNormal ) {
  4852. face.__originalFaceNormal = face.normal.clone();
  4853. } else {
  4854. face.__originalFaceNormal.copy( face.normal );
  4855. }
  4856. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  4857. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  4858. if ( ! face.__originalVertexNormals[ i ] ) {
  4859. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  4860. } else {
  4861. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  4862. }
  4863. }
  4864. }
  4865. // use temp geometry to compute face and vertex normals for each morph
  4866. var tmpGeo = new THREE.Geometry();
  4867. tmpGeo.faces = this.faces;
  4868. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  4869. // create on first access
  4870. if ( ! this.morphNormals[ i ] ) {
  4871. this.morphNormals[ i ] = {};
  4872. this.morphNormals[ i ].faceNormals = [];
  4873. this.morphNormals[ i ].vertexNormals = [];
  4874. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  4875. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  4876. var faceNormal, vertexNormals;
  4877. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4878. face = this.faces[ f ];
  4879. faceNormal = new THREE.Vector3();
  4880. if ( face instanceof THREE.Face3 ) {
  4881. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  4882. } else {
  4883. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  4884. }
  4885. dstNormalsFace.push( faceNormal );
  4886. dstNormalsVertex.push( vertexNormals );
  4887. }
  4888. }
  4889. var morphNormals = this.morphNormals[ i ];
  4890. // set vertices to morph target
  4891. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  4892. // compute morph normals
  4893. tmpGeo.computeFaceNormals();
  4894. tmpGeo.computeVertexNormals();
  4895. // store morph normals
  4896. var faceNormal, vertexNormals;
  4897. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4898. face = this.faces[ f ];
  4899. faceNormal = morphNormals.faceNormals[ f ];
  4900. vertexNormals = morphNormals.vertexNormals[ f ];
  4901. faceNormal.copy( face.normal );
  4902. if ( face instanceof THREE.Face3 ) {
  4903. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4904. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4905. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4906. } else {
  4907. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  4908. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  4909. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  4910. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  4911. }
  4912. }
  4913. }
  4914. // restore original normals
  4915. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4916. face = this.faces[ f ];
  4917. face.normal = face.__originalFaceNormal;
  4918. face.vertexNormals = face.__originalVertexNormals;
  4919. }
  4920. },
  4921. computeTangents: function () {
  4922. // based on http://www.terathon.com/code/tangent.html
  4923. // tangents go to vertices
  4924. var f, fl, v, vl, i, il, vertexIndex,
  4925. face, uv, vA, vB, vC, uvA, uvB, uvC,
  4926. x1, x2, y1, y2, z1, z2,
  4927. s1, s2, t1, t2, r, t, test,
  4928. tan1 = [], tan2 = [],
  4929. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  4930. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  4931. n = new THREE.Vector3(), w;
  4932. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  4933. tan1[ v ] = new THREE.Vector3();
  4934. tan2[ v ] = new THREE.Vector3();
  4935. }
  4936. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4937. vA = context.vertices[ a ];
  4938. vB = context.vertices[ b ];
  4939. vC = context.vertices[ c ];
  4940. uvA = uv[ ua ];
  4941. uvB = uv[ ub ];
  4942. uvC = uv[ uc ];
  4943. x1 = vB.x - vA.x;
  4944. x2 = vC.x - vA.x;
  4945. y1 = vB.y - vA.y;
  4946. y2 = vC.y - vA.y;
  4947. z1 = vB.z - vA.z;
  4948. z2 = vC.z - vA.z;
  4949. s1 = uvB.x - uvA.x;
  4950. s2 = uvC.x - uvA.x;
  4951. t1 = uvB.y - uvA.y;
  4952. t2 = uvC.y - uvA.y;
  4953. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4954. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4955. ( t2 * y1 - t1 * y2 ) * r,
  4956. ( t2 * z1 - t1 * z2 ) * r );
  4957. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4958. ( s1 * y2 - s2 * y1 ) * r,
  4959. ( s1 * z2 - s2 * z1 ) * r );
  4960. tan1[ a ].add( sdir );
  4961. tan1[ b ].add( sdir );
  4962. tan1[ c ].add( sdir );
  4963. tan2[ a ].add( tdir );
  4964. tan2[ b ].add( tdir );
  4965. tan2[ c ].add( tdir );
  4966. }
  4967. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4968. face = this.faces[ f ];
  4969. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4970. if ( face instanceof THREE.Face3 ) {
  4971. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4972. } else if ( face instanceof THREE.Face4 ) {
  4973. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4974. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4975. }
  4976. }
  4977. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4978. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4979. face = this.faces[ f ];
  4980. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4981. n.copy( face.vertexNormals[ i ] );
  4982. vertexIndex = face[ faceIndex[ i ] ];
  4983. t = tan1[ vertexIndex ];
  4984. // Gram-Schmidt orthogonalize
  4985. tmp.copy( t );
  4986. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4987. // Calculate handedness
  4988. tmp2.crossVectors( face.vertexNormals[ i ], t );
  4989. test = tmp2.dot( tan2[ vertexIndex ] );
  4990. w = (test < 0.0) ? -1.0 : 1.0;
  4991. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4992. }
  4993. }
  4994. this.hasTangents = true;
  4995. },
  4996. computeLineDistances: function ( ) {
  4997. var d = 0;
  4998. var vertices = this.vertices;
  4999. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5000. if ( i > 0 ) {
  5001. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  5002. }
  5003. this.lineDistances[ i ] = d;
  5004. }
  5005. },
  5006. computeBoundingBox: function () {
  5007. if ( this.boundingBox === null ) {
  5008. this.boundingBox = new THREE.Box3();
  5009. }
  5010. this.boundingBox.setFromPoints( this.vertices );
  5011. },
  5012. computeBoundingSphere: function () {
  5013. if ( this.boundingSphere === null ) {
  5014. this.boundingSphere = new THREE.Sphere();
  5015. }
  5016. this.boundingSphere.setFromPoints( this.vertices );
  5017. },
  5018. /*
  5019. * Checks for duplicate vertices with hashmap.
  5020. * Duplicated vertices are removed
  5021. * and faces' vertices are updated.
  5022. */
  5023. mergeVertices: function () {
  5024. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  5025. var unique = [], changes = [];
  5026. var v, key;
  5027. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  5028. var precision = Math.pow( 10, precisionPoints );
  5029. var i,il, face;
  5030. var indices, k, j, jl, u;
  5031. // reset cache of vertices as it now will be changing.
  5032. this.__tmpVertices = undefined;
  5033. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  5034. v = this.vertices[ i ];
  5035. key = Math.round( v.x * precision ) + '_' + Math.round( v.y * precision ) + '_' + Math.round( v.z * precision );
  5036. if ( verticesMap[ key ] === undefined ) {
  5037. verticesMap[ key ] = i;
  5038. unique.push( this.vertices[ i ] );
  5039. changes[ i ] = unique.length - 1;
  5040. } else {
  5041. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  5042. changes[ i ] = changes[ verticesMap[ key ] ];
  5043. }
  5044. };
  5045. // if faces are completely degenerate after merging vertices, we
  5046. // have to remove them from the geometry.
  5047. var faceIndicesToRemove = [];
  5048. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  5049. face = this.faces[ i ];
  5050. if ( face instanceof THREE.Face3 ) {
  5051. face.a = changes[ face.a ];
  5052. face.b = changes[ face.b ];
  5053. face.c = changes[ face.c ];
  5054. indices = [ face.a, face.b, face.c ];
  5055. var dupIndex = -1;
  5056. // if any duplicate vertices are found in a Face3
  5057. // we have to remove the face as nothing can be saved
  5058. for ( var n = 0; n < 3; n ++ ) {
  5059. if ( indices[ n ] == indices[ ( n + 1 ) % 3 ] ) {
  5060. dupIndex = n;
  5061. faceIndicesToRemove.push( i );
  5062. break;
  5063. }
  5064. }
  5065. } else if ( face instanceof THREE.Face4 ) {
  5066. face.a = changes[ face.a ];
  5067. face.b = changes[ face.b ];
  5068. face.c = changes[ face.c ];
  5069. face.d = changes[ face.d ];
  5070. // check dups in (a, b, c, d) and convert to -> face3
  5071. indices = [ face.a, face.b, face.c, face.d ];
  5072. var dupIndex = -1;
  5073. for ( var n = 0; n < 4; n ++ ) {
  5074. if ( indices[ n ] == indices[ ( n + 1 ) % 4 ] ) {
  5075. // if more than one duplicated vertex is found
  5076. // we can't generate any valid Face3's, thus
  5077. // we need to remove this face complete.
  5078. if ( dupIndex >= 0 ) {
  5079. faceIndicesToRemove.push( i );
  5080. }
  5081. dupIndex = n;
  5082. }
  5083. }
  5084. if ( dupIndex >= 0 ) {
  5085. indices.splice( dupIndex, 1 );
  5086. var newFace = new THREE.Face3( indices[0], indices[1], indices[2], face.normal, face.color, face.materialIndex );
  5087. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5088. u = this.faceVertexUvs[ j ][ i ];
  5089. if ( u ) {
  5090. u.splice( dupIndex, 1 );
  5091. }
  5092. }
  5093. if( face.vertexNormals && face.vertexNormals.length > 0) {
  5094. newFace.vertexNormals = face.vertexNormals;
  5095. newFace.vertexNormals.splice( dupIndex, 1 );
  5096. }
  5097. if( face.vertexColors && face.vertexColors.length > 0 ) {
  5098. newFace.vertexColors = face.vertexColors;
  5099. newFace.vertexColors.splice( dupIndex, 1 );
  5100. }
  5101. this.faces[ i ] = newFace;
  5102. }
  5103. }
  5104. }
  5105. for ( i = faceIndicesToRemove.length - 1; i >= 0; i -- ) {
  5106. this.faces.splice( i, 1 );
  5107. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  5108. this.faceVertexUvs[ j ].splice( i, 1 );
  5109. }
  5110. }
  5111. // Use unique set of vertices
  5112. var diff = this.vertices.length - unique.length;
  5113. this.vertices = unique;
  5114. return diff;
  5115. },
  5116. clone: function () {
  5117. var geometry = new THREE.Geometry();
  5118. var vertices = this.vertices;
  5119. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  5120. geometry.vertices.push( vertices[ i ].clone() );
  5121. }
  5122. var faces = this.faces;
  5123. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  5124. geometry.faces.push( faces[ i ].clone() );
  5125. }
  5126. var uvs = this.faceVertexUvs[ 0 ];
  5127. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  5128. var uv = uvs[ i ], uvCopy = [];
  5129. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  5130. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  5131. }
  5132. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  5133. }
  5134. return geometry;
  5135. },
  5136. dispose: function () {
  5137. this.dispatchEvent( { type: 'dispose' } );
  5138. }
  5139. };
  5140. /**
  5141. * @author alteredq / http://alteredqualia.com/
  5142. */
  5143. THREE.BufferGeometry = function () {
  5144. this.id = THREE.Math.generateUUID();
  5145. // attributes
  5146. this.attributes = {};
  5147. // attributes typed arrays are kept only if dynamic flag is set
  5148. this.dynamic = false;
  5149. // offsets for chunks when using indexed elements
  5150. this.offsets = [];
  5151. // boundings
  5152. this.boundingBox = null;
  5153. this.boundingSphere = null;
  5154. this.hasTangents = false;
  5155. // for compatibility
  5156. this.morphTargets = [];
  5157. };
  5158. THREE.BufferGeometry.prototype = {
  5159. constructor: THREE.BufferGeometry,
  5160. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  5161. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  5162. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  5163. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  5164. applyMatrix: function ( matrix ) {
  5165. var positionArray;
  5166. var normalArray;
  5167. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  5168. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  5169. if ( positionArray !== undefined ) {
  5170. matrix.multiplyVector3Array( positionArray );
  5171. this.verticesNeedUpdate = true;
  5172. }
  5173. if ( normalArray !== undefined ) {
  5174. var normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  5175. normalMatrix.multiplyVector3Array( normalArray );
  5176. this.normalizeNormals();
  5177. this.normalsNeedUpdate = true;
  5178. }
  5179. },
  5180. computeBoundingBox: function () {
  5181. if ( this.boundingBox === null ) {
  5182. this.boundingBox = new THREE.Box3();
  5183. }
  5184. var positions = this.attributes[ "position" ].array;
  5185. if ( positions ) {
  5186. var bb = this.boundingBox;
  5187. var x, y, z;
  5188. if( positions.length >= 3 ) {
  5189. bb.min.x = bb.max.x = positions[ 0 ];
  5190. bb.min.y = bb.max.y = positions[ 1 ];
  5191. bb.min.z = bb.max.z = positions[ 2 ];
  5192. }
  5193. for ( var i = 3, il = positions.length; i < il; i += 3 ) {
  5194. x = positions[ i ];
  5195. y = positions[ i + 1 ];
  5196. z = positions[ i + 2 ];
  5197. // bounding box
  5198. if ( x < bb.min.x ) {
  5199. bb.min.x = x;
  5200. } else if ( x > bb.max.x ) {
  5201. bb.max.x = x;
  5202. }
  5203. if ( y < bb.min.y ) {
  5204. bb.min.y = y;
  5205. } else if ( y > bb.max.y ) {
  5206. bb.max.y = y;
  5207. }
  5208. if ( z < bb.min.z ) {
  5209. bb.min.z = z;
  5210. } else if ( z > bb.max.z ) {
  5211. bb.max.z = z;
  5212. }
  5213. }
  5214. }
  5215. if ( positions === undefined || positions.length === 0 ) {
  5216. this.boundingBox.min.set( 0, 0, 0 );
  5217. this.boundingBox.max.set( 0, 0, 0 );
  5218. }
  5219. },
  5220. computeBoundingSphere: function () {
  5221. if ( this.boundingSphere === null ) {
  5222. this.boundingSphere = new THREE.Sphere();
  5223. }
  5224. var positions = this.attributes[ "position" ].array;
  5225. if ( positions ) {
  5226. var radiusSq, maxRadiusSq = 0;
  5227. var x, y, z;
  5228. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  5229. x = positions[ i ];
  5230. y = positions[ i + 1 ];
  5231. z = positions[ i + 2 ];
  5232. radiusSq = x * x + y * y + z * z;
  5233. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  5234. }
  5235. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  5236. }
  5237. },
  5238. computeVertexNormals: function () {
  5239. if ( this.attributes[ "position" ] ) {
  5240. var i, il;
  5241. var j, jl;
  5242. var nVertexElements = this.attributes[ "position" ].array.length;
  5243. if ( this.attributes[ "normal" ] === undefined ) {
  5244. this.attributes[ "normal" ] = {
  5245. itemSize: 3,
  5246. array: new Float32Array( nVertexElements )
  5247. };
  5248. } else {
  5249. // reset existing normals to zero
  5250. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  5251. this.attributes[ "normal" ].array[ i ] = 0;
  5252. }
  5253. }
  5254. var positions = this.attributes[ "position" ].array;
  5255. var normals = this.attributes[ "normal" ].array;
  5256. var vA, vB, vC, x, y, z,
  5257. pA = new THREE.Vector3(),
  5258. pB = new THREE.Vector3(),
  5259. pC = new THREE.Vector3(),
  5260. cb = new THREE.Vector3(),
  5261. ab = new THREE.Vector3();
  5262. // indexed elements
  5263. if ( this.attributes[ "index" ] ) {
  5264. var indices = this.attributes[ "index" ].array;
  5265. var offsets = this.offsets;
  5266. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5267. var start = offsets[ j ].start;
  5268. var count = offsets[ j ].count;
  5269. var index = offsets[ j ].index;
  5270. for ( i = start, il = start + count; i < il; i += 3 ) {
  5271. vA = index + indices[ i ];
  5272. vB = index + indices[ i + 1 ];
  5273. vC = index + indices[ i + 2 ];
  5274. x = positions[ vA * 3 ];
  5275. y = positions[ vA * 3 + 1 ];
  5276. z = positions[ vA * 3 + 2 ];
  5277. pA.set( x, y, z );
  5278. x = positions[ vB * 3 ];
  5279. y = positions[ vB * 3 + 1 ];
  5280. z = positions[ vB * 3 + 2 ];
  5281. pB.set( x, y, z );
  5282. x = positions[ vC * 3 ];
  5283. y = positions[ vC * 3 + 1 ];
  5284. z = positions[ vC * 3 + 2 ];
  5285. pC.set( x, y, z );
  5286. cb.subVectors( pC, pB );
  5287. ab.subVectors( pA, pB );
  5288. cb.cross( ab );
  5289. normals[ vA * 3 ] += cb.x;
  5290. normals[ vA * 3 + 1 ] += cb.y;
  5291. normals[ vA * 3 + 2 ] += cb.z;
  5292. normals[ vB * 3 ] += cb.x;
  5293. normals[ vB * 3 + 1 ] += cb.y;
  5294. normals[ vB * 3 + 2 ] += cb.z;
  5295. normals[ vC * 3 ] += cb.x;
  5296. normals[ vC * 3 + 1 ] += cb.y;
  5297. normals[ vC * 3 + 2 ] += cb.z;
  5298. }
  5299. }
  5300. // non-indexed elements (unconnected triangle soup)
  5301. } else {
  5302. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  5303. x = positions[ i ];
  5304. y = positions[ i + 1 ];
  5305. z = positions[ i + 2 ];
  5306. pA.set( x, y, z );
  5307. x = positions[ i + 3 ];
  5308. y = positions[ i + 4 ];
  5309. z = positions[ i + 5 ];
  5310. pB.set( x, y, z );
  5311. x = positions[ i + 6 ];
  5312. y = positions[ i + 7 ];
  5313. z = positions[ i + 8 ];
  5314. pC.set( x, y, z );
  5315. cb.subVectors( pC, pB );
  5316. ab.subVectors( pA, pB );
  5317. cb.cross( ab );
  5318. normals[ i ] = cb.x;
  5319. normals[ i + 1 ] = cb.y;
  5320. normals[ i + 2 ] = cb.z;
  5321. normals[ i + 3 ] = cb.x;
  5322. normals[ i + 4 ] = cb.y;
  5323. normals[ i + 5 ] = cb.z;
  5324. normals[ i + 6 ] = cb.x;
  5325. normals[ i + 7 ] = cb.y;
  5326. normals[ i + 8 ] = cb.z;
  5327. }
  5328. }
  5329. this.normalizeNormals();
  5330. this.normalsNeedUpdate = true;
  5331. }
  5332. },
  5333. normalizeNormals: function () {
  5334. var normals = this.attributes[ "normal" ].array;
  5335. var x, y, z, n;
  5336. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  5337. x = normals[ i ];
  5338. y = normals[ i + 1 ];
  5339. z = normals[ i + 2 ];
  5340. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  5341. normals[ i ] *= n;
  5342. normals[ i + 1 ] *= n;
  5343. normals[ i + 2 ] *= n;
  5344. }
  5345. },
  5346. computeTangents: function () {
  5347. // based on http://www.terathon.com/code/tangent.html
  5348. // (per vertex tangents)
  5349. if ( this.attributes[ "index" ] === undefined ||
  5350. this.attributes[ "position" ] === undefined ||
  5351. this.attributes[ "normal" ] === undefined ||
  5352. this.attributes[ "uv" ] === undefined ) {
  5353. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  5354. return;
  5355. }
  5356. var indices = this.attributes[ "index" ].array;
  5357. var positions = this.attributes[ "position" ].array;
  5358. var normals = this.attributes[ "normal" ].array;
  5359. var uvs = this.attributes[ "uv" ].array;
  5360. var nVertices = positions.length / 3;
  5361. if ( this.attributes[ "tangent" ] === undefined ) {
  5362. var nTangentElements = 4 * nVertices;
  5363. this.attributes[ "tangent" ] = {
  5364. itemSize: 4,
  5365. array: new Float32Array( nTangentElements )
  5366. };
  5367. }
  5368. var tangents = this.attributes[ "tangent" ].array;
  5369. var tan1 = [], tan2 = [];
  5370. for ( var k = 0; k < nVertices; k ++ ) {
  5371. tan1[ k ] = new THREE.Vector3();
  5372. tan2[ k ] = new THREE.Vector3();
  5373. }
  5374. var xA, yA, zA,
  5375. xB, yB, zB,
  5376. xC, yC, zC,
  5377. uA, vA,
  5378. uB, vB,
  5379. uC, vC,
  5380. x1, x2, y1, y2, z1, z2,
  5381. s1, s2, t1, t2, r;
  5382. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  5383. function handleTriangle( a, b, c ) {
  5384. xA = positions[ a * 3 ];
  5385. yA = positions[ a * 3 + 1 ];
  5386. zA = positions[ a * 3 + 2 ];
  5387. xB = positions[ b * 3 ];
  5388. yB = positions[ b * 3 + 1 ];
  5389. zB = positions[ b * 3 + 2 ];
  5390. xC = positions[ c * 3 ];
  5391. yC = positions[ c * 3 + 1 ];
  5392. zC = positions[ c * 3 + 2 ];
  5393. uA = uvs[ a * 2 ];
  5394. vA = uvs[ a * 2 + 1 ];
  5395. uB = uvs[ b * 2 ];
  5396. vB = uvs[ b * 2 + 1 ];
  5397. uC = uvs[ c * 2 ];
  5398. vC = uvs[ c * 2 + 1 ];
  5399. x1 = xB - xA;
  5400. x2 = xC - xA;
  5401. y1 = yB - yA;
  5402. y2 = yC - yA;
  5403. z1 = zB - zA;
  5404. z2 = zC - zA;
  5405. s1 = uB - uA;
  5406. s2 = uC - uA;
  5407. t1 = vB - vA;
  5408. t2 = vC - vA;
  5409. r = 1.0 / ( s1 * t2 - s2 * t1 );
  5410. sdir.set(
  5411. ( t2 * x1 - t1 * x2 ) * r,
  5412. ( t2 * y1 - t1 * y2 ) * r,
  5413. ( t2 * z1 - t1 * z2 ) * r
  5414. );
  5415. tdir.set(
  5416. ( s1 * x2 - s2 * x1 ) * r,
  5417. ( s1 * y2 - s2 * y1 ) * r,
  5418. ( s1 * z2 - s2 * z1 ) * r
  5419. );
  5420. tan1[ a ].add( sdir );
  5421. tan1[ b ].add( sdir );
  5422. tan1[ c ].add( sdir );
  5423. tan2[ a ].add( tdir );
  5424. tan2[ b ].add( tdir );
  5425. tan2[ c ].add( tdir );
  5426. }
  5427. var i, il;
  5428. var j, jl;
  5429. var iA, iB, iC;
  5430. var offsets = this.offsets;
  5431. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5432. var start = offsets[ j ].start;
  5433. var count = offsets[ j ].count;
  5434. var index = offsets[ j ].index;
  5435. for ( i = start, il = start + count; i < il; i += 3 ) {
  5436. iA = index + indices[ i ];
  5437. iB = index + indices[ i + 1 ];
  5438. iC = index + indices[ i + 2 ];
  5439. handleTriangle( iA, iB, iC );
  5440. }
  5441. }
  5442. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  5443. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  5444. var w, t, test;
  5445. function handleVertex( v ) {
  5446. n.x = normals[ v * 3 ];
  5447. n.y = normals[ v * 3 + 1 ];
  5448. n.z = normals[ v * 3 + 2 ];
  5449. n2.copy( n );
  5450. t = tan1[ v ];
  5451. // Gram-Schmidt orthogonalize
  5452. tmp.copy( t );
  5453. tmp.sub( n.multiplyScalar( n.dot( t ) ) ).normalize();
  5454. // Calculate handedness
  5455. tmp2.crossVectors( n2, t );
  5456. test = tmp2.dot( tan2[ v ] );
  5457. w = ( test < 0.0 ) ? -1.0 : 1.0;
  5458. tangents[ v * 4 ] = tmp.x;
  5459. tangents[ v * 4 + 1 ] = tmp.y;
  5460. tangents[ v * 4 + 2 ] = tmp.z;
  5461. tangents[ v * 4 + 3 ] = w;
  5462. }
  5463. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  5464. var start = offsets[ j ].start;
  5465. var count = offsets[ j ].count;
  5466. var index = offsets[ j ].index;
  5467. for ( i = start, il = start + count; i < il; i += 3 ) {
  5468. iA = index + indices[ i ];
  5469. iB = index + indices[ i + 1 ];
  5470. iC = index + indices[ i + 2 ];
  5471. handleVertex( iA );
  5472. handleVertex( iB );
  5473. handleVertex( iC );
  5474. }
  5475. }
  5476. this.hasTangents = true;
  5477. this.tangentsNeedUpdate = true;
  5478. },
  5479. dispose: function () {
  5480. this.dispatchEvent( { type: 'dispose' } );
  5481. }
  5482. };
  5483. /**
  5484. * @author mrdoob / http://mrdoob.com/
  5485. * @author mikael emtinger / http://gomo.se/
  5486. * @author WestLangley / http://github.com/WestLangley
  5487. */
  5488. THREE.Camera = function () {
  5489. THREE.Object3D.call( this );
  5490. this.matrixWorldInverse = new THREE.Matrix4();
  5491. this.projectionMatrix = new THREE.Matrix4();
  5492. this.projectionMatrixInverse = new THREE.Matrix4();
  5493. };
  5494. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  5495. THREE.Camera.prototype.lookAt = function () {
  5496. // This routine does not support cameras with rotated and/or translated parent(s)
  5497. var m1 = new THREE.Matrix4();
  5498. return function ( vector ) {
  5499. m1.lookAt( this.position, vector, this.up );
  5500. this.quaternion.setFromRotationMatrix( m1 );
  5501. };
  5502. }();
  5503. /**
  5504. * @author alteredq / http://alteredqualia.com/
  5505. */
  5506. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  5507. THREE.Camera.call( this );
  5508. this.left = left;
  5509. this.right = right;
  5510. this.top = top;
  5511. this.bottom = bottom;
  5512. this.near = ( near !== undefined ) ? near : 0.1;
  5513. this.far = ( far !== undefined ) ? far : 2000;
  5514. this.updateProjectionMatrix();
  5515. };
  5516. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  5517. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  5518. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  5519. };
  5520. /**
  5521. * @author mrdoob / http://mrdoob.com/
  5522. * @author greggman / http://games.greggman.com/
  5523. * @author zz85 / http://www.lab4games.net/zz85/blog
  5524. */
  5525. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  5526. THREE.Camera.call( this );
  5527. this.fov = fov !== undefined ? fov : 50;
  5528. this.aspect = aspect !== undefined ? aspect : 1;
  5529. this.near = near !== undefined ? near : 0.1;
  5530. this.far = far !== undefined ? far : 2000;
  5531. this.updateProjectionMatrix();
  5532. };
  5533. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  5534. /**
  5535. * Uses Focal Length (in mm) to estimate and set FOV
  5536. * 35mm (fullframe) camera is used if frame size is not specified;
  5537. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  5538. */
  5539. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  5540. if ( frameHeight === undefined ) frameHeight = 24;
  5541. this.fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  5542. this.updateProjectionMatrix();
  5543. }
  5544. /**
  5545. * Sets an offset in a larger frustum. This is useful for multi-window or
  5546. * multi-monitor/multi-machine setups.
  5547. *
  5548. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  5549. * the monitors are in grid like this
  5550. *
  5551. * +---+---+---+
  5552. * | A | B | C |
  5553. * +---+---+---+
  5554. * | D | E | F |
  5555. * +---+---+---+
  5556. *
  5557. * then for each monitor you would call it like this
  5558. *
  5559. * var w = 1920;
  5560. * var h = 1080;
  5561. * var fullWidth = w * 3;
  5562. * var fullHeight = h * 2;
  5563. *
  5564. * --A--
  5565. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  5566. * --B--
  5567. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  5568. * --C--
  5569. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  5570. * --D--
  5571. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  5572. * --E--
  5573. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  5574. * --F--
  5575. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  5576. *
  5577. * Note there is no reason monitors have to be the same size or in a grid.
  5578. */
  5579. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  5580. this.fullWidth = fullWidth;
  5581. this.fullHeight = fullHeight;
  5582. this.x = x;
  5583. this.y = y;
  5584. this.width = width;
  5585. this.height = height;
  5586. this.updateProjectionMatrix();
  5587. };
  5588. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  5589. if ( this.fullWidth ) {
  5590. var aspect = this.fullWidth / this.fullHeight;
  5591. var top = Math.tan( THREE.Math.degToRad( this.fov * 0.5 ) ) * this.near;
  5592. var bottom = -top;
  5593. var left = aspect * bottom;
  5594. var right = aspect * top;
  5595. var width = Math.abs( right - left );
  5596. var height = Math.abs( top - bottom );
  5597. this.projectionMatrix.makeFrustum(
  5598. left + this.x * width / this.fullWidth,
  5599. left + ( this.x + this.width ) * width / this.fullWidth,
  5600. top - ( this.y + this.height ) * height / this.fullHeight,
  5601. top - this.y * height / this.fullHeight,
  5602. this.near,
  5603. this.far
  5604. );
  5605. } else {
  5606. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  5607. }
  5608. };
  5609. /**
  5610. * @author mrdoob / http://mrdoob.com/
  5611. * @author alteredq / http://alteredqualia.com/
  5612. */
  5613. THREE.Light = function ( hex ) {
  5614. THREE.Object3D.call( this );
  5615. this.color = new THREE.Color( hex );
  5616. };
  5617. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  5618. THREE.Light.prototype.clone = function ( light ) {
  5619. if ( light === undefined ) light = new THREE.Light();
  5620. THREE.Object3D.prototype.clone.call( this, light );
  5621. light.color.copy( this.color );
  5622. return light;
  5623. };
  5624. /**
  5625. * @author mrdoob / http://mrdoob.com/
  5626. */
  5627. THREE.AmbientLight = function ( hex ) {
  5628. THREE.Light.call( this, hex );
  5629. };
  5630. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  5631. THREE.AmbientLight.prototype.clone = function () {
  5632. var light = new THREE.AmbientLight();
  5633. THREE.Light.prototype.clone.call( this, light );
  5634. return light;
  5635. };
  5636. /**
  5637. * @author MPanknin / http://www.redplant.de/
  5638. * @author alteredq / http://alteredqualia.com/
  5639. */
  5640. THREE.AreaLight = function ( hex, intensity ) {
  5641. THREE.Light.call( this, hex );
  5642. this.normal = new THREE.Vector3( 0, -1, 0 );
  5643. this.right = new THREE.Vector3( 1, 0, 0 );
  5644. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5645. this.width = 1.0;
  5646. this.height = 1.0;
  5647. this.constantAttenuation = 1.5;
  5648. this.linearAttenuation = 0.5;
  5649. this.quadraticAttenuation = 0.1;
  5650. };
  5651. THREE.AreaLight.prototype = Object.create( THREE.Light.prototype );
  5652. /**
  5653. * @author mrdoob / http://mrdoob.com/
  5654. * @author alteredq / http://alteredqualia.com/
  5655. */
  5656. THREE.DirectionalLight = function ( hex, intensity ) {
  5657. THREE.Light.call( this, hex );
  5658. this.position.set( 0, 1, 0 );
  5659. this.target = new THREE.Object3D();
  5660. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5661. this.castShadow = false;
  5662. this.onlyShadow = false;
  5663. //
  5664. this.shadowCameraNear = 50;
  5665. this.shadowCameraFar = 5000;
  5666. this.shadowCameraLeft = -500;
  5667. this.shadowCameraRight = 500;
  5668. this.shadowCameraTop = 500;
  5669. this.shadowCameraBottom = -500;
  5670. this.shadowCameraVisible = false;
  5671. this.shadowBias = 0;
  5672. this.shadowDarkness = 0.5;
  5673. this.shadowMapWidth = 512;
  5674. this.shadowMapHeight = 512;
  5675. //
  5676. this.shadowCascade = false;
  5677. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  5678. this.shadowCascadeCount = 2;
  5679. this.shadowCascadeBias = [ 0, 0, 0 ];
  5680. this.shadowCascadeWidth = [ 512, 512, 512 ];
  5681. this.shadowCascadeHeight = [ 512, 512, 512 ];
  5682. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  5683. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  5684. this.shadowCascadeArray = [];
  5685. //
  5686. this.shadowMap = null;
  5687. this.shadowMapSize = null;
  5688. this.shadowCamera = null;
  5689. this.shadowMatrix = null;
  5690. };
  5691. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  5692. THREE.DirectionalLight.prototype.clone = function () {
  5693. var light = new THREE.DirectionalLight();
  5694. THREE.Light.prototype.clone.call( this, light );
  5695. light.target = this.target.clone();
  5696. light.intensity = this.intensity;
  5697. light.castShadow = this.castShadow;
  5698. light.onlyShadow = this.onlyShadow;
  5699. return light;
  5700. };
  5701. /**
  5702. * @author alteredq / http://alteredqualia.com/
  5703. */
  5704. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  5705. THREE.Light.call( this, skyColorHex );
  5706. this.position.set( 0, 100, 0 );
  5707. this.groundColor = new THREE.Color( groundColorHex );
  5708. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5709. };
  5710. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  5711. THREE.HemisphereLight.prototype.clone = function () {
  5712. var light = new THREE.PointLight();
  5713. THREE.Light.prototype.clone.call( this, light );
  5714. light.groundColor.copy( this.groundColor );
  5715. light.intensity = this.intensity;
  5716. return light;
  5717. };
  5718. /**
  5719. * @author mrdoob / http://mrdoob.com/
  5720. */
  5721. THREE.PointLight = function ( hex, intensity, distance ) {
  5722. THREE.Light.call( this, hex );
  5723. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5724. this.distance = ( distance !== undefined ) ? distance : 0;
  5725. };
  5726. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  5727. THREE.PointLight.prototype.clone = function () {
  5728. var light = new THREE.PointLight();
  5729. THREE.Light.prototype.clone.call( this, light );
  5730. light.intensity = this.intensity;
  5731. light.distance = this.distance;
  5732. return light;
  5733. };
  5734. /**
  5735. * @author alteredq / http://alteredqualia.com/
  5736. */
  5737. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  5738. THREE.Light.call( this, hex );
  5739. this.position.set( 0, 1, 0 );
  5740. this.target = new THREE.Object3D();
  5741. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  5742. this.distance = ( distance !== undefined ) ? distance : 0;
  5743. this.angle = ( angle !== undefined ) ? angle : Math.PI / 3;
  5744. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  5745. this.castShadow = false;
  5746. this.onlyShadow = false;
  5747. //
  5748. this.shadowCameraNear = 50;
  5749. this.shadowCameraFar = 5000;
  5750. this.shadowCameraFov = 50;
  5751. this.shadowCameraVisible = false;
  5752. this.shadowBias = 0;
  5753. this.shadowDarkness = 0.5;
  5754. this.shadowMapWidth = 512;
  5755. this.shadowMapHeight = 512;
  5756. //
  5757. this.shadowMap = null;
  5758. this.shadowMapSize = null;
  5759. this.shadowCamera = null;
  5760. this.shadowMatrix = null;
  5761. };
  5762. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  5763. THREE.SpotLight.prototype.clone = function () {
  5764. var light = new THREE.SpotLight();
  5765. THREE.Light.prototype.clone.call( this, light );
  5766. light.target = this.target.clone();
  5767. light.intensity = this.intensity;
  5768. light.distance = this.distance;
  5769. light.angle = this.angle;
  5770. light.exponent = this.exponent;
  5771. light.castShadow = this.castShadow;
  5772. light.onlyShadow = this.onlyShadow;
  5773. return light;
  5774. };
  5775. /**
  5776. * @author alteredq / http://alteredqualia.com/
  5777. */
  5778. THREE.Loader = function ( showStatus ) {
  5779. this.showStatus = showStatus;
  5780. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  5781. this.onLoadStart = function () {};
  5782. this.onLoadProgress = function () {};
  5783. this.onLoadComplete = function () {};
  5784. };
  5785. THREE.Loader.prototype = {
  5786. constructor: THREE.Loader,
  5787. crossOrigin: 'anonymous',
  5788. addStatusElement: function () {
  5789. var e = document.createElement( "div" );
  5790. e.style.position = "absolute";
  5791. e.style.right = "0px";
  5792. e.style.top = "0px";
  5793. e.style.fontSize = "0.8em";
  5794. e.style.textAlign = "left";
  5795. e.style.background = "rgba(0,0,0,0.25)";
  5796. e.style.color = "#fff";
  5797. e.style.width = "120px";
  5798. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  5799. e.style.zIndex = 1000;
  5800. e.innerHTML = "Loading ...";
  5801. return e;
  5802. },
  5803. updateProgress: function ( progress ) {
  5804. var message = "Loaded ";
  5805. if ( progress.total ) {
  5806. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  5807. } else {
  5808. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  5809. }
  5810. this.statusDomElement.innerHTML = message;
  5811. },
  5812. extractUrlBase: function ( url ) {
  5813. var parts = url.split( '/' );
  5814. parts.pop();
  5815. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  5816. },
  5817. initMaterials: function ( materials, texturePath ) {
  5818. var array = [];
  5819. for ( var i = 0; i < materials.length; ++ i ) {
  5820. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  5821. }
  5822. return array;
  5823. },
  5824. needsTangents: function ( materials ) {
  5825. for( var i = 0, il = materials.length; i < il; i ++ ) {
  5826. var m = materials[ i ];
  5827. if ( m instanceof THREE.ShaderMaterial ) return true;
  5828. }
  5829. return false;
  5830. },
  5831. createMaterial: function ( m, texturePath ) {
  5832. var _this = this;
  5833. function is_pow2( n ) {
  5834. var l = Math.log( n ) / Math.LN2;
  5835. return Math.floor( l ) == l;
  5836. }
  5837. function nearest_pow2( n ) {
  5838. var l = Math.log( n ) / Math.LN2;
  5839. return Math.pow( 2, Math.round( l ) );
  5840. }
  5841. function load_image( where, url ) {
  5842. var image = new Image();
  5843. image.onload = function () {
  5844. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  5845. var width = nearest_pow2( this.width );
  5846. var height = nearest_pow2( this.height );
  5847. where.image.width = width;
  5848. where.image.height = height;
  5849. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  5850. } else {
  5851. where.image = this;
  5852. }
  5853. where.needsUpdate = true;
  5854. };
  5855. image.crossOrigin = _this.crossOrigin;
  5856. image.src = url;
  5857. }
  5858. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  5859. var isCompressed = /\.dds$/i.test( sourceFile );
  5860. var fullPath = texturePath + "/" + sourceFile;
  5861. if ( isCompressed ) {
  5862. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  5863. where[ name ] = texture;
  5864. } else {
  5865. var texture = document.createElement( 'canvas' );
  5866. where[ name ] = new THREE.Texture( texture );
  5867. }
  5868. where[ name ].sourceFile = sourceFile;
  5869. if( repeat ) {
  5870. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5871. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5872. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5873. }
  5874. if ( offset ) {
  5875. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5876. }
  5877. if ( wrap ) {
  5878. var wrapMap = {
  5879. "repeat": THREE.RepeatWrapping,
  5880. "mirror": THREE.MirroredRepeatWrapping
  5881. }
  5882. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5883. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5884. }
  5885. if ( anisotropy ) {
  5886. where[ name ].anisotropy = anisotropy;
  5887. }
  5888. if ( ! isCompressed ) {
  5889. load_image( where[ name ], fullPath );
  5890. }
  5891. }
  5892. function rgb2hex( rgb ) {
  5893. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5894. }
  5895. // defaults
  5896. var mtype = "MeshLambertMaterial";
  5897. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5898. // parameters from model file
  5899. if ( m.shading ) {
  5900. var shading = m.shading.toLowerCase();
  5901. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5902. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5903. }
  5904. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5905. mpars.blending = THREE[ m.blending ];
  5906. }
  5907. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5908. mpars.transparent = m.transparent;
  5909. }
  5910. if ( m.depthTest !== undefined ) {
  5911. mpars.depthTest = m.depthTest;
  5912. }
  5913. if ( m.depthWrite !== undefined ) {
  5914. mpars.depthWrite = m.depthWrite;
  5915. }
  5916. if ( m.visible !== undefined ) {
  5917. mpars.visible = m.visible;
  5918. }
  5919. if ( m.flipSided !== undefined ) {
  5920. mpars.side = THREE.BackSide;
  5921. }
  5922. if ( m.doubleSided !== undefined ) {
  5923. mpars.side = THREE.DoubleSide;
  5924. }
  5925. if ( m.wireframe !== undefined ) {
  5926. mpars.wireframe = m.wireframe;
  5927. }
  5928. if ( m.vertexColors !== undefined ) {
  5929. if ( m.vertexColors === "face" ) {
  5930. mpars.vertexColors = THREE.FaceColors;
  5931. } else if ( m.vertexColors ) {
  5932. mpars.vertexColors = THREE.VertexColors;
  5933. }
  5934. }
  5935. // colors
  5936. if ( m.colorDiffuse ) {
  5937. mpars.color = rgb2hex( m.colorDiffuse );
  5938. } else if ( m.DbgColor ) {
  5939. mpars.color = m.DbgColor;
  5940. }
  5941. if ( m.colorSpecular ) {
  5942. mpars.specular = rgb2hex( m.colorSpecular );
  5943. }
  5944. if ( m.colorAmbient ) {
  5945. mpars.ambient = rgb2hex( m.colorAmbient );
  5946. }
  5947. // modifiers
  5948. if ( m.transparency ) {
  5949. mpars.opacity = m.transparency;
  5950. }
  5951. if ( m.specularCoef ) {
  5952. mpars.shininess = m.specularCoef;
  5953. }
  5954. // textures
  5955. if ( m.mapDiffuse && texturePath ) {
  5956. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5957. }
  5958. if ( m.mapLight && texturePath ) {
  5959. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5960. }
  5961. if ( m.mapBump && texturePath ) {
  5962. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5963. }
  5964. if ( m.mapNormal && texturePath ) {
  5965. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5966. }
  5967. if ( m.mapSpecular && texturePath ) {
  5968. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5969. }
  5970. //
  5971. if ( m.mapBumpScale ) {
  5972. mpars.bumpScale = m.mapBumpScale;
  5973. }
  5974. // special case for normal mapped material
  5975. if ( m.mapNormal ) {
  5976. var shader = THREE.ShaderLib[ "normalmap" ];
  5977. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5978. uniforms[ "tNormal" ].value = mpars.normalMap;
  5979. if ( m.mapNormalFactor ) {
  5980. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5981. }
  5982. if ( mpars.map ) {
  5983. uniforms[ "tDiffuse" ].value = mpars.map;
  5984. uniforms[ "enableDiffuse" ].value = true;
  5985. }
  5986. if ( mpars.specularMap ) {
  5987. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5988. uniforms[ "enableSpecular" ].value = true;
  5989. }
  5990. if ( mpars.lightMap ) {
  5991. uniforms[ "tAO" ].value = mpars.lightMap;
  5992. uniforms[ "enableAO" ].value = true;
  5993. }
  5994. // for the moment don't handle displacement texture
  5995. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5996. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5997. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5998. uniforms[ "uShininess" ].value = mpars.shininess;
  5999. if ( mpars.opacity !== undefined ) {
  6000. uniforms[ "uOpacity" ].value = mpars.opacity;
  6001. }
  6002. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6003. var material = new THREE.ShaderMaterial( parameters );
  6004. if ( mpars.transparent ) {
  6005. material.transparent = true;
  6006. }
  6007. } else {
  6008. var material = new THREE[ mtype ]( mpars );
  6009. }
  6010. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6011. return material;
  6012. }
  6013. };
  6014. /**
  6015. * @author mrdoob / http://mrdoob.com/
  6016. */
  6017. THREE.XHRLoader = function ( manager ) {
  6018. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6019. };
  6020. THREE.XHRLoader.prototype = {
  6021. constructor: THREE.XHRLoader,
  6022. load: function ( url, onLoad, onProgress, onError ) {
  6023. var scope = this;
  6024. var request = new XMLHttpRequest();
  6025. if ( onLoad !== undefined ) {
  6026. request.addEventListener( 'load', function ( event ) {
  6027. scope.manager.itemEnd( url );
  6028. onLoad( event.target.responseText );
  6029. }, false );
  6030. }
  6031. if ( onProgress !== undefined ) {
  6032. request.addEventListener( 'progress', function ( event ) {
  6033. onProgress( event );
  6034. }, false );
  6035. }
  6036. if ( onError !== undefined ) {
  6037. request.addEventListener( 'error', function ( event ) {
  6038. onError( event );
  6039. }, false );
  6040. }
  6041. if ( this.crossOrigin !== undefined ) request.crossOrigin = this.crossOrigin;
  6042. request.open( 'GET', url, true );
  6043. request.send( null );
  6044. scope.manager.itemStart( url );
  6045. },
  6046. setCrossOrigin: function ( value ) {
  6047. this.crossOrigin = value;
  6048. }
  6049. };
  6050. /**
  6051. * @author mrdoob / http://mrdoob.com/
  6052. */
  6053. THREE.ImageLoader = function ( manager ) {
  6054. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6055. };
  6056. THREE.ImageLoader.prototype = {
  6057. constructor: THREE.ImageLoader,
  6058. load: function ( url, onLoad, onProgress, onError ) {
  6059. var scope = this;
  6060. var image = document.createElement( 'img' );
  6061. if ( onLoad !== undefined ) {
  6062. image.addEventListener( 'load', function ( event ) {
  6063. scope.manager.itemEnd( url );
  6064. onLoad( this );
  6065. }, false );
  6066. }
  6067. if ( onProgress !== undefined ) {
  6068. image.addEventListener( 'progress', function ( event ) {
  6069. onProgress( event );
  6070. }, false );
  6071. }
  6072. if ( onError !== undefined ) {
  6073. image.addEventListener( 'error', function ( event ) {
  6074. onError( event );
  6075. }, false );
  6076. }
  6077. if ( this.crossOrigin !== undefined ) image.crossOrigin = this.crossOrigin;
  6078. image.src = url;
  6079. scope.manager.itemStart( url );
  6080. },
  6081. setCrossOrigin: function ( value ) {
  6082. this.crossOrigin = value;
  6083. }
  6084. }
  6085. /**
  6086. * @author mrdoob / http://mrdoob.com/
  6087. * @author alteredq / http://alteredqualia.com/
  6088. */
  6089. THREE.JSONLoader = function ( showStatus ) {
  6090. THREE.Loader.call( this, showStatus );
  6091. this.withCredentials = false;
  6092. };
  6093. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  6094. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  6095. var scope = this;
  6096. // todo: unify load API to for easier SceneLoader use
  6097. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  6098. this.onLoadStart();
  6099. this.loadAjaxJSON( this, url, callback, texturePath );
  6100. };
  6101. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  6102. var xhr = new XMLHttpRequest();
  6103. var length = 0;
  6104. xhr.onreadystatechange = function () {
  6105. if ( xhr.readyState === xhr.DONE ) {
  6106. if ( xhr.status === 200 || xhr.status === 0 ) {
  6107. if ( xhr.responseText ) {
  6108. var json = JSON.parse( xhr.responseText );
  6109. var result = context.parse( json, texturePath );
  6110. callback( result.geometry, result.materials );
  6111. } else {
  6112. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  6113. }
  6114. // in context of more complex asset initialization
  6115. // do not block on single failed file
  6116. // maybe should go even one more level up
  6117. context.onLoadComplete();
  6118. } else {
  6119. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6120. }
  6121. } else if ( xhr.readyState === xhr.LOADING ) {
  6122. if ( callbackProgress ) {
  6123. if ( length === 0 ) {
  6124. length = xhr.getResponseHeader( "Content-Length" );
  6125. }
  6126. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6127. }
  6128. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  6129. if ( callbackProgress !== undefined ) {
  6130. length = xhr.getResponseHeader( "Content-Length" );
  6131. }
  6132. }
  6133. };
  6134. xhr.open( "GET", url, true );
  6135. xhr.withCredentials = this.withCredentials;
  6136. xhr.send( null );
  6137. };
  6138. THREE.JSONLoader.prototype.parse = function ( json, texturePath ) {
  6139. var scope = this,
  6140. geometry = new THREE.Geometry(),
  6141. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  6142. parseModel( scale );
  6143. parseSkin();
  6144. parseMorphing( scale );
  6145. geometry.computeCentroids();
  6146. geometry.computeFaceNormals();
  6147. function parseModel( scale ) {
  6148. function isBitSet( value, position ) {
  6149. return value & ( 1 << position );
  6150. }
  6151. var i, j, fi,
  6152. offset, zLength, nVertices,
  6153. colorIndex, normalIndex, uvIndex, materialIndex,
  6154. type,
  6155. isQuad,
  6156. hasMaterial,
  6157. hasFaceUv, hasFaceVertexUv,
  6158. hasFaceNormal, hasFaceVertexNormal,
  6159. hasFaceColor, hasFaceVertexColor,
  6160. vertex, face, color, normal,
  6161. uvLayer, uvs, u, v,
  6162. faces = json.faces,
  6163. vertices = json.vertices,
  6164. normals = json.normals,
  6165. colors = json.colors,
  6166. nUvLayers = 0;
  6167. // disregard empty arrays
  6168. for ( i = 0; i < json.uvs.length; i++ ) {
  6169. if ( json.uvs[ i ].length ) nUvLayers ++;
  6170. }
  6171. for ( i = 0; i < nUvLayers; i++ ) {
  6172. geometry.faceUvs[ i ] = [];
  6173. geometry.faceVertexUvs[ i ] = [];
  6174. }
  6175. offset = 0;
  6176. zLength = vertices.length;
  6177. while ( offset < zLength ) {
  6178. vertex = new THREE.Vector3();
  6179. vertex.x = vertices[ offset ++ ] * scale;
  6180. vertex.y = vertices[ offset ++ ] * scale;
  6181. vertex.z = vertices[ offset ++ ] * scale;
  6182. geometry.vertices.push( vertex );
  6183. }
  6184. offset = 0;
  6185. zLength = faces.length;
  6186. while ( offset < zLength ) {
  6187. type = faces[ offset ++ ];
  6188. isQuad = isBitSet( type, 0 );
  6189. hasMaterial = isBitSet( type, 1 );
  6190. hasFaceUv = isBitSet( type, 2 );
  6191. hasFaceVertexUv = isBitSet( type, 3 );
  6192. hasFaceNormal = isBitSet( type, 4 );
  6193. hasFaceVertexNormal = isBitSet( type, 5 );
  6194. hasFaceColor = isBitSet( type, 6 );
  6195. hasFaceVertexColor = isBitSet( type, 7 );
  6196. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  6197. if ( isQuad ) {
  6198. face = new THREE.Face4();
  6199. face.a = faces[ offset ++ ];
  6200. face.b = faces[ offset ++ ];
  6201. face.c = faces[ offset ++ ];
  6202. face.d = faces[ offset ++ ];
  6203. nVertices = 4;
  6204. } else {
  6205. face = new THREE.Face3();
  6206. face.a = faces[ offset ++ ];
  6207. face.b = faces[ offset ++ ];
  6208. face.c = faces[ offset ++ ];
  6209. nVertices = 3;
  6210. }
  6211. if ( hasMaterial ) {
  6212. materialIndex = faces[ offset ++ ];
  6213. face.materialIndex = materialIndex;
  6214. }
  6215. // to get face <=> uv index correspondence
  6216. fi = geometry.faces.length;
  6217. if ( hasFaceUv ) {
  6218. for ( i = 0; i < nUvLayers; i++ ) {
  6219. uvLayer = json.uvs[ i ];
  6220. uvIndex = faces[ offset ++ ];
  6221. u = uvLayer[ uvIndex * 2 ];
  6222. v = uvLayer[ uvIndex * 2 + 1 ];
  6223. geometry.faceUvs[ i ][ fi ] = new THREE.Vector2( u, v );
  6224. }
  6225. }
  6226. if ( hasFaceVertexUv ) {
  6227. for ( i = 0; i < nUvLayers; i++ ) {
  6228. uvLayer = json.uvs[ i ];
  6229. uvs = [];
  6230. for ( j = 0; j < nVertices; j ++ ) {
  6231. uvIndex = faces[ offset ++ ];
  6232. u = uvLayer[ uvIndex * 2 ];
  6233. v = uvLayer[ uvIndex * 2 + 1 ];
  6234. uvs[ j ] = new THREE.Vector2( u, v );
  6235. }
  6236. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  6237. }
  6238. }
  6239. if ( hasFaceNormal ) {
  6240. normalIndex = faces[ offset ++ ] * 3;
  6241. normal = new THREE.Vector3();
  6242. normal.x = normals[ normalIndex ++ ];
  6243. normal.y = normals[ normalIndex ++ ];
  6244. normal.z = normals[ normalIndex ];
  6245. face.normal = normal;
  6246. }
  6247. if ( hasFaceVertexNormal ) {
  6248. for ( i = 0; i < nVertices; i++ ) {
  6249. normalIndex = faces[ offset ++ ] * 3;
  6250. normal = new THREE.Vector3();
  6251. normal.x = normals[ normalIndex ++ ];
  6252. normal.y = normals[ normalIndex ++ ];
  6253. normal.z = normals[ normalIndex ];
  6254. face.vertexNormals.push( normal );
  6255. }
  6256. }
  6257. if ( hasFaceColor ) {
  6258. colorIndex = faces[ offset ++ ];
  6259. color = new THREE.Color( colors[ colorIndex ] );
  6260. face.color = color;
  6261. }
  6262. if ( hasFaceVertexColor ) {
  6263. for ( i = 0; i < nVertices; i++ ) {
  6264. colorIndex = faces[ offset ++ ];
  6265. color = new THREE.Color( colors[ colorIndex ] );
  6266. face.vertexColors.push( color );
  6267. }
  6268. }
  6269. geometry.faces.push( face );
  6270. }
  6271. };
  6272. function parseSkin() {
  6273. var i, l, x, y, z, w, a, b, c, d;
  6274. if ( json.skinWeights ) {
  6275. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  6276. x = json.skinWeights[ i ];
  6277. y = json.skinWeights[ i + 1 ];
  6278. z = 0;
  6279. w = 0;
  6280. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  6281. }
  6282. }
  6283. if ( json.skinIndices ) {
  6284. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  6285. a = json.skinIndices[ i ];
  6286. b = json.skinIndices[ i + 1 ];
  6287. c = 0;
  6288. d = 0;
  6289. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  6290. }
  6291. }
  6292. geometry.bones = json.bones;
  6293. geometry.animation = json.animation;
  6294. };
  6295. function parseMorphing( scale ) {
  6296. if ( json.morphTargets !== undefined ) {
  6297. var i, l, v, vl, dstVertices, srcVertices;
  6298. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  6299. geometry.morphTargets[ i ] = {};
  6300. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  6301. geometry.morphTargets[ i ].vertices = [];
  6302. dstVertices = geometry.morphTargets[ i ].vertices;
  6303. srcVertices = json.morphTargets [ i ].vertices;
  6304. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  6305. var vertex = new THREE.Vector3();
  6306. vertex.x = srcVertices[ v ] * scale;
  6307. vertex.y = srcVertices[ v + 1 ] * scale;
  6308. vertex.z = srcVertices[ v + 2 ] * scale;
  6309. dstVertices.push( vertex );
  6310. }
  6311. }
  6312. }
  6313. if ( json.morphColors !== undefined ) {
  6314. var i, l, c, cl, dstColors, srcColors, color;
  6315. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  6316. geometry.morphColors[ i ] = {};
  6317. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  6318. geometry.morphColors[ i ].colors = [];
  6319. dstColors = geometry.morphColors[ i ].colors;
  6320. srcColors = json.morphColors [ i ].colors;
  6321. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  6322. color = new THREE.Color( 0xffaa00 );
  6323. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  6324. dstColors.push( color );
  6325. }
  6326. }
  6327. }
  6328. };
  6329. if ( json.materials === undefined ) {
  6330. return { geometry: geometry };
  6331. } else {
  6332. var materials = this.initMaterials( json.materials, texturePath );
  6333. if ( this.needsTangents( materials ) ) {
  6334. geometry.computeTangents();
  6335. }
  6336. return { geometry: geometry, materials: materials };
  6337. }
  6338. };
  6339. /**
  6340. * @author mrdoob / http://mrdoob.com/
  6341. */
  6342. THREE.LoadingManager = function ( onLoad, onProgress, onError ) {
  6343. var scope = this;
  6344. var loaded = 0, total = 0;
  6345. this.onLoad = onLoad;
  6346. this.onProgress = onProgress;
  6347. this.onError = onError;
  6348. this.itemStart = function ( url ) {
  6349. total ++;
  6350. };
  6351. this.itemEnd = function ( url ) {
  6352. loaded ++;
  6353. if ( scope.onProgress !== undefined ) {
  6354. scope.onProgress( url, loaded, total );
  6355. }
  6356. if ( loaded === total && scope.onLoad !== undefined ) {
  6357. scope.onLoad();
  6358. }
  6359. };
  6360. };
  6361. THREE.DefaultLoadingManager = new THREE.LoadingManager();
  6362. /**
  6363. * @author mrdoob / http://mrdoob.com/
  6364. */
  6365. THREE.GeometryLoader = function ( manager ) {
  6366. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6367. };
  6368. THREE.GeometryLoader.prototype = {
  6369. constructor: THREE.GeometryLoader,
  6370. load: function ( url, onLoad, onProgress, onError ) {
  6371. var scope = this;
  6372. var loader = new THREE.XHRLoader();
  6373. loader.setCrossOrigin( this.crossOrigin );
  6374. loader.load( url, function ( text ) {
  6375. onLoad( scope.parse( JSON.parse( text ) ) );
  6376. } );
  6377. },
  6378. setCrossOrigin: function ( value ) {
  6379. this.crossOrigin = value;
  6380. },
  6381. parse: function ( json ) {
  6382. }
  6383. };
  6384. /**
  6385. * @author mrdoob / http://mrdoob.com/
  6386. */
  6387. THREE.MaterialLoader = function ( manager ) {
  6388. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6389. };
  6390. THREE.MaterialLoader.prototype = {
  6391. constructor: THREE.MaterialLoader,
  6392. load: function ( url, onLoad, onProgress, onError ) {
  6393. var scope = this;
  6394. var loader = new THREE.XHRLoader();
  6395. loader.setCrossOrigin( this.crossOrigin );
  6396. loader.load( url, function ( text ) {
  6397. onLoad( scope.parse( JSON.parse( text ) ) );
  6398. } );
  6399. },
  6400. setCrossOrigin: function ( value ) {
  6401. this.crossOrigin = value;
  6402. },
  6403. parse: function ( json ) {
  6404. var material;
  6405. switch ( json.type ) {
  6406. case 'MeshBasicMaterial':
  6407. material = new THREE.MeshBasicMaterial( {
  6408. color: json.color,
  6409. opacity: json.opacity,
  6410. transparent: json.transparent,
  6411. wireframe: json.wireframe
  6412. } );
  6413. break;
  6414. case 'MeshLambertMaterial':
  6415. material = new THREE.MeshLambertMaterial( {
  6416. color: json.color,
  6417. ambient: json.ambient,
  6418. emissive: json.emissive,
  6419. opacity: json.opacity,
  6420. transparent: json.transparent,
  6421. wireframe: json.wireframe
  6422. } );
  6423. break;
  6424. case 'MeshPhongMaterial':
  6425. material = new THREE.MeshPhongMaterial( {
  6426. color: json.color,
  6427. ambient: json.ambient,
  6428. emissive: json.emissive,
  6429. specular: json.specular,
  6430. shininess: json.shininess,
  6431. opacity: json.opacity,
  6432. transparent: json.transparent,
  6433. wireframe: json.wireframe
  6434. } );
  6435. break;
  6436. case 'MeshNormalMaterial':
  6437. material = new THREE.MeshNormalMaterial( {
  6438. opacity: json.opacity,
  6439. transparent: json.transparent,
  6440. wireframe: json.wireframe
  6441. } );
  6442. break;
  6443. case 'MeshDepthMaterial':
  6444. material = new THREE.MeshDepthMaterial( {
  6445. opacity: json.opacity,
  6446. transparent: json.transparent,
  6447. wireframe: json.wireframe
  6448. } );
  6449. break;
  6450. }
  6451. return material;
  6452. }
  6453. };
  6454. /**
  6455. * @author mrdoob / http://mrdoob.com/
  6456. */
  6457. THREE.ObjectLoader = function ( manager ) {
  6458. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  6459. };
  6460. THREE.ObjectLoader.prototype = {
  6461. constructor: THREE.ObjectLoader,
  6462. load: function ( url, onLoad, onProgress, onError ) {
  6463. var scope = this;
  6464. var loader = new THREE.XHRLoader( scope.manager );
  6465. loader.setCrossOrigin( this.crossOrigin );
  6466. loader.load( url, function ( text ) {
  6467. onLoad( scope.parse( JSON.parse( text ) ) );
  6468. } );
  6469. },
  6470. setCrossOrigin: function ( value ) {
  6471. this.crossOrigin = value;
  6472. },
  6473. parse: function ( json ) {
  6474. var geometries = this.parseGeometries( json.geometries );
  6475. var materials = this.parseMaterials( json.materials );
  6476. var object = this.parseObject( json.object, geometries, materials );
  6477. return object;
  6478. },
  6479. parseGeometries: function ( json ) {
  6480. var geometries = {};
  6481. if ( json !== undefined ) {
  6482. var loader = new THREE.JSONLoader();
  6483. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6484. var geometry;
  6485. var data = json[ i ];
  6486. switch ( data.type ) {
  6487. case 'PlaneGeometry':
  6488. geometry = new THREE.PlaneGeometry(
  6489. data.width,
  6490. data.height,
  6491. data.widthSegments,
  6492. data.heightSegments
  6493. );
  6494. break;
  6495. case 'CubeGeometry':
  6496. geometry = new THREE.CubeGeometry(
  6497. data.width,
  6498. data.height,
  6499. data.depth,
  6500. data.widthSegments,
  6501. data.heightSegments,
  6502. data.depthSegments
  6503. );
  6504. break;
  6505. case 'CylinderGeometry':
  6506. geometry = new THREE.CylinderGeometry(
  6507. data.radiusTop,
  6508. data.radiusBottom,
  6509. data.height,
  6510. data.radiusSegments,
  6511. data.heightSegments,
  6512. data.openEnded
  6513. );
  6514. break;
  6515. case 'SphereGeometry':
  6516. geometry = new THREE.SphereGeometry(
  6517. data.radius,
  6518. data.widthSegments,
  6519. data.heightSegments,
  6520. data.phiStart,
  6521. data.phiLength,
  6522. data.thetaStart,
  6523. data.thetaLength
  6524. );
  6525. break;
  6526. case 'IcosahedronGeometry':
  6527. geometry = new THREE.IcosahedronGeometry(
  6528. data.radius,
  6529. data.detail
  6530. );
  6531. break;
  6532. case 'TorusGeometry':
  6533. geometry = new THREE.TorusGeometry(
  6534. data.radius,
  6535. data.tube,
  6536. data.radialSegments,
  6537. data.tubularSegments,
  6538. data.arc
  6539. );
  6540. break;
  6541. case 'TorusKnotGeometry':
  6542. geometry = new THREE.TorusKnotGeometry(
  6543. data.radius,
  6544. data.tube,
  6545. data.radialSegments,
  6546. data.tubularSegments,
  6547. data.p,
  6548. data.q,
  6549. data.heightScale
  6550. );
  6551. break;
  6552. case 'Geometry':
  6553. geometry = loader.parse( data.data ).geometry;
  6554. break;
  6555. }
  6556. if ( data.id !== undefined ) geometry.id = data.id;
  6557. if ( data.name !== undefined ) geometry.name = data.name;
  6558. geometries[ data.id ] = geometry;
  6559. }
  6560. }
  6561. return geometries;
  6562. },
  6563. parseMaterials: function ( json ) {
  6564. var materials = {};
  6565. if ( json !== undefined ) {
  6566. var loader = new THREE.MaterialLoader();
  6567. for ( var i = 0, l = json.length; i < l; i ++ ) {
  6568. var data = json[ i ];
  6569. var material = loader.parse( data );
  6570. if ( data.id !== undefined ) material.id = data.id;
  6571. if ( data.name !== undefined ) material.name = data.name;
  6572. materials[ data.id ] = material;
  6573. }
  6574. }
  6575. return materials;
  6576. },
  6577. parseObject: function () {
  6578. var matrix = new THREE.Matrix4();
  6579. return function ( data, geometries, materials ) {
  6580. var object;
  6581. switch ( data.type ) {
  6582. case 'Scene':
  6583. object = new THREE.Scene();
  6584. break;
  6585. case 'PerspectiveCamera':
  6586. object = new THREE.PerspectiveCamera( data.fov, data.aspect, data.near, data.far );
  6587. break;
  6588. case 'OrthographicCamera':
  6589. object = new THREE.OrthographicCamera( data.left, data.right, data.top, data.bottom, data.near, data.far );
  6590. break;
  6591. case 'AmbientLight':
  6592. object = new THREE.AmbientLight( data.color );
  6593. break;
  6594. case 'DirectionalLight':
  6595. object = new THREE.DirectionalLight( data.color, data.intensity );
  6596. break;
  6597. case 'PointLight':
  6598. object = new THREE.PointLight( data.color, data.intensity, data.distance );
  6599. break;
  6600. case 'SpotLight':
  6601. object = new THREE.SpotLight( data.color, data.intensity, data.distance, data.angle, data.exponent );
  6602. break;
  6603. case 'HemisphereLight':
  6604. object = new THREE.HemisphereLight( data.color, data.groundColor, data.intensity );
  6605. break;
  6606. case 'Mesh':
  6607. object = new THREE.Mesh( geometries[ data.geometry ], materials[ data.material ] );
  6608. break;
  6609. default:
  6610. object = new THREE.Object3D();
  6611. }
  6612. if ( data.matrix !== undefined ) {
  6613. matrix.fromArray( data.matrix );
  6614. matrix.decompose( object.position, object.quaternion, object.scale );
  6615. } else {
  6616. if ( data.position !== undefined ) object.position.fromArray( data.position );
  6617. if ( data.rotation !== undefined ) object.rotation.fromArray( data.rotation );
  6618. if ( data.scale !== undefined ) object.scale.fromArray( data.scale );
  6619. }
  6620. if ( data.id !== undefined ) object.id = data.id;
  6621. if ( data.name !== undefined ) object.name = data.name;
  6622. if ( data.visible !== undefined ) object.visible = data.visible;
  6623. if ( data.userData !== undefined ) object.userData = data.userData;
  6624. if ( data.children !== undefined ) {
  6625. for ( var child in data.children ) {
  6626. object.add( this.parseObject( data.children[ child ], geometries, materials ) );
  6627. }
  6628. }
  6629. return object;
  6630. }
  6631. }()
  6632. };
  6633. /**
  6634. * @author alteredq / http://alteredqualia.com/
  6635. */
  6636. THREE.SceneLoader = function () {
  6637. this.onLoadStart = function () {};
  6638. this.onLoadProgress = function() {};
  6639. this.onLoadComplete = function () {};
  6640. this.callbackSync = function () {};
  6641. this.callbackProgress = function () {};
  6642. this.geometryHandlers = {};
  6643. this.hierarchyHandlers = {};
  6644. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  6645. };
  6646. THREE.SceneLoader.prototype = {
  6647. constructor: THREE.SceneLoader,
  6648. load: function ( url, onLoad, onProgress, onError ) {
  6649. var scope = this;
  6650. var loader = new THREE.XHRLoader( scope.manager );
  6651. loader.setCrossOrigin( this.crossOrigin );
  6652. loader.load( url, function ( text ) {
  6653. scope.parse( JSON.parse( text ), onLoad, url );
  6654. } );
  6655. },
  6656. setCrossOrigin: function ( value ) {
  6657. this.crossOrigin = value;
  6658. },
  6659. addGeometryHandler: function ( typeID, loaderClass ) {
  6660. this.geometryHandlers[ typeID ] = { "loaderClass": loaderClass };
  6661. },
  6662. addHierarchyHandler: function ( typeID, loaderClass ) {
  6663. this.hierarchyHandlers[ typeID ] = { "loaderClass": loaderClass };
  6664. },
  6665. parse: function ( json, callbackFinished, url ) {
  6666. var scope = this;
  6667. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  6668. var geometry, material, camera, fog,
  6669. texture, images, color,
  6670. light, hex, intensity,
  6671. counter_models, counter_textures,
  6672. total_models, total_textures,
  6673. result;
  6674. var target_array = [];
  6675. var data = json;
  6676. // async geometry loaders
  6677. for ( var typeID in this.geometryHandlers ) {
  6678. var loaderClass = this.geometryHandlers[ typeID ][ "loaderClass" ];
  6679. this.geometryHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6680. }
  6681. // async hierachy loaders
  6682. for ( var typeID in this.hierarchyHandlers ) {
  6683. var loaderClass = this.hierarchyHandlers[ typeID ][ "loaderClass" ];
  6684. this.hierarchyHandlers[ typeID ][ "loaderObject" ] = new loaderClass();
  6685. }
  6686. counter_models = 0;
  6687. counter_textures = 0;
  6688. result = {
  6689. scene: new THREE.Scene(),
  6690. geometries: {},
  6691. face_materials: {},
  6692. materials: {},
  6693. textures: {},
  6694. objects: {},
  6695. cameras: {},
  6696. lights: {},
  6697. fogs: {},
  6698. empties: {},
  6699. groups: {}
  6700. };
  6701. if ( data.transform ) {
  6702. var position = data.transform.position,
  6703. rotation = data.transform.rotation,
  6704. scale = data.transform.scale;
  6705. if ( position ) {
  6706. result.scene.position.fromArray( position );
  6707. }
  6708. if ( rotation ) {
  6709. result.scene.rotation.fromArray( rotation );
  6710. }
  6711. if ( scale ) {
  6712. result.scene.scale.fromArray( scale );
  6713. }
  6714. if ( position || rotation || scale ) {
  6715. result.scene.updateMatrix();
  6716. result.scene.updateMatrixWorld();
  6717. }
  6718. }
  6719. function get_url( source_url, url_type ) {
  6720. if ( url_type == "relativeToHTML" ) {
  6721. return source_url;
  6722. } else {
  6723. return urlBase + "/" + source_url;
  6724. }
  6725. };
  6726. // toplevel loader function, delegates to handle_children
  6727. function handle_objects() {
  6728. handle_children( result.scene, data.objects );
  6729. }
  6730. // handle all the children from the loaded json and attach them to given parent
  6731. function handle_children( parent, children ) {
  6732. var mat, dst, pos, rot, scl, quat;
  6733. for ( var objID in children ) {
  6734. // check by id if child has already been handled,
  6735. // if not, create new object
  6736. var object = result.objects[ objID ];
  6737. var objJSON = children[ objID ];
  6738. if ( object === undefined ) {
  6739. // meshes
  6740. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  6741. if ( objJSON.loading === undefined ) {
  6742. var reservedTypes = {
  6743. "type": 1, "url": 1, "material": 1,
  6744. "position": 1, "rotation": 1, "scale" : 1,
  6745. "visible": 1, "children": 1, "userData": 1,
  6746. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1
  6747. };
  6748. var loaderParameters = {};
  6749. for ( var parType in objJSON ) {
  6750. if ( ! ( parType in reservedTypes ) ) {
  6751. loaderParameters[ parType ] = objJSON[ parType ];
  6752. }
  6753. }
  6754. material = result.materials[ objJSON.material ];
  6755. objJSON.loading = true;
  6756. var loader = scope.hierarchyHandlers[ objJSON.type ][ "loaderObject" ];
  6757. // ColladaLoader
  6758. if ( loader.options ) {
  6759. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  6760. // UTF8Loader
  6761. // OBJLoader
  6762. } else {
  6763. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  6764. }
  6765. }
  6766. } else if ( objJSON.geometry !== undefined ) {
  6767. geometry = result.geometries[ objJSON.geometry ];
  6768. // geometry already loaded
  6769. if ( geometry ) {
  6770. var needsTangents = false;
  6771. material = result.materials[ objJSON.material ];
  6772. needsTangents = material instanceof THREE.ShaderMaterial;
  6773. pos = objJSON.position;
  6774. rot = objJSON.rotation;
  6775. scl = objJSON.scale;
  6776. mat = objJSON.matrix;
  6777. quat = objJSON.quaternion;
  6778. // use materials from the model file
  6779. // if there is no material specified in the object
  6780. if ( ! objJSON.material ) {
  6781. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6782. }
  6783. // use materials from the model file
  6784. // if there is just empty face material
  6785. // (must create new material as each model has its own face material)
  6786. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6787. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6788. }
  6789. if ( material instanceof THREE.MeshFaceMaterial ) {
  6790. for ( var i = 0; i < material.materials.length; i ++ ) {
  6791. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6792. }
  6793. }
  6794. if ( needsTangents ) {
  6795. geometry.computeTangents();
  6796. }
  6797. if ( objJSON.skin ) {
  6798. object = new THREE.SkinnedMesh( geometry, material );
  6799. } else if ( objJSON.morph ) {
  6800. object = new THREE.MorphAnimMesh( geometry, material );
  6801. if ( objJSON.duration !== undefined ) {
  6802. object.duration = objJSON.duration;
  6803. }
  6804. if ( objJSON.time !== undefined ) {
  6805. object.time = objJSON.time;
  6806. }
  6807. if ( objJSON.mirroredLoop !== undefined ) {
  6808. object.mirroredLoop = objJSON.mirroredLoop;
  6809. }
  6810. if ( material.morphNormals ) {
  6811. geometry.computeMorphNormals();
  6812. }
  6813. } else {
  6814. object = new THREE.Mesh( geometry, material );
  6815. }
  6816. object.name = objID;
  6817. if ( mat ) {
  6818. object.matrixAutoUpdate = false;
  6819. object.matrix.set(
  6820. mat[0], mat[1], mat[2], mat[3],
  6821. mat[4], mat[5], mat[6], mat[7],
  6822. mat[8], mat[9], mat[10], mat[11],
  6823. mat[12], mat[13], mat[14], mat[15]
  6824. );
  6825. } else {
  6826. object.position.fromArray( pos );
  6827. if ( quat ) {
  6828. object.quaternion.fromArray( quat );
  6829. } else {
  6830. object.rotation.fromArray( rot );
  6831. }
  6832. object.scale.fromArray( scl );
  6833. }
  6834. object.visible = objJSON.visible;
  6835. object.castShadow = objJSON.castShadow;
  6836. object.receiveShadow = objJSON.receiveShadow;
  6837. parent.add( object );
  6838. result.objects[ objID ] = object;
  6839. }
  6840. // lights
  6841. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6842. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6843. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6844. if ( objJSON.type === "DirectionalLight" ) {
  6845. pos = objJSON.direction;
  6846. light = new THREE.DirectionalLight( hex, intensity );
  6847. light.position.fromArray( pos );
  6848. if ( objJSON.target ) {
  6849. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6850. // kill existing default target
  6851. // otherwise it gets added to scene when parent gets added
  6852. light.target = null;
  6853. }
  6854. } else if ( objJSON.type === "PointLight" ) {
  6855. pos = objJSON.position;
  6856. dst = objJSON.distance;
  6857. light = new THREE.PointLight( hex, intensity, dst );
  6858. light.position.fromArray( pos );
  6859. } else if ( objJSON.type === "AmbientLight" ) {
  6860. light = new THREE.AmbientLight( hex );
  6861. }
  6862. parent.add( light );
  6863. light.name = objID;
  6864. result.lights[ objID ] = light;
  6865. result.objects[ objID ] = light;
  6866. // cameras
  6867. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6868. pos = objJSON.position;
  6869. rot = objJSON.rotation;
  6870. quat = objJSON.quaternion;
  6871. if ( objJSON.type === "PerspectiveCamera" ) {
  6872. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6873. } else if ( objJSON.type === "OrthographicCamera" ) {
  6874. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6875. }
  6876. camera.name = objID;
  6877. camera.position.fromArray( pos );
  6878. if ( quat !== undefined ) {
  6879. camera.quaternion.fromArray( quat );
  6880. } else if ( rot !== undefined ) {
  6881. camera.rotation.fromArray( rot );
  6882. }
  6883. parent.add( camera );
  6884. result.cameras[ objID ] = camera;
  6885. result.objects[ objID ] = camera;
  6886. // pure Object3D
  6887. } else {
  6888. pos = objJSON.position;
  6889. rot = objJSON.rotation;
  6890. scl = objJSON.scale;
  6891. quat = objJSON.quaternion;
  6892. object = new THREE.Object3D();
  6893. object.name = objID;
  6894. object.position.fromArray( pos );
  6895. if ( quat ) {
  6896. object.quaternion.fromArray( quat );
  6897. } else {
  6898. object.rotation.fromArray( rot );
  6899. }
  6900. object.scale.fromArray( scl );
  6901. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6902. parent.add( object );
  6903. result.objects[ objID ] = object;
  6904. result.empties[ objID ] = object;
  6905. }
  6906. if ( object ) {
  6907. if ( objJSON.userData !== undefined ) {
  6908. for ( var key in objJSON.userData ) {
  6909. var value = objJSON.userData[ key ];
  6910. object.userData[ key ] = value;
  6911. }
  6912. }
  6913. if ( objJSON.groups !== undefined ) {
  6914. for ( var i = 0; i < objJSON.groups.length; i ++ ) {
  6915. var groupID = objJSON.groups[ i ];
  6916. if ( result.groups[ groupID ] === undefined ) {
  6917. result.groups[ groupID ] = [];
  6918. }
  6919. result.groups[ groupID ].push( objID );
  6920. }
  6921. }
  6922. }
  6923. }
  6924. if ( object !== undefined && objJSON.children !== undefined ) {
  6925. handle_children( object, objJSON.children );
  6926. }
  6927. }
  6928. };
  6929. function handle_mesh( geo, mat, id ) {
  6930. result.geometries[ id ] = geo;
  6931. result.face_materials[ id ] = mat;
  6932. handle_objects();
  6933. };
  6934. function handle_hierarchy( node, id, parent, material, obj ) {
  6935. var p = obj.position;
  6936. var r = obj.rotation;
  6937. var q = obj.quaternion;
  6938. var s = obj.scale;
  6939. node.position.fromArray( p );
  6940. if ( q ) {
  6941. node.quaternion.fromArray( q );
  6942. } else {
  6943. node.rotation.fromArray( r );
  6944. }
  6945. node.scale.fromArray( s );
  6946. // override children materials
  6947. // if object material was specified in JSON explicitly
  6948. if ( material ) {
  6949. node.traverse( function ( child ) {
  6950. child.material = material;
  6951. } );
  6952. }
  6953. // override children visibility
  6954. // with root node visibility as specified in JSON
  6955. var visible = ( obj.visible !== undefined ) ? obj.visible : true;
  6956. node.traverse( function ( child ) {
  6957. child.visible = visible;
  6958. } );
  6959. parent.add( node );
  6960. node.name = id;
  6961. result.objects[ id ] = node;
  6962. handle_objects();
  6963. };
  6964. function create_callback_geometry( id ) {
  6965. return function ( geo, mat ) {
  6966. geo.name = id;
  6967. handle_mesh( geo, mat, id );
  6968. counter_models -= 1;
  6969. scope.onLoadComplete();
  6970. async_callback_gate();
  6971. }
  6972. };
  6973. function create_callback_hierachy( id, parent, material, obj ) {
  6974. return function ( event ) {
  6975. var result;
  6976. // loaders which use EventDispatcher
  6977. if ( event.content ) {
  6978. result = event.content;
  6979. // ColladaLoader
  6980. } else if ( event.dae ) {
  6981. result = event.scene;
  6982. // UTF8Loader
  6983. } else {
  6984. result = event;
  6985. }
  6986. handle_hierarchy( result, id, parent, material, obj );
  6987. counter_models -= 1;
  6988. scope.onLoadComplete();
  6989. async_callback_gate();
  6990. }
  6991. };
  6992. function create_callback_embed( id ) {
  6993. return function ( geo, mat ) {
  6994. geo.name = id;
  6995. result.geometries[ id ] = geo;
  6996. result.face_materials[ id ] = mat;
  6997. }
  6998. };
  6999. function async_callback_gate() {
  7000. var progress = {
  7001. totalModels : total_models,
  7002. totalTextures : total_textures,
  7003. loadedModels : total_models - counter_models,
  7004. loadedTextures : total_textures - counter_textures
  7005. };
  7006. scope.callbackProgress( progress, result );
  7007. scope.onLoadProgress();
  7008. if ( counter_models === 0 && counter_textures === 0 ) {
  7009. finalize();
  7010. callbackFinished( result );
  7011. }
  7012. };
  7013. function finalize() {
  7014. // take care of targets which could be asynchronously loaded objects
  7015. for ( var i = 0; i < target_array.length; i ++ ) {
  7016. var ta = target_array[ i ];
  7017. var target = result.objects[ ta.targetName ];
  7018. if ( target ) {
  7019. ta.object.target = target;
  7020. } else {
  7021. // if there was error and target of specified name doesn't exist in the scene file
  7022. // create instead dummy target
  7023. // (target must be added to scene explicitly as parent is already added)
  7024. ta.object.target = new THREE.Object3D();
  7025. result.scene.add( ta.object.target );
  7026. }
  7027. ta.object.target.userData.targetInverse = ta.object;
  7028. }
  7029. };
  7030. var callbackTexture = function ( count ) {
  7031. counter_textures -= count;
  7032. async_callback_gate();
  7033. scope.onLoadComplete();
  7034. };
  7035. // must use this instead of just directly calling callbackTexture
  7036. // because of closure in the calling context loop
  7037. var generateTextureCallback = function ( count ) {
  7038. return function () {
  7039. callbackTexture( count );
  7040. };
  7041. };
  7042. function traverse_json_hierarchy( objJSON, callback ) {
  7043. callback( objJSON );
  7044. if ( objJSON.children !== undefined ) {
  7045. for ( var objChildID in objJSON.children ) {
  7046. traverse_json_hierarchy( objJSON.children[ objChildID ], callback );
  7047. }
  7048. }
  7049. };
  7050. // first go synchronous elements
  7051. // fogs
  7052. var fogID, fogJSON;
  7053. for ( fogID in data.fogs ) {
  7054. fogJSON = data.fogs[ fogID ];
  7055. if ( fogJSON.type === "linear" ) {
  7056. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  7057. } else if ( fogJSON.type === "exp2" ) {
  7058. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  7059. }
  7060. color = fogJSON.color;
  7061. fog.color.setRGB( color[0], color[1], color[2] );
  7062. result.fogs[ fogID ] = fog;
  7063. }
  7064. // now come potentially asynchronous elements
  7065. // geometries
  7066. // count how many geometries will be loaded asynchronously
  7067. var geoID, geoJSON;
  7068. for ( geoID in data.geometries ) {
  7069. geoJSON = data.geometries[ geoID ];
  7070. if ( geoJSON.type in this.geometryHandlers ) {
  7071. counter_models += 1;
  7072. scope.onLoadStart();
  7073. }
  7074. }
  7075. // count how many hierarchies will be loaded asynchronously
  7076. for ( var objID in data.objects ) {
  7077. traverse_json_hierarchy( data.objects[ objID ], function ( objJSON ) {
  7078. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlers ) ) {
  7079. counter_models += 1;
  7080. scope.onLoadStart();
  7081. }
  7082. });
  7083. }
  7084. total_models = counter_models;
  7085. for ( geoID in data.geometries ) {
  7086. geoJSON = data.geometries[ geoID ];
  7087. if ( geoJSON.type === "cube" ) {
  7088. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  7089. geometry.name = geoID;
  7090. result.geometries[ geoID ] = geometry;
  7091. } else if ( geoJSON.type === "plane" ) {
  7092. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  7093. geometry.name = geoID;
  7094. result.geometries[ geoID ] = geometry;
  7095. } else if ( geoJSON.type === "sphere" ) {
  7096. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  7097. geometry.name = geoID;
  7098. result.geometries[ geoID ] = geometry;
  7099. } else if ( geoJSON.type === "cylinder" ) {
  7100. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  7101. geometry.name = geoID;
  7102. result.geometries[ geoID ] = geometry;
  7103. } else if ( geoJSON.type === "torus" ) {
  7104. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  7105. geometry.name = geoID;
  7106. result.geometries[ geoID ] = geometry;
  7107. } else if ( geoJSON.type === "icosahedron" ) {
  7108. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  7109. geometry.name = geoID;
  7110. result.geometries[ geoID ] = geometry;
  7111. } else if ( geoJSON.type in this.geometryHandlers ) {
  7112. var loaderParameters = {};
  7113. for ( var parType in geoJSON ) {
  7114. if ( parType !== "type" && parType !== "url" ) {
  7115. loaderParameters[ parType ] = geoJSON[ parType ];
  7116. }
  7117. }
  7118. var loader = this.geometryHandlers[ geoJSON.type ][ "loaderObject" ];
  7119. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  7120. } else if ( geoJSON.type === "embedded" ) {
  7121. var modelJson = data.embeds[ geoJSON.id ],
  7122. texture_path = "";
  7123. // pass metadata along to jsonLoader so it knows the format version
  7124. modelJson.metadata = data.metadata;
  7125. if ( modelJson ) {
  7126. var jsonLoader = this.geometryHandlers[ "ascii" ][ "loaderObject" ];
  7127. var model = jsonLoader.parse( modelJson, texture_path );
  7128. create_callback_embed( geoID )( model.geometry, model.materials );
  7129. }
  7130. }
  7131. }
  7132. // textures
  7133. // count how many textures will be loaded asynchronously
  7134. var textureID, textureJSON;
  7135. for ( textureID in data.textures ) {
  7136. textureJSON = data.textures[ textureID ];
  7137. if ( textureJSON.url instanceof Array ) {
  7138. counter_textures += textureJSON.url.length;
  7139. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  7140. scope.onLoadStart();
  7141. }
  7142. } else {
  7143. counter_textures += 1;
  7144. scope.onLoadStart();
  7145. }
  7146. }
  7147. total_textures = counter_textures;
  7148. for ( textureID in data.textures ) {
  7149. textureJSON = data.textures[ textureID ];
  7150. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  7151. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  7152. }
  7153. if ( textureJSON.url instanceof Array ) {
  7154. var count = textureJSON.url.length;
  7155. var url_array = [];
  7156. for( var i = 0; i < count; i ++ ) {
  7157. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  7158. }
  7159. var isCompressed = /\.dds$/i.test( url_array[ 0 ] );
  7160. if ( isCompressed ) {
  7161. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7162. } else {
  7163. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  7164. }
  7165. } else {
  7166. var isCompressed = /\.dds$/i.test( textureJSON.url );
  7167. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  7168. var textureCallback = generateTextureCallback( 1 );
  7169. if ( isCompressed ) {
  7170. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  7171. } else {
  7172. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  7173. }
  7174. if ( THREE[ textureJSON.minFilter ] !== undefined )
  7175. texture.minFilter = THREE[ textureJSON.minFilter ];
  7176. if ( THREE[ textureJSON.magFilter ] !== undefined )
  7177. texture.magFilter = THREE[ textureJSON.magFilter ];
  7178. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  7179. if ( textureJSON.repeat ) {
  7180. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  7181. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  7182. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  7183. }
  7184. if ( textureJSON.offset ) {
  7185. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  7186. }
  7187. // handle wrap after repeat so that default repeat can be overriden
  7188. if ( textureJSON.wrap ) {
  7189. var wrapMap = {
  7190. "repeat": THREE.RepeatWrapping,
  7191. "mirror": THREE.MirroredRepeatWrapping
  7192. }
  7193. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  7194. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  7195. }
  7196. }
  7197. result.textures[ textureID ] = texture;
  7198. }
  7199. // materials
  7200. var matID, matJSON;
  7201. var parID;
  7202. for ( matID in data.materials ) {
  7203. matJSON = data.materials[ matID ];
  7204. for ( parID in matJSON.parameters ) {
  7205. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  7206. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  7207. } else if ( parID === "shading" ) {
  7208. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  7209. } else if ( parID === "side" ) {
  7210. if ( matJSON.parameters[ parID ] == "double" ) {
  7211. matJSON.parameters[ parID ] = THREE.DoubleSide;
  7212. } else if ( matJSON.parameters[ parID ] == "back" ) {
  7213. matJSON.parameters[ parID ] = THREE.BackSide;
  7214. } else {
  7215. matJSON.parameters[ parID ] = THREE.FrontSide;
  7216. }
  7217. } else if ( parID === "blending" ) {
  7218. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  7219. } else if ( parID === "combine" ) {
  7220. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.MultiplyOperation;
  7221. } else if ( parID === "vertexColors" ) {
  7222. if ( matJSON.parameters[ parID ] == "face" ) {
  7223. matJSON.parameters[ parID ] = THREE.FaceColors;
  7224. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  7225. } else if ( matJSON.parameters[ parID ] ) {
  7226. matJSON.parameters[ parID ] = THREE.VertexColors;
  7227. }
  7228. } else if ( parID === "wrapRGB" ) {
  7229. var v3 = matJSON.parameters[ parID ];
  7230. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  7231. }
  7232. }
  7233. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  7234. matJSON.parameters.transparent = true;
  7235. }
  7236. if ( matJSON.parameters.normalMap ) {
  7237. var shader = THREE.ShaderLib[ "normalmap" ];
  7238. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  7239. var diffuse = matJSON.parameters.color;
  7240. var specular = matJSON.parameters.specular;
  7241. var ambient = matJSON.parameters.ambient;
  7242. var shininess = matJSON.parameters.shininess;
  7243. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  7244. if ( matJSON.parameters.normalScale ) {
  7245. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  7246. }
  7247. if ( matJSON.parameters.map ) {
  7248. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  7249. uniforms[ "enableDiffuse" ].value = true;
  7250. }
  7251. if ( matJSON.parameters.envMap ) {
  7252. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  7253. uniforms[ "enableReflection" ].value = true;
  7254. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  7255. }
  7256. if ( matJSON.parameters.lightMap ) {
  7257. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  7258. uniforms[ "enableAO" ].value = true;
  7259. }
  7260. if ( matJSON.parameters.specularMap ) {
  7261. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  7262. uniforms[ "enableSpecular" ].value = true;
  7263. }
  7264. if ( matJSON.parameters.displacementMap ) {
  7265. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  7266. uniforms[ "enableDisplacement" ].value = true;
  7267. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  7268. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  7269. }
  7270. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  7271. uniforms[ "uSpecularColor" ].value.setHex( specular );
  7272. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  7273. uniforms[ "uShininess" ].value = shininess;
  7274. if ( matJSON.parameters.opacity ) {
  7275. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  7276. }
  7277. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  7278. material = new THREE.ShaderMaterial( parameters );
  7279. } else {
  7280. material = new THREE[ matJSON.type ]( matJSON.parameters );
  7281. }
  7282. material.name = matID;
  7283. result.materials[ matID ] = material;
  7284. }
  7285. // second pass through all materials to initialize MeshFaceMaterials
  7286. // that could be referring to other materials out of order
  7287. for ( matID in data.materials ) {
  7288. matJSON = data.materials[ matID ];
  7289. if ( matJSON.parameters.materials ) {
  7290. var materialArray = [];
  7291. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  7292. var label = matJSON.parameters.materials[ i ];
  7293. materialArray.push( result.materials[ label ] );
  7294. }
  7295. result.materials[ matID ].materials = materialArray;
  7296. }
  7297. }
  7298. // objects ( synchronous init of procedural primitives )
  7299. handle_objects();
  7300. // defaults
  7301. if ( result.cameras && data.defaults.camera ) {
  7302. result.currentCamera = result.cameras[ data.defaults.camera ];
  7303. }
  7304. if ( result.fogs && data.defaults.fog ) {
  7305. result.scene.fog = result.fogs[ data.defaults.fog ];
  7306. }
  7307. // synchronous callback
  7308. scope.callbackSync( result );
  7309. // just in case there are no async elements
  7310. async_callback_gate();
  7311. }
  7312. }
  7313. /**
  7314. * @author mrdoob / http://mrdoob.com/
  7315. */
  7316. THREE.TextureLoader = function ( manager ) {
  7317. this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
  7318. };
  7319. THREE.TextureLoader.prototype = {
  7320. constructor: THREE.TextureLoader,
  7321. load: function ( url, onLoad, onProgress, onError ) {
  7322. var scope = this;
  7323. var loader = new THREE.ImageLoader( scope.manager );
  7324. loader.setCrossOrigin( this.crossOrigin );
  7325. loader.load( url, function ( image ) {
  7326. var texture = new THREE.Texture( image );
  7327. texture.needsUpdate = true;
  7328. if ( onLoad !== undefined ) {
  7329. onLoad( texture );
  7330. }
  7331. } );
  7332. },
  7333. setCrossOrigin: function ( value ) {
  7334. this.crossOrigin = value;
  7335. }
  7336. };
  7337. /**
  7338. * @author mrdoob / http://mrdoob.com/
  7339. * @author alteredq / http://alteredqualia.com/
  7340. */
  7341. THREE.Material = function () {
  7342. this.id = THREE.Math.generateUUID();
  7343. this.name = '';
  7344. this.side = THREE.FrontSide;
  7345. this.opacity = 1;
  7346. this.transparent = false;
  7347. this.blending = THREE.NormalBlending;
  7348. this.blendSrc = THREE.SrcAlphaFactor;
  7349. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  7350. this.blendEquation = THREE.AddEquation;
  7351. this.depthTest = true;
  7352. this.depthWrite = true;
  7353. this.polygonOffset = false;
  7354. this.polygonOffsetFactor = 0;
  7355. this.polygonOffsetUnits = 0;
  7356. this.alphaTest = 0;
  7357. this.overdraw = 0; // Overdrawn pixels (typically between 0 and 1) for fixing antialiasing gaps in CanvasRenderer
  7358. this.visible = true;
  7359. this.needsUpdate = true;
  7360. };
  7361. THREE.Material.prototype = {
  7362. constructor: THREE.Material,
  7363. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  7364. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  7365. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  7366. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  7367. setValues: function ( values ) {
  7368. if ( values === undefined ) return;
  7369. for ( var key in values ) {
  7370. var newValue = values[ key ];
  7371. if ( newValue === undefined ) {
  7372. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  7373. continue;
  7374. }
  7375. if ( key in this ) {
  7376. var currentValue = this[ key ];
  7377. if ( currentValue instanceof THREE.Color ) {
  7378. currentValue.set( newValue );
  7379. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  7380. currentValue.copy( newValue );
  7381. } else if ( key == 'overdraw') {
  7382. // ensure overdraw is backwards-compatable with legacy boolean type
  7383. this[ key ] = Number(newValue);
  7384. } else {
  7385. this[ key ] = newValue;
  7386. }
  7387. }
  7388. }
  7389. },
  7390. clone: function ( material ) {
  7391. if ( material === undefined ) material = new THREE.Material();
  7392. material.name = this.name;
  7393. material.side = this.side;
  7394. material.opacity = this.opacity;
  7395. material.transparent = this.transparent;
  7396. material.blending = this.blending;
  7397. material.blendSrc = this.blendSrc;
  7398. material.blendDst = this.blendDst;
  7399. material.blendEquation = this.blendEquation;
  7400. material.depthTest = this.depthTest;
  7401. material.depthWrite = this.depthWrite;
  7402. material.polygonOffset = this.polygonOffset;
  7403. material.polygonOffsetFactor = this.polygonOffsetFactor;
  7404. material.polygonOffsetUnits = this.polygonOffsetUnits;
  7405. material.alphaTest = this.alphaTest;
  7406. material.overdraw = this.overdraw;
  7407. material.visible = this.visible;
  7408. return material;
  7409. },
  7410. dispose: function () {
  7411. this.dispatchEvent( { type: 'dispose' } );
  7412. }
  7413. };
  7414. /**
  7415. * @author mrdoob / http://mrdoob.com/
  7416. * @author alteredq / http://alteredqualia.com/
  7417. *
  7418. * parameters = {
  7419. * color: <hex>,
  7420. * opacity: <float>,
  7421. *
  7422. * blending: THREE.NormalBlending,
  7423. * depthTest: <bool>,
  7424. * depthWrite: <bool>,
  7425. *
  7426. * linewidth: <float>,
  7427. * linecap: "round",
  7428. * linejoin: "round",
  7429. *
  7430. * vertexColors: <bool>
  7431. *
  7432. * fog: <bool>
  7433. * }
  7434. */
  7435. THREE.LineBasicMaterial = function ( parameters ) {
  7436. THREE.Material.call( this );
  7437. this.color = new THREE.Color( 0xffffff );
  7438. this.linewidth = 1;
  7439. this.linecap = 'round';
  7440. this.linejoin = 'round';
  7441. this.vertexColors = false;
  7442. this.fog = true;
  7443. this.setValues( parameters );
  7444. };
  7445. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7446. THREE.LineBasicMaterial.prototype.clone = function () {
  7447. var material = new THREE.LineBasicMaterial();
  7448. THREE.Material.prototype.clone.call( this, material );
  7449. material.color.copy( this.color );
  7450. material.linewidth = this.linewidth;
  7451. material.linecap = this.linecap;
  7452. material.linejoin = this.linejoin;
  7453. material.vertexColors = this.vertexColors;
  7454. material.fog = this.fog;
  7455. return material;
  7456. };
  7457. /**
  7458. * @author alteredq / http://alteredqualia.com/
  7459. *
  7460. * parameters = {
  7461. * color: <hex>,
  7462. * opacity: <float>,
  7463. *
  7464. * blending: THREE.NormalBlending,
  7465. * depthTest: <bool>,
  7466. * depthWrite: <bool>,
  7467. *
  7468. * linewidth: <float>,
  7469. *
  7470. * scale: <float>,
  7471. * dashSize: <float>,
  7472. * gapSize: <float>,
  7473. *
  7474. * vertexColors: <bool>
  7475. *
  7476. * fog: <bool>
  7477. * }
  7478. */
  7479. THREE.LineDashedMaterial = function ( parameters ) {
  7480. THREE.Material.call( this );
  7481. this.color = new THREE.Color( 0xffffff );
  7482. this.linewidth = 1;
  7483. this.scale = 1;
  7484. this.dashSize = 3;
  7485. this.gapSize = 1;
  7486. this.vertexColors = false;
  7487. this.fog = true;
  7488. this.setValues( parameters );
  7489. };
  7490. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  7491. THREE.LineDashedMaterial.prototype.clone = function () {
  7492. var material = new THREE.LineDashedMaterial();
  7493. THREE.Material.prototype.clone.call( this, material );
  7494. material.color.copy( this.color );
  7495. material.linewidth = this.linewidth;
  7496. material.scale = this.scale;
  7497. material.dashSize = this.dashSize;
  7498. material.gapSize = this.gapSize;
  7499. material.vertexColors = this.vertexColors;
  7500. material.fog = this.fog;
  7501. return material;
  7502. };
  7503. /**
  7504. * @author mrdoob / http://mrdoob.com/
  7505. * @author alteredq / http://alteredqualia.com/
  7506. *
  7507. * parameters = {
  7508. * color: <hex>,
  7509. * opacity: <float>,
  7510. * map: new THREE.Texture( <Image> ),
  7511. *
  7512. * lightMap: new THREE.Texture( <Image> ),
  7513. *
  7514. * specularMap: new THREE.Texture( <Image> ),
  7515. *
  7516. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7517. * combine: THREE.Multiply,
  7518. * reflectivity: <float>,
  7519. * refractionRatio: <float>,
  7520. *
  7521. * shading: THREE.SmoothShading,
  7522. * blending: THREE.NormalBlending,
  7523. * depthTest: <bool>,
  7524. * depthWrite: <bool>,
  7525. *
  7526. * wireframe: <boolean>,
  7527. * wireframeLinewidth: <float>,
  7528. *
  7529. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7530. *
  7531. * skinning: <bool>,
  7532. * morphTargets: <bool>,
  7533. *
  7534. * fog: <bool>
  7535. * }
  7536. */
  7537. THREE.MeshBasicMaterial = function ( parameters ) {
  7538. THREE.Material.call( this );
  7539. this.color = new THREE.Color( 0xffffff ); // emissive
  7540. this.map = null;
  7541. this.lightMap = null;
  7542. this.specularMap = null;
  7543. this.envMap = null;
  7544. this.combine = THREE.MultiplyOperation;
  7545. this.reflectivity = 1;
  7546. this.refractionRatio = 0.98;
  7547. this.fog = true;
  7548. this.shading = THREE.SmoothShading;
  7549. this.wireframe = false;
  7550. this.wireframeLinewidth = 1;
  7551. this.wireframeLinecap = 'round';
  7552. this.wireframeLinejoin = 'round';
  7553. this.vertexColors = THREE.NoColors;
  7554. this.skinning = false;
  7555. this.morphTargets = false;
  7556. this.setValues( parameters );
  7557. };
  7558. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7559. THREE.MeshBasicMaterial.prototype.clone = function () {
  7560. var material = new THREE.MeshBasicMaterial();
  7561. THREE.Material.prototype.clone.call( this, material );
  7562. material.color.copy( this.color );
  7563. material.map = this.map;
  7564. material.lightMap = this.lightMap;
  7565. material.specularMap = this.specularMap;
  7566. material.envMap = this.envMap;
  7567. material.combine = this.combine;
  7568. material.reflectivity = this.reflectivity;
  7569. material.refractionRatio = this.refractionRatio;
  7570. material.fog = this.fog;
  7571. material.shading = this.shading;
  7572. material.wireframe = this.wireframe;
  7573. material.wireframeLinewidth = this.wireframeLinewidth;
  7574. material.wireframeLinecap = this.wireframeLinecap;
  7575. material.wireframeLinejoin = this.wireframeLinejoin;
  7576. material.vertexColors = this.vertexColors;
  7577. material.skinning = this.skinning;
  7578. material.morphTargets = this.morphTargets;
  7579. return material;
  7580. };
  7581. /**
  7582. * @author mrdoob / http://mrdoob.com/
  7583. * @author alteredq / http://alteredqualia.com/
  7584. *
  7585. * parameters = {
  7586. * color: <hex>,
  7587. * ambient: <hex>,
  7588. * emissive: <hex>,
  7589. * opacity: <float>,
  7590. *
  7591. * map: new THREE.Texture( <Image> ),
  7592. *
  7593. * lightMap: new THREE.Texture( <Image> ),
  7594. *
  7595. * specularMap: new THREE.Texture( <Image> ),
  7596. *
  7597. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7598. * combine: THREE.Multiply,
  7599. * reflectivity: <float>,
  7600. * refractionRatio: <float>,
  7601. *
  7602. * shading: THREE.SmoothShading,
  7603. * blending: THREE.NormalBlending,
  7604. * depthTest: <bool>,
  7605. * depthWrite: <bool>,
  7606. *
  7607. * wireframe: <boolean>,
  7608. * wireframeLinewidth: <float>,
  7609. *
  7610. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7611. *
  7612. * skinning: <bool>,
  7613. * morphTargets: <bool>,
  7614. * morphNormals: <bool>,
  7615. *
  7616. * fog: <bool>
  7617. * }
  7618. */
  7619. THREE.MeshLambertMaterial = function ( parameters ) {
  7620. THREE.Material.call( this );
  7621. this.color = new THREE.Color( 0xffffff ); // diffuse
  7622. this.ambient = new THREE.Color( 0xffffff );
  7623. this.emissive = new THREE.Color( 0x000000 );
  7624. this.wrapAround = false;
  7625. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7626. this.map = null;
  7627. this.lightMap = null;
  7628. this.specularMap = null;
  7629. this.envMap = null;
  7630. this.combine = THREE.MultiplyOperation;
  7631. this.reflectivity = 1;
  7632. this.refractionRatio = 0.98;
  7633. this.fog = true;
  7634. this.shading = THREE.SmoothShading;
  7635. this.wireframe = false;
  7636. this.wireframeLinewidth = 1;
  7637. this.wireframeLinecap = 'round';
  7638. this.wireframeLinejoin = 'round';
  7639. this.vertexColors = THREE.NoColors;
  7640. this.skinning = false;
  7641. this.morphTargets = false;
  7642. this.morphNormals = false;
  7643. this.setValues( parameters );
  7644. };
  7645. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  7646. THREE.MeshLambertMaterial.prototype.clone = function () {
  7647. var material = new THREE.MeshLambertMaterial();
  7648. THREE.Material.prototype.clone.call( this, material );
  7649. material.color.copy( this.color );
  7650. material.ambient.copy( this.ambient );
  7651. material.emissive.copy( this.emissive );
  7652. material.wrapAround = this.wrapAround;
  7653. material.wrapRGB.copy( this.wrapRGB );
  7654. material.map = this.map;
  7655. material.lightMap = this.lightMap;
  7656. material.specularMap = this.specularMap;
  7657. material.envMap = this.envMap;
  7658. material.combine = this.combine;
  7659. material.reflectivity = this.reflectivity;
  7660. material.refractionRatio = this.refractionRatio;
  7661. material.fog = this.fog;
  7662. material.shading = this.shading;
  7663. material.wireframe = this.wireframe;
  7664. material.wireframeLinewidth = this.wireframeLinewidth;
  7665. material.wireframeLinecap = this.wireframeLinecap;
  7666. material.wireframeLinejoin = this.wireframeLinejoin;
  7667. material.vertexColors = this.vertexColors;
  7668. material.skinning = this.skinning;
  7669. material.morphTargets = this.morphTargets;
  7670. material.morphNormals = this.morphNormals;
  7671. return material;
  7672. };
  7673. /**
  7674. * @author mrdoob / http://mrdoob.com/
  7675. * @author alteredq / http://alteredqualia.com/
  7676. *
  7677. * parameters = {
  7678. * color: <hex>,
  7679. * ambient: <hex>,
  7680. * emissive: <hex>,
  7681. * specular: <hex>,
  7682. * shininess: <float>,
  7683. * opacity: <float>,
  7684. *
  7685. * map: new THREE.Texture( <Image> ),
  7686. *
  7687. * lightMap: new THREE.Texture( <Image> ),
  7688. *
  7689. * bumpMap: new THREE.Texture( <Image> ),
  7690. * bumpScale: <float>,
  7691. *
  7692. * normalMap: new THREE.Texture( <Image> ),
  7693. * normalScale: <Vector2>,
  7694. *
  7695. * specularMap: new THREE.Texture( <Image> ),
  7696. *
  7697. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  7698. * combine: THREE.Multiply,
  7699. * reflectivity: <float>,
  7700. * refractionRatio: <float>,
  7701. *
  7702. * shading: THREE.SmoothShading,
  7703. * blending: THREE.NormalBlending,
  7704. * depthTest: <bool>,
  7705. * depthWrite: <bool>,
  7706. *
  7707. * wireframe: <boolean>,
  7708. * wireframeLinewidth: <float>,
  7709. *
  7710. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7711. *
  7712. * skinning: <bool>,
  7713. * morphTargets: <bool>,
  7714. * morphNormals: <bool>,
  7715. *
  7716. * fog: <bool>
  7717. * }
  7718. */
  7719. THREE.MeshPhongMaterial = function ( parameters ) {
  7720. THREE.Material.call( this );
  7721. this.color = new THREE.Color( 0xffffff ); // diffuse
  7722. this.ambient = new THREE.Color( 0xffffff );
  7723. this.emissive = new THREE.Color( 0x000000 );
  7724. this.specular = new THREE.Color( 0x111111 );
  7725. this.shininess = 30;
  7726. this.metal = false;
  7727. this.perPixel = true;
  7728. this.wrapAround = false;
  7729. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  7730. this.map = null;
  7731. this.lightMap = null;
  7732. this.bumpMap = null;
  7733. this.bumpScale = 1;
  7734. this.normalMap = null;
  7735. this.normalScale = new THREE.Vector2( 1, 1 );
  7736. this.specularMap = null;
  7737. this.envMap = null;
  7738. this.combine = THREE.MultiplyOperation;
  7739. this.reflectivity = 1;
  7740. this.refractionRatio = 0.98;
  7741. this.fog = true;
  7742. this.shading = THREE.SmoothShading;
  7743. this.wireframe = false;
  7744. this.wireframeLinewidth = 1;
  7745. this.wireframeLinecap = 'round';
  7746. this.wireframeLinejoin = 'round';
  7747. this.vertexColors = THREE.NoColors;
  7748. this.skinning = false;
  7749. this.morphTargets = false;
  7750. this.morphNormals = false;
  7751. this.setValues( parameters );
  7752. };
  7753. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  7754. THREE.MeshPhongMaterial.prototype.clone = function () {
  7755. var material = new THREE.MeshPhongMaterial();
  7756. THREE.Material.prototype.clone.call( this, material );
  7757. material.color.copy( this.color );
  7758. material.ambient.copy( this.ambient );
  7759. material.emissive.copy( this.emissive );
  7760. material.specular.copy( this.specular );
  7761. material.shininess = this.shininess;
  7762. material.metal = this.metal;
  7763. material.perPixel = this.perPixel;
  7764. material.wrapAround = this.wrapAround;
  7765. material.wrapRGB.copy( this.wrapRGB );
  7766. material.map = this.map;
  7767. material.lightMap = this.lightMap;
  7768. material.bumpMap = this.bumpMap;
  7769. material.bumpScale = this.bumpScale;
  7770. material.normalMap = this.normalMap;
  7771. material.normalScale.copy( this.normalScale );
  7772. material.specularMap = this.specularMap;
  7773. material.envMap = this.envMap;
  7774. material.combine = this.combine;
  7775. material.reflectivity = this.reflectivity;
  7776. material.refractionRatio = this.refractionRatio;
  7777. material.fog = this.fog;
  7778. material.shading = this.shading;
  7779. material.wireframe = this.wireframe;
  7780. material.wireframeLinewidth = this.wireframeLinewidth;
  7781. material.wireframeLinecap = this.wireframeLinecap;
  7782. material.wireframeLinejoin = this.wireframeLinejoin;
  7783. material.vertexColors = this.vertexColors;
  7784. material.skinning = this.skinning;
  7785. material.morphTargets = this.morphTargets;
  7786. material.morphNormals = this.morphNormals;
  7787. return material;
  7788. };
  7789. /**
  7790. * @author mrdoob / http://mrdoob.com/
  7791. * @author alteredq / http://alteredqualia.com/
  7792. *
  7793. * parameters = {
  7794. * opacity: <float>,
  7795. *
  7796. * blending: THREE.NormalBlending,
  7797. * depthTest: <bool>,
  7798. * depthWrite: <bool>,
  7799. *
  7800. * wireframe: <boolean>,
  7801. * wireframeLinewidth: <float>
  7802. * }
  7803. */
  7804. THREE.MeshDepthMaterial = function ( parameters ) {
  7805. THREE.Material.call( this );
  7806. this.wireframe = false;
  7807. this.wireframeLinewidth = 1;
  7808. this.setValues( parameters );
  7809. };
  7810. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  7811. THREE.MeshDepthMaterial.prototype.clone = function () {
  7812. var material = new THREE.MeshDepthMaterial();
  7813. THREE.Material.prototype.clone.call( this, material );
  7814. material.wireframe = this.wireframe;
  7815. material.wireframeLinewidth = this.wireframeLinewidth;
  7816. return material;
  7817. };
  7818. /**
  7819. * @author mrdoob / http://mrdoob.com/
  7820. *
  7821. * parameters = {
  7822. * opacity: <float>,
  7823. *
  7824. * shading: THREE.FlatShading,
  7825. * blending: THREE.NormalBlending,
  7826. * depthTest: <bool>,
  7827. * depthWrite: <bool>,
  7828. *
  7829. * wireframe: <boolean>,
  7830. * wireframeLinewidth: <float>
  7831. * }
  7832. */
  7833. THREE.MeshNormalMaterial = function ( parameters ) {
  7834. THREE.Material.call( this, parameters );
  7835. this.shading = THREE.FlatShading;
  7836. this.wireframe = false;
  7837. this.wireframeLinewidth = 1;
  7838. this.morphTargets = false;
  7839. this.setValues( parameters );
  7840. };
  7841. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7842. THREE.MeshNormalMaterial.prototype.clone = function () {
  7843. var material = new THREE.MeshNormalMaterial();
  7844. THREE.Material.prototype.clone.call( this, material );
  7845. material.shading = this.shading;
  7846. material.wireframe = this.wireframe;
  7847. material.wireframeLinewidth = this.wireframeLinewidth;
  7848. return material;
  7849. };
  7850. /**
  7851. * @author mrdoob / http://mrdoob.com/
  7852. */
  7853. THREE.MeshFaceMaterial = function ( materials ) {
  7854. this.materials = materials instanceof Array ? materials : [];
  7855. };
  7856. THREE.MeshFaceMaterial.prototype.clone = function () {
  7857. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7858. };
  7859. /**
  7860. * @author mrdoob / http://mrdoob.com/
  7861. * @author alteredq / http://alteredqualia.com/
  7862. *
  7863. * parameters = {
  7864. * color: <hex>,
  7865. * opacity: <float>,
  7866. * map: new THREE.Texture( <Image> ),
  7867. *
  7868. * size: <float>,
  7869. *
  7870. * blending: THREE.NormalBlending,
  7871. * depthTest: <bool>,
  7872. * depthWrite: <bool>,
  7873. *
  7874. * vertexColors: <bool>,
  7875. *
  7876. * fog: <bool>
  7877. * }
  7878. */
  7879. THREE.ParticleBasicMaterial = function ( parameters ) {
  7880. THREE.Material.call( this );
  7881. this.color = new THREE.Color( 0xffffff );
  7882. this.map = null;
  7883. this.size = 1;
  7884. this.sizeAttenuation = true;
  7885. this.vertexColors = false;
  7886. this.fog = true;
  7887. this.setValues( parameters );
  7888. };
  7889. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7890. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7891. var material = new THREE.ParticleBasicMaterial();
  7892. THREE.Material.prototype.clone.call( this, material );
  7893. material.color.copy( this.color );
  7894. material.map = this.map;
  7895. material.size = this.size;
  7896. material.sizeAttenuation = this.sizeAttenuation;
  7897. material.vertexColors = this.vertexColors;
  7898. material.fog = this.fog;
  7899. return material;
  7900. };
  7901. /**
  7902. * @author mrdoob / http://mrdoob.com/
  7903. *
  7904. * parameters = {
  7905. * color: <hex>,
  7906. * program: <function>,
  7907. * opacity: <float>,
  7908. * blending: THREE.NormalBlending
  7909. * }
  7910. */
  7911. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7912. THREE.Material.call( this );
  7913. this.color = new THREE.Color( 0xffffff );
  7914. this.program = function ( context, color ) {};
  7915. this.setValues( parameters );
  7916. };
  7917. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7918. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7919. var material = new THREE.ParticleCanvasMaterial();
  7920. THREE.Material.prototype.clone.call( this, material );
  7921. material.color.copy( this.color );
  7922. material.program = this.program;
  7923. return material;
  7924. };
  7925. /**
  7926. * @author alteredq / http://alteredqualia.com/
  7927. *
  7928. * parameters = {
  7929. * fragmentShader: <string>,
  7930. * vertexShader: <string>,
  7931. *
  7932. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7933. *
  7934. * defines: { "label" : "value" },
  7935. *
  7936. * shading: THREE.SmoothShading,
  7937. * blending: THREE.NormalBlending,
  7938. * depthTest: <bool>,
  7939. * depthWrite: <bool>,
  7940. *
  7941. * wireframe: <boolean>,
  7942. * wireframeLinewidth: <float>,
  7943. *
  7944. * lights: <bool>,
  7945. *
  7946. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7947. *
  7948. * skinning: <bool>,
  7949. * morphTargets: <bool>,
  7950. * morphNormals: <bool>,
  7951. *
  7952. * fog: <bool>
  7953. * }
  7954. */
  7955. THREE.ShaderMaterial = function ( parameters ) {
  7956. THREE.Material.call( this );
  7957. this.fragmentShader = "void main() {}";
  7958. this.vertexShader = "void main() {}";
  7959. this.uniforms = {};
  7960. this.defines = {};
  7961. this.attributes = null;
  7962. this.shading = THREE.SmoothShading;
  7963. this.linewidth = 1;
  7964. this.wireframe = false;
  7965. this.wireframeLinewidth = 1;
  7966. this.fog = false; // set to use scene fog
  7967. this.lights = false; // set to use scene lights
  7968. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7969. this.skinning = false; // set to use skinning attribute streams
  7970. this.morphTargets = false; // set to use morph targets
  7971. this.morphNormals = false; // set to use morph normals
  7972. this.setValues( parameters );
  7973. };
  7974. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7975. THREE.ShaderMaterial.prototype.clone = function () {
  7976. var material = new THREE.ShaderMaterial();
  7977. THREE.Material.prototype.clone.call( this, material );
  7978. material.fragmentShader = this.fragmentShader;
  7979. material.vertexShader = this.vertexShader;
  7980. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7981. material.attributes = this.attributes;
  7982. material.defines = this.defines;
  7983. material.shading = this.shading;
  7984. material.wireframe = this.wireframe;
  7985. material.wireframeLinewidth = this.wireframeLinewidth;
  7986. material.fog = this.fog;
  7987. material.lights = this.lights;
  7988. material.vertexColors = this.vertexColors;
  7989. material.skinning = this.skinning;
  7990. material.morphTargets = this.morphTargets;
  7991. material.morphNormals = this.morphNormals;
  7992. return material;
  7993. };
  7994. /**
  7995. * @author alteredq / http://alteredqualia.com/
  7996. *
  7997. * parameters = {
  7998. * color: <hex>,
  7999. * opacity: <float>,
  8000. * map: new THREE.Texture( <Image> ),
  8001. *
  8002. * blending: THREE.NormalBlending,
  8003. * depthTest: <bool>,
  8004. * depthWrite: <bool>,
  8005. *
  8006. * useScreenCoordinates: <bool>,
  8007. * sizeAttenuation: <bool>,
  8008. * scaleByViewport: <bool>,
  8009. * alignment: THREE.SpriteAlignment.center,
  8010. *
  8011. * uvOffset: new THREE.Vector2(),
  8012. * uvScale: new THREE.Vector2(),
  8013. *
  8014. * fog: <bool>
  8015. * }
  8016. */
  8017. THREE.SpriteMaterial = function ( parameters ) {
  8018. THREE.Material.call( this );
  8019. // defaults
  8020. this.color = new THREE.Color( 0xffffff );
  8021. this.map = new THREE.Texture();
  8022. this.useScreenCoordinates = true;
  8023. this.depthTest = !this.useScreenCoordinates;
  8024. this.sizeAttenuation = !this.useScreenCoordinates;
  8025. this.scaleByViewport = !this.sizeAttenuation;
  8026. this.alignment = THREE.SpriteAlignment.center.clone();
  8027. this.fog = false;
  8028. this.uvOffset = new THREE.Vector2( 0, 0 );
  8029. this.uvScale = new THREE.Vector2( 1, 1 );
  8030. // set parameters
  8031. this.setValues( parameters );
  8032. // override coupled defaults if not specified explicitly by parameters
  8033. parameters = parameters || {};
  8034. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  8035. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  8036. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  8037. };
  8038. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  8039. THREE.SpriteMaterial.prototype.clone = function () {
  8040. var material = new THREE.SpriteMaterial();
  8041. THREE.Material.prototype.clone.call( this, material );
  8042. material.color.copy( this.color );
  8043. material.map = this.map;
  8044. material.useScreenCoordinates = this.useScreenCoordinates;
  8045. material.sizeAttenuation = this.sizeAttenuation;
  8046. material.scaleByViewport = this.scaleByViewport;
  8047. material.alignment.copy( this.alignment );
  8048. material.uvOffset.copy( this.uvOffset );
  8049. material.uvScale.copy( this.uvScale );
  8050. material.fog = this.fog;
  8051. return material;
  8052. };
  8053. // Alignment enums
  8054. THREE.SpriteAlignment = {};
  8055. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  8056. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  8057. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  8058. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  8059. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  8060. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  8061. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  8062. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  8063. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  8064. /**
  8065. * @author mrdoob / http://mrdoob.com/
  8066. * @author alteredq / http://alteredqualia.com/
  8067. * @author szimek / https://github.com/szimek/
  8068. */
  8069. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  8070. this.id = THREE.Math.generateUUID();
  8071. this.name = '';
  8072. this.image = image;
  8073. this.mipmaps = [];
  8074. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  8075. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  8076. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  8077. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  8078. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  8079. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  8080. this.format = format !== undefined ? format : THREE.RGBAFormat;
  8081. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  8082. this.offset = new THREE.Vector2( 0, 0 );
  8083. this.repeat = new THREE.Vector2( 1, 1 );
  8084. this.generateMipmaps = true;
  8085. this.premultiplyAlpha = false;
  8086. this.flipY = true;
  8087. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  8088. this.needsUpdate = false;
  8089. this.onUpdate = null;
  8090. };
  8091. THREE.Texture.prototype = {
  8092. constructor: THREE.Texture,
  8093. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  8094. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  8095. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  8096. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  8097. clone: function ( texture ) {
  8098. if ( texture === undefined ) texture = new THREE.Texture();
  8099. texture.image = this.image;
  8100. texture.mipmaps = this.mipmaps.slice(0);
  8101. texture.mapping = this.mapping;
  8102. texture.wrapS = this.wrapS;
  8103. texture.wrapT = this.wrapT;
  8104. texture.magFilter = this.magFilter;
  8105. texture.minFilter = this.minFilter;
  8106. texture.anisotropy = this.anisotropy;
  8107. texture.format = this.format;
  8108. texture.type = this.type;
  8109. texture.offset.copy( this.offset );
  8110. texture.repeat.copy( this.repeat );
  8111. texture.generateMipmaps = this.generateMipmaps;
  8112. texture.premultiplyAlpha = this.premultiplyAlpha;
  8113. texture.flipY = this.flipY;
  8114. texture.unpackAlignment = this.unpackAlignment;
  8115. return texture;
  8116. },
  8117. dispose: function () {
  8118. this.dispatchEvent( { type: 'dispose' } );
  8119. }
  8120. };
  8121. /**
  8122. * @author alteredq / http://alteredqualia.com/
  8123. */
  8124. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8125. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8126. this.image = { width: width, height: height };
  8127. this.mipmaps = mipmaps;
  8128. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  8129. };
  8130. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  8131. THREE.CompressedTexture.prototype.clone = function () {
  8132. var texture = new THREE.CompressedTexture();
  8133. THREE.Texture.prototype.clone.call( this, texture );
  8134. return texture;
  8135. };
  8136. /**
  8137. * @author alteredq / http://alteredqualia.com/
  8138. */
  8139. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  8140. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  8141. this.image = { data: data, width: width, height: height };
  8142. };
  8143. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  8144. THREE.DataTexture.prototype.clone = function () {
  8145. var texture = new THREE.DataTexture();
  8146. THREE.Texture.prototype.clone.call( this, texture );
  8147. return texture;
  8148. };
  8149. /**
  8150. * @author mrdoob / http://mrdoob.com/
  8151. */
  8152. THREE.Particle = function ( material ) {
  8153. THREE.Object3D.call( this );
  8154. this.material = material;
  8155. };
  8156. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  8157. THREE.Particle.prototype.clone = function ( object ) {
  8158. if ( object === undefined ) object = new THREE.Particle( this.material );
  8159. THREE.Object3D.prototype.clone.call( this, object );
  8160. return object;
  8161. };
  8162. /**
  8163. * @author alteredq / http://alteredqualia.com/
  8164. */
  8165. THREE.ParticleSystem = function ( geometry, material ) {
  8166. THREE.Object3D.call( this );
  8167. this.geometry = geometry;
  8168. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  8169. this.sortParticles = false;
  8170. if ( this.geometry ) {
  8171. // calc bound radius
  8172. if( this.geometry.boundingSphere === null ) {
  8173. this.geometry.computeBoundingSphere();
  8174. }
  8175. }
  8176. this.frustumCulled = false;
  8177. };
  8178. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  8179. THREE.ParticleSystem.prototype.clone = function ( object ) {
  8180. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  8181. object.sortParticles = this.sortParticles;
  8182. THREE.Object3D.prototype.clone.call( this, object );
  8183. return object;
  8184. };
  8185. /**
  8186. * @author mrdoob / http://mrdoob.com/
  8187. */
  8188. THREE.Line = function ( geometry, material, type ) {
  8189. THREE.Object3D.call( this );
  8190. this.geometry = geometry;
  8191. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  8192. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  8193. if ( this.geometry ) {
  8194. if ( ! this.geometry.boundingSphere ) {
  8195. this.geometry.computeBoundingSphere();
  8196. }
  8197. }
  8198. };
  8199. THREE.LineStrip = 0;
  8200. THREE.LinePieces = 1;
  8201. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  8202. THREE.Line.prototype.clone = function ( object ) {
  8203. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  8204. THREE.Object3D.prototype.clone.call( this, object );
  8205. return object;
  8206. };
  8207. /**
  8208. * @author mrdoob / http://mrdoob.com/
  8209. * @author alteredq / http://alteredqualia.com/
  8210. * @author mikael emtinger / http://gomo.se/
  8211. * @author jonobr1 / http://jonobr1.com/
  8212. */
  8213. THREE.Mesh = function ( geometry, material ) {
  8214. THREE.Object3D.call( this );
  8215. this.geometry = null;
  8216. this.material = null;
  8217. this.setGeometry( geometry );
  8218. this.setMaterial( material );
  8219. };
  8220. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  8221. THREE.Mesh.prototype.setGeometry = function ( geometry ) {
  8222. if ( geometry !== undefined ) {
  8223. this.geometry = geometry;
  8224. if ( this.geometry.boundingSphere === null ) {
  8225. this.geometry.computeBoundingSphere();
  8226. }
  8227. this.updateMorphTargets();
  8228. }
  8229. };
  8230. THREE.Mesh.prototype.setMaterial = function ( material ) {
  8231. if ( material !== undefined ) {
  8232. this.material = material;
  8233. } else {
  8234. this.material = new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  8235. }
  8236. };
  8237. THREE.Mesh.prototype.updateMorphTargets = function () {
  8238. if ( this.geometry.morphTargets.length > 0 ) {
  8239. this.morphTargetBase = -1;
  8240. this.morphTargetForcedOrder = [];
  8241. this.morphTargetInfluences = [];
  8242. this.morphTargetDictionary = {};
  8243. for ( var m = 0, ml = this.geometry.morphTargets.length; m < ml; m ++ ) {
  8244. this.morphTargetInfluences.push( 0 );
  8245. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  8246. }
  8247. }
  8248. };
  8249. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  8250. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  8251. return this.morphTargetDictionary[ name ];
  8252. }
  8253. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  8254. return 0;
  8255. };
  8256. THREE.Mesh.prototype.clone = function ( object ) {
  8257. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  8258. THREE.Object3D.prototype.clone.call( this, object );
  8259. return object;
  8260. };
  8261. /**
  8262. * @author mikael emtinger / http://gomo.se/
  8263. * @author alteredq / http://alteredqualia.com/
  8264. */
  8265. THREE.Bone = function( belongsToSkin ) {
  8266. THREE.Object3D.call( this );
  8267. this.skin = belongsToSkin;
  8268. this.skinMatrix = new THREE.Matrix4();
  8269. };
  8270. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  8271. THREE.Bone.prototype.update = function ( parentSkinMatrix, forceUpdate ) {
  8272. // update local
  8273. if ( this.matrixAutoUpdate ) {
  8274. forceUpdate |= this.updateMatrix();
  8275. }
  8276. // update skin matrix
  8277. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  8278. if( parentSkinMatrix ) {
  8279. this.skinMatrix.multiplyMatrices( parentSkinMatrix, this.matrix );
  8280. } else {
  8281. this.skinMatrix.copy( this.matrix );
  8282. }
  8283. this.matrixWorldNeedsUpdate = false;
  8284. forceUpdate = true;
  8285. }
  8286. // update children
  8287. var child, i, l = this.children.length;
  8288. for ( i = 0; i < l; i ++ ) {
  8289. this.children[ i ].update( this.skinMatrix, forceUpdate );
  8290. }
  8291. };
  8292. /**
  8293. * @author mikael emtinger / http://gomo.se/
  8294. * @author alteredq / http://alteredqualia.com/
  8295. */
  8296. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  8297. THREE.Mesh.call( this, geometry, material );
  8298. //
  8299. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  8300. // init bones
  8301. this.identityMatrix = new THREE.Matrix4();
  8302. this.bones = [];
  8303. this.boneMatrices = [];
  8304. var b, bone, gbone, p, q, s;
  8305. if ( this.geometry && this.geometry.bones !== undefined ) {
  8306. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  8307. gbone = this.geometry.bones[ b ];
  8308. p = gbone.pos;
  8309. q = gbone.rotq;
  8310. s = gbone.scl;
  8311. bone = this.addBone();
  8312. bone.name = gbone.name;
  8313. bone.position.set( p[0], p[1], p[2] );
  8314. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  8315. if ( s !== undefined ) {
  8316. bone.scale.set( s[0], s[1], s[2] );
  8317. } else {
  8318. bone.scale.set( 1, 1, 1 );
  8319. }
  8320. }
  8321. for ( b = 0; b < this.bones.length; b ++ ) {
  8322. gbone = this.geometry.bones[ b ];
  8323. bone = this.bones[ b ];
  8324. if ( gbone.parent === -1 ) {
  8325. this.add( bone );
  8326. } else {
  8327. this.bones[ gbone.parent ].add( bone );
  8328. }
  8329. }
  8330. //
  8331. var nBones = this.bones.length;
  8332. if ( this.useVertexTexture ) {
  8333. // layout (1 matrix = 4 pixels)
  8334. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  8335. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  8336. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  8337. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  8338. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  8339. var size;
  8340. if ( nBones > 256 )
  8341. size = 64;
  8342. else if ( nBones > 64 )
  8343. size = 32;
  8344. else if ( nBones > 16 )
  8345. size = 16;
  8346. else
  8347. size = 8;
  8348. this.boneTextureWidth = size;
  8349. this.boneTextureHeight = size;
  8350. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  8351. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  8352. this.boneTexture.minFilter = THREE.NearestFilter;
  8353. this.boneTexture.magFilter = THREE.NearestFilter;
  8354. this.boneTexture.generateMipmaps = false;
  8355. this.boneTexture.flipY = false;
  8356. } else {
  8357. this.boneMatrices = new Float32Array( 16 * nBones );
  8358. }
  8359. this.pose();
  8360. }
  8361. };
  8362. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  8363. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  8364. if ( bone === undefined ) {
  8365. bone = new THREE.Bone( this );
  8366. }
  8367. this.bones.push( bone );
  8368. return bone;
  8369. };
  8370. THREE.SkinnedMesh.prototype.updateMatrixWorld = function () {
  8371. var offsetMatrix = new THREE.Matrix4();
  8372. return function ( force ) {
  8373. this.matrixAutoUpdate && this.updateMatrix();
  8374. // update matrixWorld
  8375. if ( this.matrixWorldNeedsUpdate || force ) {
  8376. if ( this.parent ) {
  8377. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  8378. } else {
  8379. this.matrixWorld.copy( this.matrix );
  8380. }
  8381. this.matrixWorldNeedsUpdate = false;
  8382. force = true;
  8383. }
  8384. // update children
  8385. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  8386. var child = this.children[ i ];
  8387. if ( child instanceof THREE.Bone ) {
  8388. child.update( this.identityMatrix, false );
  8389. } else {
  8390. child.updateMatrixWorld( true );
  8391. }
  8392. }
  8393. // make a snapshot of the bones' rest position
  8394. if ( this.boneInverses == undefined ) {
  8395. this.boneInverses = [];
  8396. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8397. var inverse = new THREE.Matrix4();
  8398. inverse.getInverse( this.bones[ b ].skinMatrix );
  8399. this.boneInverses.push( inverse );
  8400. }
  8401. }
  8402. // flatten bone matrices to array
  8403. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  8404. // compute the offset between the current and the original transform;
  8405. // TODO: we could get rid of this multiplication step if the skinMatrix
  8406. // was already representing the offset; however, this requires some
  8407. // major changes to the animation system
  8408. offsetMatrix.multiplyMatrices( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  8409. offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  8410. }
  8411. if ( this.useVertexTexture ) {
  8412. this.boneTexture.needsUpdate = true;
  8413. }
  8414. };
  8415. }();
  8416. THREE.SkinnedMesh.prototype.pose = function () {
  8417. this.updateMatrixWorld( true );
  8418. this.normalizeSkinWeights();
  8419. };
  8420. THREE.SkinnedMesh.prototype.normalizeSkinWeights = function () {
  8421. if ( this.geometry instanceof THREE.Geometry ) {
  8422. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  8423. var sw = this.geometry.skinWeights[ i ];
  8424. var scale = 1.0 / sw.lengthManhattan();
  8425. if ( scale !== Infinity ) {
  8426. sw.multiplyScalar( scale );
  8427. } else {
  8428. sw.set( 1 ); // this will be normalized by the shader anyway
  8429. }
  8430. }
  8431. } else {
  8432. // skinning weights assumed to be normalized for THREE.BufferGeometry
  8433. }
  8434. };
  8435. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  8436. if ( object === undefined ) {
  8437. object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  8438. }
  8439. THREE.Mesh.prototype.clone.call( this, object );
  8440. return object;
  8441. };
  8442. /**
  8443. * @author alteredq / http://alteredqualia.com/
  8444. */
  8445. THREE.MorphAnimMesh = function ( geometry, material ) {
  8446. THREE.Mesh.call( this, geometry, material );
  8447. // API
  8448. this.duration = 1000; // milliseconds
  8449. this.mirroredLoop = false;
  8450. this.time = 0;
  8451. // internals
  8452. this.lastKeyframe = 0;
  8453. this.currentKeyframe = 0;
  8454. this.direction = 1;
  8455. this.directionBackwards = false;
  8456. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  8457. };
  8458. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  8459. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  8460. this.startKeyframe = start;
  8461. this.endKeyframe = end;
  8462. this.length = this.endKeyframe - this.startKeyframe + 1;
  8463. };
  8464. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  8465. this.direction = 1;
  8466. this.directionBackwards = false;
  8467. };
  8468. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  8469. this.direction = -1;
  8470. this.directionBackwards = true;
  8471. };
  8472. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  8473. var geometry = this.geometry;
  8474. if ( ! geometry.animations ) geometry.animations = {};
  8475. var firstAnimation, animations = geometry.animations;
  8476. var pattern = /([a-z]+)(\d+)/;
  8477. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  8478. var morph = geometry.morphTargets[ i ];
  8479. var parts = morph.name.match( pattern );
  8480. if ( parts && parts.length > 1 ) {
  8481. var label = parts[ 1 ];
  8482. var num = parts[ 2 ];
  8483. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  8484. var animation = animations[ label ];
  8485. if ( i < animation.start ) animation.start = i;
  8486. if ( i > animation.end ) animation.end = i;
  8487. if ( ! firstAnimation ) firstAnimation = label;
  8488. }
  8489. }
  8490. geometry.firstAnimation = firstAnimation;
  8491. };
  8492. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  8493. if ( ! this.geometry.animations ) this.geometry.animations = {};
  8494. this.geometry.animations[ label ] = { start: start, end: end };
  8495. };
  8496. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  8497. var animation = this.geometry.animations[ label ];
  8498. if ( animation ) {
  8499. this.setFrameRange( animation.start, animation.end );
  8500. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  8501. this.time = 0;
  8502. } else {
  8503. console.warn( "animation[" + label + "] undefined" );
  8504. }
  8505. };
  8506. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  8507. var frameTime = this.duration / this.length;
  8508. this.time += this.direction * delta;
  8509. if ( this.mirroredLoop ) {
  8510. if ( this.time > this.duration || this.time < 0 ) {
  8511. this.direction *= -1;
  8512. if ( this.time > this.duration ) {
  8513. this.time = this.duration;
  8514. this.directionBackwards = true;
  8515. }
  8516. if ( this.time < 0 ) {
  8517. this.time = 0;
  8518. this.directionBackwards = false;
  8519. }
  8520. }
  8521. } else {
  8522. this.time = this.time % this.duration;
  8523. if ( this.time < 0 ) this.time += this.duration;
  8524. }
  8525. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  8526. if ( keyframe !== this.currentKeyframe ) {
  8527. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  8528. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  8529. this.morphTargetInfluences[ keyframe ] = 0;
  8530. this.lastKeyframe = this.currentKeyframe;
  8531. this.currentKeyframe = keyframe;
  8532. }
  8533. var mix = ( this.time % frameTime ) / frameTime;
  8534. if ( this.directionBackwards ) {
  8535. mix = 1 - mix;
  8536. }
  8537. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  8538. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  8539. };
  8540. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  8541. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  8542. object.duration = this.duration;
  8543. object.mirroredLoop = this.mirroredLoop;
  8544. object.time = this.time;
  8545. object.lastKeyframe = this.lastKeyframe;
  8546. object.currentKeyframe = this.currentKeyframe;
  8547. object.direction = this.direction;
  8548. object.directionBackwards = this.directionBackwards;
  8549. THREE.Mesh.prototype.clone.call( this, object );
  8550. return object;
  8551. };
  8552. /**
  8553. * @author alteredq / http://alteredqualia.com/
  8554. */
  8555. THREE.Ribbon = function ( geometry, material ) {
  8556. THREE.Object3D.call( this );
  8557. this.geometry = geometry;
  8558. this.material = material;
  8559. };
  8560. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  8561. THREE.Ribbon.prototype.clone = function ( object ) {
  8562. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  8563. THREE.Object3D.prototype.clone.call( this, object );
  8564. return object;
  8565. };
  8566. /**
  8567. * @author mikael emtinger / http://gomo.se/
  8568. * @author alteredq / http://alteredqualia.com/
  8569. * @author mrdoob / http://mrdoob.com/
  8570. */
  8571. THREE.LOD = function () {
  8572. THREE.Object3D.call( this );
  8573. this.objects = [];
  8574. };
  8575. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  8576. THREE.LOD.prototype.addLevel = function ( object, distance ) {
  8577. if ( distance === undefined ) distance = 0;
  8578. distance = Math.abs( distance );
  8579. for ( var l = 0; l < this.objects.length; l ++ ) {
  8580. if ( distance < this.objects[ l ].distance ) {
  8581. break;
  8582. }
  8583. }
  8584. this.objects.splice( l, 0, { distance: distance, object: object } );
  8585. this.add( object );
  8586. };
  8587. THREE.LOD.prototype.getObjectForDistance = function ( distance ) {
  8588. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8589. if ( distance < this.objects[ i ].distance ) {
  8590. break;
  8591. }
  8592. }
  8593. return this.objects[ i - 1 ].object;
  8594. };
  8595. THREE.LOD.prototype.update = function () {
  8596. var v1 = new THREE.Vector3();
  8597. var v2 = new THREE.Vector3();
  8598. return function ( camera ) {
  8599. if ( this.objects.length > 1 ) {
  8600. v1.getPositionFromMatrix( camera.matrixWorld );
  8601. v2.getPositionFromMatrix( this.matrixWorld );
  8602. var distance = v1.distanceTo( v2 );
  8603. this.objects[ 0 ].object.visible = true;
  8604. for ( var i = 1, l = this.objects.length; i < l; i ++ ) {
  8605. if ( distance >= this.objects[ i ].distance ) {
  8606. this.objects[ i - 1 ].object.visible = false;
  8607. this.objects[ i ].object.visible = true;
  8608. } else {
  8609. break;
  8610. }
  8611. }
  8612. for( ; i < l; i ++ ) {
  8613. this.objects[ i ].object.visible = false;
  8614. }
  8615. }
  8616. };
  8617. }();
  8618. THREE.LOD.prototype.clone = function () {
  8619. // TODO
  8620. };
  8621. /**
  8622. * @author mikael emtinger / http://gomo.se/
  8623. * @author alteredq / http://alteredqualia.com/
  8624. */
  8625. THREE.Sprite = function ( material ) {
  8626. THREE.Object3D.call( this );
  8627. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  8628. this.rotation3d = this.rotation;
  8629. this.rotation = 0;
  8630. };
  8631. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  8632. /*
  8633. * Custom update matrix
  8634. */
  8635. THREE.Sprite.prototype.updateMatrix = function () {
  8636. this.rotation3d.set( 0, 0, this.rotation, this.rotation3d.order );
  8637. this.quaternion.setFromEuler( this.rotation3d );
  8638. this.matrix.compose( this.position, this.quaternion, this.scale );
  8639. this.matrixWorldNeedsUpdate = true;
  8640. };
  8641. THREE.Sprite.prototype.clone = function ( object ) {
  8642. if ( object === undefined ) object = new THREE.Sprite( this.material );
  8643. THREE.Object3D.prototype.clone.call( this, object );
  8644. return object;
  8645. };
  8646. /**
  8647. * @author mrdoob / http://mrdoob.com/
  8648. */
  8649. THREE.Scene = function () {
  8650. THREE.Object3D.call( this );
  8651. this.fog = null;
  8652. this.overrideMaterial = null;
  8653. this.autoUpdate = true; // checked by the renderer
  8654. this.matrixAutoUpdate = false;
  8655. this.__objects = [];
  8656. this.__lights = [];
  8657. this.__objectsAdded = [];
  8658. this.__objectsRemoved = [];
  8659. };
  8660. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  8661. THREE.Scene.prototype.__addObject = function ( object ) {
  8662. if ( object instanceof THREE.Light ) {
  8663. if ( this.__lights.indexOf( object ) === - 1 ) {
  8664. this.__lights.push( object );
  8665. }
  8666. if ( object.target && object.target.parent === undefined ) {
  8667. this.add( object.target );
  8668. }
  8669. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  8670. if ( this.__objects.indexOf( object ) === - 1 ) {
  8671. this.__objects.push( object );
  8672. this.__objectsAdded.push( object );
  8673. // check if previously removed
  8674. var i = this.__objectsRemoved.indexOf( object );
  8675. if ( i !== -1 ) {
  8676. this.__objectsRemoved.splice( i, 1 );
  8677. }
  8678. }
  8679. }
  8680. for ( var c = 0; c < object.children.length; c ++ ) {
  8681. this.__addObject( object.children[ c ] );
  8682. }
  8683. };
  8684. THREE.Scene.prototype.__removeObject = function ( object ) {
  8685. if ( object instanceof THREE.Light ) {
  8686. var i = this.__lights.indexOf( object );
  8687. if ( i !== -1 ) {
  8688. this.__lights.splice( i, 1 );
  8689. }
  8690. } else if ( !( object instanceof THREE.Camera ) ) {
  8691. var i = this.__objects.indexOf( object );
  8692. if( i !== -1 ) {
  8693. this.__objects.splice( i, 1 );
  8694. this.__objectsRemoved.push( object );
  8695. // check if previously added
  8696. var ai = this.__objectsAdded.indexOf( object );
  8697. if ( ai !== -1 ) {
  8698. this.__objectsAdded.splice( ai, 1 );
  8699. }
  8700. }
  8701. }
  8702. for ( var c = 0; c < object.children.length; c ++ ) {
  8703. this.__removeObject( object.children[ c ] );
  8704. }
  8705. };
  8706. THREE.Scene.prototype.clone = function ( object ) {
  8707. if ( object === undefined ) object = new THREE.Scene();
  8708. THREE.Object3D.prototype.clone.call(this, object);
  8709. if ( this.fog !== null ) object.fog = this.fog.clone();
  8710. if ( this.overrideMaterial !== null ) object.overrideMaterial = this.overrideMaterial.clone();
  8711. object.autoUpdate = this.autoUpdate;
  8712. object.matrixAutoUpdate = this.matrixAutoUpdate;
  8713. return object;
  8714. };
  8715. /**
  8716. * @author mrdoob / http://mrdoob.com/
  8717. * @author alteredq / http://alteredqualia.com/
  8718. */
  8719. THREE.Fog = function ( hex, near, far ) {
  8720. this.name = '';
  8721. this.color = new THREE.Color( hex );
  8722. this.near = ( near !== undefined ) ? near : 1;
  8723. this.far = ( far !== undefined ) ? far : 1000;
  8724. };
  8725. THREE.Fog.prototype.clone = function () {
  8726. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  8727. };
  8728. /**
  8729. * @author mrdoob / http://mrdoob.com/
  8730. * @author alteredq / http://alteredqualia.com/
  8731. */
  8732. THREE.FogExp2 = function ( hex, density ) {
  8733. this.name = '';
  8734. this.color = new THREE.Color( hex );
  8735. this.density = ( density !== undefined ) ? density : 0.00025;
  8736. };
  8737. THREE.FogExp2.prototype.clone = function () {
  8738. return new THREE.FogExp2( this.color.getHex(), this.density );
  8739. };
  8740. /**
  8741. * @author mrdoob / http://mrdoob.com/
  8742. */
  8743. THREE.CanvasRenderer = function ( parameters ) {
  8744. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  8745. var smoothstep = THREE.Math.smoothstep;
  8746. parameters = parameters || {};
  8747. var _this = this,
  8748. _renderData, _elements, _lights,
  8749. _projector = new THREE.Projector(),
  8750. _canvas = parameters.canvas !== undefined
  8751. ? parameters.canvas
  8752. : document.createElement( 'canvas' ),
  8753. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  8754. _context = _canvas.getContext( '2d' ),
  8755. _clearColor = new THREE.Color( 0x000000 ),
  8756. _clearAlpha = 0,
  8757. _contextGlobalAlpha = 1,
  8758. _contextGlobalCompositeOperation = 0,
  8759. _contextStrokeStyle = null,
  8760. _contextFillStyle = null,
  8761. _contextLineWidth = null,
  8762. _contextLineCap = null,
  8763. _contextLineJoin = null,
  8764. _contextDashSize = null,
  8765. _contextGapSize = 0,
  8766. _camera,
  8767. _v1, _v2, _v3, _v4,
  8768. _v5 = new THREE.RenderableVertex(),
  8769. _v6 = new THREE.RenderableVertex(),
  8770. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  8771. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  8772. _color = new THREE.Color(),
  8773. _color1 = new THREE.Color(),
  8774. _color2 = new THREE.Color(),
  8775. _color3 = new THREE.Color(),
  8776. _color4 = new THREE.Color(),
  8777. _diffuseColor = new THREE.Color(),
  8778. _emissiveColor = new THREE.Color(),
  8779. _lightColor = new THREE.Color(),
  8780. _patterns = {}, _imagedatas = {},
  8781. _near, _far,
  8782. _image, _uvs,
  8783. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  8784. _clipBox = new THREE.Box2(),
  8785. _clearBox = new THREE.Box2(),
  8786. _elemBox = new THREE.Box2(),
  8787. _ambientLight = new THREE.Color(),
  8788. _directionalLights = new THREE.Color(),
  8789. _pointLights = new THREE.Color(),
  8790. _vector3 = new THREE.Vector3(), // Needed for PointLight
  8791. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  8792. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  8793. _pixelMap = document.createElement( 'canvas' );
  8794. _pixelMap.width = _pixelMap.height = 2;
  8795. _pixelMapContext = _pixelMap.getContext( '2d' );
  8796. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  8797. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  8798. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  8799. _pixelMapData = _pixelMapImage.data;
  8800. _gradientMap = document.createElement( 'canvas' );
  8801. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  8802. _gradientMapContext = _gradientMap.getContext( '2d' );
  8803. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  8804. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  8805. _gradientMapQuality --; // Fix UVs
  8806. // dash+gap fallbacks for Firefox and everything else
  8807. if ( _context.setLineDash === undefined ) {
  8808. if ( _context.mozDash !== undefined ) {
  8809. _context.setLineDash = function ( values ) {
  8810. _context.mozDash = values[ 0 ] !== null ? values : null;
  8811. }
  8812. } else {
  8813. _context.setLineDash = function () {}
  8814. }
  8815. }
  8816. this.domElement = _canvas;
  8817. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  8818. ? parameters.devicePixelRatio
  8819. : window.devicePixelRatio !== undefined
  8820. ? window.devicePixelRatio
  8821. : 1;
  8822. this.autoClear = true;
  8823. this.sortObjects = true;
  8824. this.sortElements = true;
  8825. this.info = {
  8826. render: {
  8827. vertices: 0,
  8828. faces: 0
  8829. }
  8830. }
  8831. // WebGLRenderer compatibility
  8832. this.supportsVertexTextures = function () {};
  8833. this.setFaceCulling = function () {};
  8834. this.setSize = function ( width, height, updateStyle ) {
  8835. _canvasWidth = width * this.devicePixelRatio;
  8836. _canvasHeight = height * this.devicePixelRatio;
  8837. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  8838. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  8839. _canvas.width = _canvasWidth;
  8840. _canvas.height = _canvasHeight;
  8841. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  8842. _canvas.style.width = width + 'px';
  8843. _canvas.style.height = height + 'px';
  8844. }
  8845. _clipBox.set(
  8846. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8847. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8848. );
  8849. _clearBox.set(
  8850. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8851. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8852. );
  8853. _contextGlobalAlpha = 1;
  8854. _contextGlobalCompositeOperation = 0;
  8855. _contextStrokeStyle = null;
  8856. _contextFillStyle = null;
  8857. _contextLineWidth = null;
  8858. _contextLineCap = null;
  8859. _contextLineJoin = null;
  8860. };
  8861. this.setClearColor = function ( color, alpha ) {
  8862. _clearColor.set( color );
  8863. _clearAlpha = alpha !== undefined ? alpha : 1;
  8864. _clearBox.set(
  8865. new THREE.Vector2( - _canvasWidthHalf, - _canvasHeightHalf ),
  8866. new THREE.Vector2( _canvasWidthHalf, _canvasHeightHalf )
  8867. );
  8868. };
  8869. this.setClearColorHex = function ( hex, alpha ) {
  8870. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  8871. this.setClearColor( hex, alpha );
  8872. };
  8873. this.getMaxAnisotropy = function () {
  8874. return 0;
  8875. };
  8876. this.clear = function () {
  8877. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8878. if ( _clearBox.empty() === false ) {
  8879. _clearBox.intersect( _clipBox );
  8880. _clearBox.expandByScalar( 2 );
  8881. if ( _clearAlpha < 1 ) {
  8882. _context.clearRect(
  8883. _clearBox.min.x | 0,
  8884. _clearBox.min.y | 0,
  8885. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8886. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8887. );
  8888. }
  8889. if ( _clearAlpha > 0 ) {
  8890. setBlending( THREE.NormalBlending );
  8891. setOpacity( 1 );
  8892. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearAlpha + ')' );
  8893. _context.fillRect(
  8894. _clearBox.min.x | 0,
  8895. _clearBox.min.y | 0,
  8896. ( _clearBox.max.x - _clearBox.min.x ) | 0,
  8897. ( _clearBox.max.y - _clearBox.min.y ) | 0
  8898. );
  8899. }
  8900. _clearBox.makeEmpty();
  8901. }
  8902. };
  8903. this.render = function ( scene, camera ) {
  8904. if ( camera instanceof THREE.Camera === false ) {
  8905. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8906. return;
  8907. }
  8908. if ( this.autoClear === true ) this.clear();
  8909. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8910. _this.info.render.vertices = 0;
  8911. _this.info.render.faces = 0;
  8912. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8913. _elements = _renderData.elements;
  8914. _lights = _renderData.lights;
  8915. _camera = camera;
  8916. /* DEBUG
  8917. setFillStyle( 'rgba( 0, 255, 255, 0.5 )' );
  8918. _context.fillRect( _clipBox.min.x, _clipBox.min.y, _clipBox.max.x - _clipBox.min.x, _clipBox.max.y - _clipBox.min.y );
  8919. */
  8920. calculateLights();
  8921. for ( var e = 0, el = _elements.length; e < el; e++ ) {
  8922. var element = _elements[ e ];
  8923. var material = element.material;
  8924. if ( material === undefined || material.visible === false ) continue;
  8925. _elemBox.makeEmpty();
  8926. if ( element instanceof THREE.RenderableParticle ) {
  8927. _v1 = element;
  8928. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8929. renderParticle( _v1, element, material );
  8930. } else if ( element instanceof THREE.RenderableLine ) {
  8931. _v1 = element.v1; _v2 = element.v2;
  8932. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8933. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8934. _elemBox.setFromPoints( [
  8935. _v1.positionScreen,
  8936. _v2.positionScreen
  8937. ] );
  8938. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8939. renderLine( _v1, _v2, element, material );
  8940. }
  8941. } else if ( element instanceof THREE.RenderableFace3 ) {
  8942. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8943. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8944. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8945. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8946. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8947. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8948. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8949. if ( material.overdraw > 0 ) {
  8950. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8951. expand( _v2.positionScreen, _v3.positionScreen, material.overdraw );
  8952. expand( _v3.positionScreen, _v1.positionScreen, material.overdraw );
  8953. }
  8954. _elemBox.setFromPoints( [
  8955. _v1.positionScreen,
  8956. _v2.positionScreen,
  8957. _v3.positionScreen
  8958. ] );
  8959. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8960. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material );
  8961. }
  8962. } else if ( element instanceof THREE.RenderableFace4 ) {
  8963. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8964. if ( _v1.positionScreen.z < -1 || _v1.positionScreen.z > 1 ) continue;
  8965. if ( _v2.positionScreen.z < -1 || _v2.positionScreen.z > 1 ) continue;
  8966. if ( _v3.positionScreen.z < -1 || _v3.positionScreen.z > 1 ) continue;
  8967. if ( _v4.positionScreen.z < -1 || _v4.positionScreen.z > 1 ) continue;
  8968. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8969. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8970. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8971. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8972. _v5.positionScreen.copy( _v2.positionScreen );
  8973. _v6.positionScreen.copy( _v4.positionScreen );
  8974. if ( material.overdraw > 0 ) {
  8975. expand( _v1.positionScreen, _v2.positionScreen, material.overdraw );
  8976. expand( _v2.positionScreen, _v4.positionScreen, material.overdraw );
  8977. expand( _v4.positionScreen, _v1.positionScreen, material.overdraw );
  8978. expand( _v3.positionScreen, _v5.positionScreen, material.overdraw );
  8979. expand( _v3.positionScreen, _v6.positionScreen, material.overdraw );
  8980. }
  8981. _elemBox.setFromPoints( [
  8982. _v1.positionScreen,
  8983. _v2.positionScreen,
  8984. _v3.positionScreen,
  8985. _v4.positionScreen
  8986. ] );
  8987. if ( _clipBox.isIntersectionBox( _elemBox ) === true ) {
  8988. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material );
  8989. }
  8990. }
  8991. /* DEBUG
  8992. setLineWidth( 1 );
  8993. setStrokeStyle( 'rgba( 0, 255, 0, 0.5 )' );
  8994. _context.strokeRect( _elemBox.min.x, _elemBox.min.y, _elemBox.max.x - _elemBox.min.x, _elemBox.max.y - _elemBox.min.y );
  8995. */
  8996. _clearBox.union( _elemBox );
  8997. }
  8998. /* DEBUG
  8999. setLineWidth( 1 );
  9000. setStrokeStyle( 'rgba( 255, 0, 0, 0.5 )' );
  9001. _context.strokeRect( _clearBox.min.x, _clearBox.min.y, _clearBox.max.x - _clearBox.min.x, _clearBox.max.y - _clearBox.min.y );
  9002. */
  9003. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  9004. };
  9005. //
  9006. function calculateLights() {
  9007. _ambientLight.setRGB( 0, 0, 0 );
  9008. _directionalLights.setRGB( 0, 0, 0 );
  9009. _pointLights.setRGB( 0, 0, 0 );
  9010. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9011. var light = _lights[ l ];
  9012. var lightColor = light.color;
  9013. if ( light instanceof THREE.AmbientLight ) {
  9014. _ambientLight.add( lightColor );
  9015. } else if ( light instanceof THREE.DirectionalLight ) {
  9016. // for particles
  9017. _directionalLights.add( lightColor );
  9018. } else if ( light instanceof THREE.PointLight ) {
  9019. // for particles
  9020. _pointLights.add( lightColor );
  9021. }
  9022. }
  9023. }
  9024. function calculateLight( position, normal, color ) {
  9025. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  9026. var light = _lights[ l ];
  9027. _lightColor.copy( light.color );
  9028. if ( light instanceof THREE.DirectionalLight ) {
  9029. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld ).normalize();
  9030. var amount = normal.dot( lightPosition );
  9031. if ( amount <= 0 ) continue;
  9032. amount *= light.intensity;
  9033. color.add( _lightColor.multiplyScalar( amount ) );
  9034. } else if ( light instanceof THREE.PointLight ) {
  9035. var lightPosition = _vector3.getPositionFromMatrix( light.matrixWorld );
  9036. var amount = normal.dot( _vector3.subVectors( lightPosition, position ).normalize() );
  9037. if ( amount <= 0 ) continue;
  9038. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  9039. if ( amount == 0 ) continue;
  9040. amount *= light.intensity;
  9041. color.add( _lightColor.multiplyScalar( amount ) );
  9042. }
  9043. }
  9044. }
  9045. function renderParticle( v1, element, material ) {
  9046. setOpacity( material.opacity );
  9047. setBlending( material.blending );
  9048. var width, height, scaleX, scaleY,
  9049. bitmap, bitmapWidth, bitmapHeight;
  9050. if ( material instanceof THREE.ParticleBasicMaterial ) {
  9051. if ( material.map === null ) {
  9052. scaleX = element.object.scale.x;
  9053. scaleY = element.object.scale.y;
  9054. // TODO: Be able to disable this
  9055. scaleX *= element.scale.x * _canvasWidthHalf;
  9056. scaleY *= element.scale.y * _canvasHeightHalf;
  9057. _elemBox.min.set( v1.x - scaleX, v1.y - scaleY );
  9058. _elemBox.max.set( v1.x + scaleX, v1.y + scaleY );
  9059. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9060. _elemBox.makeEmpty();
  9061. return;
  9062. }
  9063. setFillStyle( material.color.getStyle() );
  9064. _context.save();
  9065. _context.translate( v1.x, v1.y );
  9066. _context.rotate( - element.rotation );
  9067. _context.scale( scaleX, scaleY );
  9068. _context.fillRect( -1, -1, 2, 2 );
  9069. _context.restore();
  9070. } else {
  9071. bitmap = material.map.image;
  9072. bitmapWidth = bitmap.width >> 1;
  9073. bitmapHeight = bitmap.height >> 1;
  9074. scaleX = element.scale.x * _canvasWidthHalf;
  9075. scaleY = element.scale.y * _canvasHeightHalf;
  9076. width = scaleX * bitmapWidth;
  9077. height = scaleY * bitmapHeight;
  9078. // TODO: Rotations break this...
  9079. _elemBox.min.set( v1.x - width, v1.y - height );
  9080. _elemBox.max.set( v1.x + width, v1.y + height );
  9081. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9082. _elemBox.makeEmpty();
  9083. return;
  9084. }
  9085. _context.save();
  9086. _context.translate( v1.x, v1.y );
  9087. _context.rotate( - element.rotation );
  9088. _context.scale( scaleX, - scaleY );
  9089. _context.translate( - bitmapWidth, - bitmapHeight );
  9090. _context.drawImage( bitmap, 0, 0 );
  9091. _context.restore();
  9092. }
  9093. /* DEBUG
  9094. setStrokeStyle( 'rgb(255,255,0)' );
  9095. _context.beginPath();
  9096. _context.moveTo( v1.x - 10, v1.y );
  9097. _context.lineTo( v1.x + 10, v1.y );
  9098. _context.moveTo( v1.x, v1.y - 10 );
  9099. _context.lineTo( v1.x, v1.y + 10 );
  9100. _context.stroke();
  9101. */
  9102. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  9103. width = element.scale.x * _canvasWidthHalf;
  9104. height = element.scale.y * _canvasHeightHalf;
  9105. _elemBox.min.set( v1.x - width, v1.y - height );
  9106. _elemBox.max.set( v1.x + width, v1.y + height );
  9107. if ( _clipBox.isIntersectionBox( _elemBox ) === false ) {
  9108. _elemBox.makeEmpty();
  9109. return;
  9110. }
  9111. setStrokeStyle( material.color.getStyle() );
  9112. setFillStyle( material.color.getStyle() );
  9113. _context.save();
  9114. _context.translate( v1.x, v1.y );
  9115. _context.rotate( - element.rotation );
  9116. _context.scale( width, height );
  9117. material.program( _context );
  9118. _context.restore();
  9119. }
  9120. }
  9121. function renderLine( v1, v2, element, material ) {
  9122. setOpacity( material.opacity );
  9123. setBlending( material.blending );
  9124. _context.beginPath();
  9125. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  9126. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  9127. if ( material instanceof THREE.LineBasicMaterial ) {
  9128. setLineWidth( material.linewidth );
  9129. setLineCap( material.linecap );
  9130. setLineJoin( material.linejoin );
  9131. if ( material.vertexColors !== THREE.VertexColors ) {
  9132. setStrokeStyle( material.color.getStyle() );
  9133. } else {
  9134. var colorStyle1 = element.vertexColors[0].getStyle();
  9135. var colorStyle2 = element.vertexColors[1].getStyle();
  9136. if ( colorStyle1 === colorStyle2 ) {
  9137. setStrokeStyle( colorStyle1 );
  9138. } else {
  9139. try {
  9140. var grad = _context.createLinearGradient(
  9141. v1.positionScreen.x,
  9142. v1.positionScreen.y,
  9143. v2.positionScreen.x,
  9144. v2.positionScreen.y
  9145. );
  9146. grad.addColorStop( 0, colorStyle1 );
  9147. grad.addColorStop( 1, colorStyle2 );
  9148. } catch ( exception ) {
  9149. grad = colorStyle1;
  9150. }
  9151. setStrokeStyle( grad );
  9152. }
  9153. }
  9154. _context.stroke();
  9155. _elemBox.expandByScalar( material.linewidth * 2 );
  9156. } else if ( material instanceof THREE.LineDashedMaterial ) {
  9157. setLineWidth( material.linewidth );
  9158. setLineCap( material.linecap );
  9159. setLineJoin( material.linejoin );
  9160. setStrokeStyle( material.color.getStyle() );
  9161. setDashAndGap( material.dashSize, material.gapSize );
  9162. _context.stroke();
  9163. _elemBox.expandByScalar( material.linewidth * 2 );
  9164. setDashAndGap( null, null );
  9165. }
  9166. }
  9167. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material ) {
  9168. _this.info.render.vertices += 3;
  9169. _this.info.render.faces ++;
  9170. setOpacity( material.opacity );
  9171. setBlending( material.blending );
  9172. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9173. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9174. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9175. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  9176. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null ) {
  9177. _diffuseColor.copy( material.color );
  9178. _emissiveColor.copy( material.emissive );
  9179. if ( material.vertexColors === THREE.FaceColors ) {
  9180. _diffuseColor.multiply( element.color );
  9181. }
  9182. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  9183. _color1.copy( _ambientLight );
  9184. _color2.copy( _ambientLight );
  9185. _color3.copy( _ambientLight );
  9186. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9187. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9188. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color3 );
  9189. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9190. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9191. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9192. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9193. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9194. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9195. } else {
  9196. _color.copy( _ambientLight );
  9197. calculateLight( element.centroidModel, element.normalModel, _color );
  9198. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9199. material.wireframe === true
  9200. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9201. : fillPath( _color );
  9202. }
  9203. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9204. if ( material.map !== null ) {
  9205. if ( material.map.mapping instanceof THREE.UVMapping ) {
  9206. _uvs = element.uvs[ 0 ];
  9207. 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 );
  9208. }
  9209. } else if ( material.envMap !== null ) {
  9210. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  9211. _vector3.copy( element.vertexNormalsModelView[ uv1 ] );
  9212. _uv1x = 0.5 * _vector3.x + 0.5;
  9213. _uv1y = 0.5 * _vector3.y + 0.5;
  9214. _vector3.copy( element.vertexNormalsModelView[ uv2 ] );
  9215. _uv2x = 0.5 * _vector3.x + 0.5;
  9216. _uv2y = 0.5 * _vector3.y + 0.5;
  9217. _vector3.copy( element.vertexNormalsModelView[ uv3 ] );
  9218. _uv3x = 0.5 * _vector3.x + 0.5;
  9219. _uv3y = 0.5 * _vector3.y + 0.5;
  9220. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  9221. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  9222. }*/
  9223. } else {
  9224. _color.copy( material.color );
  9225. if ( material.vertexColors === THREE.FaceColors ) {
  9226. _color.multiply( element.color );
  9227. }
  9228. material.wireframe === true
  9229. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9230. : fillPath( _color );
  9231. }
  9232. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9233. _near = _camera.near;
  9234. _far = _camera.far;
  9235. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9236. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9237. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9238. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9239. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9240. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9241. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9242. var normal;
  9243. if ( material.shading == THREE.FlatShading ) {
  9244. normal = element.normalModelView;
  9245. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9246. material.wireframe === true
  9247. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9248. : fillPath( _color );
  9249. } else if ( material.shading == THREE.SmoothShading ) {
  9250. normal = element.vertexNormalsModelView[ uv1 ];
  9251. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9252. normal = element.vertexNormalsModelView[ uv2 ];
  9253. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9254. normal = element.vertexNormalsModelView[ uv3 ];
  9255. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9256. _color4.addColors( _color2, _color3 ).multiplyScalar( 0.5 );
  9257. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9258. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  9259. }
  9260. }
  9261. }
  9262. function renderFace4( v1, v2, v3, v4, v5, v6, element, material ) {
  9263. _this.info.render.vertices += 4;
  9264. _this.info.render.faces ++;
  9265. setOpacity( material.opacity );
  9266. setBlending( material.blending );
  9267. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  9268. // Let renderFace3() handle this
  9269. renderFace3( v1, v2, v4, 0, 1, 3, element, material );
  9270. renderFace3( v5, v3, v6, 1, 2, 3, element, material );
  9271. return;
  9272. }
  9273. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  9274. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  9275. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  9276. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  9277. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  9278. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  9279. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  9280. _diffuseColor.copy( material.color );
  9281. _emissiveColor.copy( material.emissive );
  9282. if ( material.vertexColors === THREE.FaceColors ) {
  9283. _diffuseColor.multiply( element.color );
  9284. }
  9285. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  9286. _color1.copy( _ambientLight );
  9287. _color2.copy( _ambientLight );
  9288. _color3.copy( _ambientLight );
  9289. _color4.copy( _ambientLight );
  9290. calculateLight( element.v1.positionWorld, element.vertexNormalsModel[ 0 ], _color1 );
  9291. calculateLight( element.v2.positionWorld, element.vertexNormalsModel[ 1 ], _color2 );
  9292. calculateLight( element.v4.positionWorld, element.vertexNormalsModel[ 3 ], _color3 );
  9293. calculateLight( element.v3.positionWorld, element.vertexNormalsModel[ 2 ], _color4 );
  9294. _color1.multiply( _diffuseColor ).add( _emissiveColor );
  9295. _color2.multiply( _diffuseColor ).add( _emissiveColor );
  9296. _color3.multiply( _diffuseColor ).add( _emissiveColor );
  9297. _color4.multiply( _diffuseColor ).add( _emissiveColor );
  9298. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9299. // TODO: UVs are incorrect, v4->v3?
  9300. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9301. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9302. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9303. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9304. } else {
  9305. _color.copy( _ambientLight );
  9306. calculateLight( element.centroidModel, element.normalModel, _color );
  9307. _color.multiply( _diffuseColor ).add( _emissiveColor );
  9308. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9309. material.wireframe === true
  9310. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9311. : fillPath( _color );
  9312. }
  9313. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  9314. _color.copy( material.color );
  9315. if ( material.vertexColors === THREE.FaceColors ) {
  9316. _color.multiply( element.color );
  9317. }
  9318. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9319. material.wireframe === true
  9320. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9321. : fillPath( _color );
  9322. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  9323. var normal;
  9324. if ( material.shading == THREE.FlatShading ) {
  9325. normal = element.normalModelView;
  9326. _color.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9327. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  9328. material.wireframe === true
  9329. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  9330. : fillPath( _color );
  9331. } else if ( material.shading == THREE.SmoothShading ) {
  9332. normal = element.vertexNormalsModelView[ 0 ];
  9333. _color1.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9334. normal = element.vertexNormalsModelView[ 1 ];
  9335. _color2.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9336. normal = element.vertexNormalsModelView[ 3 ];
  9337. _color3.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9338. normal = element.vertexNormalsModelView[ 2 ];
  9339. _color4.setRGB( normal.x, normal.y, normal.z ).multiplyScalar( 0.5 ).addScalar( 0.5 );
  9340. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9341. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9342. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9343. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9344. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9345. }
  9346. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  9347. _near = _camera.near;
  9348. _far = _camera.far;
  9349. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z * v1.positionScreen.w, _near, _far );
  9350. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z * v2.positionScreen.w, _near, _far );
  9351. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z * v4.positionScreen.w, _near, _far );
  9352. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z * v3.positionScreen.w, _near, _far );
  9353. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  9354. // TODO: UVs are incorrect, v4->v3?
  9355. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  9356. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  9357. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  9358. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  9359. }
  9360. }
  9361. //
  9362. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  9363. _context.beginPath();
  9364. _context.moveTo( x0, y0 );
  9365. _context.lineTo( x1, y1 );
  9366. _context.lineTo( x2, y2 );
  9367. _context.closePath();
  9368. }
  9369. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  9370. _context.beginPath();
  9371. _context.moveTo( x0, y0 );
  9372. _context.lineTo( x1, y1 );
  9373. _context.lineTo( x2, y2 );
  9374. _context.lineTo( x3, y3 );
  9375. _context.closePath();
  9376. }
  9377. function strokePath( color, linewidth, linecap, linejoin ) {
  9378. setLineWidth( linewidth );
  9379. setLineCap( linecap );
  9380. setLineJoin( linejoin );
  9381. setStrokeStyle( color.getStyle() );
  9382. _context.stroke();
  9383. _elemBox.expandByScalar( linewidth * 2 );
  9384. }
  9385. function fillPath( color ) {
  9386. setFillStyle( color.getStyle() );
  9387. _context.fill();
  9388. }
  9389. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  9390. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  9391. if ( texture.needsUpdate === true ) {
  9392. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  9393. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  9394. _patterns[ texture.id ] = _context.createPattern(
  9395. texture.image, repeatX === true && repeatY === true
  9396. ? 'repeat'
  9397. : repeatX === true && repeatY === false
  9398. ? 'repeat-x'
  9399. : repeatX === false && repeatY === true
  9400. ? 'repeat-y'
  9401. : 'no-repeat'
  9402. );
  9403. texture.needsUpdate = false;
  9404. }
  9405. _patterns[ texture.id ] === undefined
  9406. ? setFillStyle( 'rgba(0,0,0,1)' )
  9407. : setFillStyle( _patterns[ texture.id ] );
  9408. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9409. var a, b, c, d, e, f, det, idet,
  9410. offsetX = texture.offset.x / texture.repeat.x,
  9411. offsetY = texture.offset.y / texture.repeat.y,
  9412. width = texture.image.width * texture.repeat.x,
  9413. height = texture.image.height * texture.repeat.y;
  9414. u0 = ( u0 + offsetX ) * width;
  9415. v0 = ( 1.0 - v0 + offsetY ) * height;
  9416. u1 = ( u1 + offsetX ) * width;
  9417. v1 = ( 1.0 - v1 + offsetY ) * height;
  9418. u2 = ( u2 + offsetX ) * width;
  9419. v2 = ( 1.0 - v2 + offsetY ) * height;
  9420. x1 -= x0; y1 -= y0;
  9421. x2 -= x0; y2 -= y0;
  9422. u1 -= u0; v1 -= v0;
  9423. u2 -= u0; v2 -= v0;
  9424. det = u1 * v2 - u2 * v1;
  9425. if ( det === 0 ) {
  9426. if ( _imagedatas[ texture.id ] === undefined ) {
  9427. var canvas = document.createElement( 'canvas' )
  9428. canvas.width = texture.image.width;
  9429. canvas.height = texture.image.height;
  9430. var context = canvas.getContext( '2d' );
  9431. context.drawImage( texture.image, 0, 0 );
  9432. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  9433. }
  9434. var data = _imagedatas[ texture.id ];
  9435. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  9436. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  9437. fillPath( _color );
  9438. return;
  9439. }
  9440. idet = 1 / det;
  9441. a = ( v2 * x1 - v1 * x2 ) * idet;
  9442. b = ( v2 * y1 - v1 * y2 ) * idet;
  9443. c = ( u1 * x2 - u2 * x1 ) * idet;
  9444. d = ( u1 * y2 - u2 * y1 ) * idet;
  9445. e = x0 - a * u0 - c * v0;
  9446. f = y0 - b * u0 - d * v0;
  9447. _context.save();
  9448. _context.transform( a, b, c, d, e, f );
  9449. _context.fill();
  9450. _context.restore();
  9451. }
  9452. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  9453. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  9454. var a, b, c, d, e, f, det, idet,
  9455. width = image.width - 1,
  9456. height = image.height - 1;
  9457. u0 *= width; v0 *= height;
  9458. u1 *= width; v1 *= height;
  9459. u2 *= width; v2 *= height;
  9460. x1 -= x0; y1 -= y0;
  9461. x2 -= x0; y2 -= y0;
  9462. u1 -= u0; v1 -= v0;
  9463. u2 -= u0; v2 -= v0;
  9464. det = u1 * v2 - u2 * v1;
  9465. idet = 1 / det;
  9466. a = ( v2 * x1 - v1 * x2 ) * idet;
  9467. b = ( v2 * y1 - v1 * y2 ) * idet;
  9468. c = ( u1 * x2 - u2 * x1 ) * idet;
  9469. d = ( u1 * y2 - u2 * y1 ) * idet;
  9470. e = x0 - a * u0 - c * v0;
  9471. f = y0 - b * u0 - d * v0;
  9472. _context.save();
  9473. _context.transform( a, b, c, d, e, f );
  9474. _context.clip();
  9475. _context.drawImage( image, 0, 0 );
  9476. _context.restore();
  9477. }
  9478. function getGradientTexture( color1, color2, color3, color4 ) {
  9479. // http://mrdoob.com/blog/post/710
  9480. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  9481. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  9482. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  9483. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  9484. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  9485. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  9486. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  9487. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  9488. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  9489. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  9490. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  9491. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  9492. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  9493. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  9494. return _gradientMap;
  9495. }
  9496. // Hide anti-alias gaps
  9497. function expand( v1, v2, pixels ) {
  9498. var x = v2.x - v1.x, y = v2.y - v1.y,
  9499. det = x * x + y * y, idet;
  9500. if ( det === 0 ) return;
  9501. idet = pixels / Math.sqrt( det );
  9502. x *= idet; y *= idet;
  9503. v2.x += x; v2.y += y;
  9504. v1.x -= x; v1.y -= y;
  9505. }
  9506. // Context cached methods.
  9507. function setOpacity( value ) {
  9508. if ( _contextGlobalAlpha !== value ) {
  9509. _context.globalAlpha = value;
  9510. _contextGlobalAlpha = value;
  9511. }
  9512. }
  9513. function setBlending( value ) {
  9514. if ( _contextGlobalCompositeOperation !== value ) {
  9515. if ( value === THREE.NormalBlending ) {
  9516. _context.globalCompositeOperation = 'source-over';
  9517. } else if ( value === THREE.AdditiveBlending ) {
  9518. _context.globalCompositeOperation = 'lighter';
  9519. } else if ( value === THREE.SubtractiveBlending ) {
  9520. _context.globalCompositeOperation = 'darker';
  9521. }
  9522. _contextGlobalCompositeOperation = value;
  9523. }
  9524. }
  9525. function setLineWidth( value ) {
  9526. if ( _contextLineWidth !== value ) {
  9527. _context.lineWidth = value;
  9528. _contextLineWidth = value;
  9529. }
  9530. }
  9531. function setLineCap( value ) {
  9532. // "butt", "round", "square"
  9533. if ( _contextLineCap !== value ) {
  9534. _context.lineCap = value;
  9535. _contextLineCap = value;
  9536. }
  9537. }
  9538. function setLineJoin( value ) {
  9539. // "round", "bevel", "miter"
  9540. if ( _contextLineJoin !== value ) {
  9541. _context.lineJoin = value;
  9542. _contextLineJoin = value;
  9543. }
  9544. }
  9545. function setStrokeStyle( value ) {
  9546. if ( _contextStrokeStyle !== value ) {
  9547. _context.strokeStyle = value;
  9548. _contextStrokeStyle = value;
  9549. }
  9550. }
  9551. function setFillStyle( value ) {
  9552. if ( _contextFillStyle !== value ) {
  9553. _context.fillStyle = value;
  9554. _contextFillStyle = value;
  9555. }
  9556. }
  9557. function setDashAndGap( dashSizeValue, gapSizeValue ) {
  9558. if ( _contextDashSize !== dashSizeValue || _contextGapSize !== gapSizeValue ) {
  9559. _context.setLineDash( [ dashSizeValue, gapSizeValue ] );
  9560. _contextDashSize = dashSizeValue;
  9561. _contextGapSize = gapSizeValue;
  9562. }
  9563. }
  9564. };
  9565. /**
  9566. * @author alteredq / http://alteredqualia.com/
  9567. * @author mrdoob / http://mrdoob.com/
  9568. * @author mikael emtinger / http://gomo.se/
  9569. */
  9570. THREE.ShaderChunk = {
  9571. // FOG
  9572. fog_pars_fragment: [
  9573. "#ifdef USE_FOG",
  9574. "uniform vec3 fogColor;",
  9575. "#ifdef FOG_EXP2",
  9576. "uniform float fogDensity;",
  9577. "#else",
  9578. "uniform float fogNear;",
  9579. "uniform float fogFar;",
  9580. "#endif",
  9581. "#endif"
  9582. ].join("\n"),
  9583. fog_fragment: [
  9584. "#ifdef USE_FOG",
  9585. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9586. "#ifdef FOG_EXP2",
  9587. "const float LOG2 = 1.442695;",
  9588. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  9589. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  9590. "#else",
  9591. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  9592. "#endif",
  9593. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  9594. "#endif"
  9595. ].join("\n"),
  9596. // ENVIRONMENT MAP
  9597. envmap_pars_fragment: [
  9598. "#ifdef USE_ENVMAP",
  9599. "uniform float reflectivity;",
  9600. "uniform samplerCube envMap;",
  9601. "uniform float flipEnvMap;",
  9602. "uniform int combine;",
  9603. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9604. "uniform bool useRefract;",
  9605. "uniform float refractionRatio;",
  9606. "#else",
  9607. "varying vec3 vReflect;",
  9608. "#endif",
  9609. "#endif"
  9610. ].join("\n"),
  9611. envmap_fragment: [
  9612. "#ifdef USE_ENVMAP",
  9613. "vec3 reflectVec;",
  9614. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  9615. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  9616. "if ( useRefract ) {",
  9617. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  9618. "} else { ",
  9619. "reflectVec = reflect( cameraToVertex, normal );",
  9620. "}",
  9621. "#else",
  9622. "reflectVec = vReflect;",
  9623. "#endif",
  9624. "#ifdef DOUBLE_SIDED",
  9625. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9626. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9627. "#else",
  9628. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  9629. "#endif",
  9630. "#ifdef GAMMA_INPUT",
  9631. "cubeColor.xyz *= cubeColor.xyz;",
  9632. "#endif",
  9633. "if ( combine == 1 ) {",
  9634. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  9635. "} else if ( combine == 2 ) {",
  9636. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  9637. "} else {",
  9638. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  9639. "}",
  9640. "#endif"
  9641. ].join("\n"),
  9642. envmap_pars_vertex: [
  9643. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9644. "varying vec3 vReflect;",
  9645. "uniform float refractionRatio;",
  9646. "uniform bool useRefract;",
  9647. "#endif"
  9648. ].join("\n"),
  9649. worldpos_vertex : [
  9650. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  9651. "#ifdef USE_SKINNING",
  9652. "vec4 worldPosition = modelMatrix * skinned;",
  9653. "#endif",
  9654. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9655. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  9656. "#endif",
  9657. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  9658. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  9659. "#endif",
  9660. "#endif"
  9661. ].join("\n"),
  9662. envmap_vertex : [
  9663. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  9664. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  9665. "worldNormal = normalize( worldNormal );",
  9666. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  9667. "if ( useRefract ) {",
  9668. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  9669. "} else {",
  9670. "vReflect = reflect( cameraToVertex, worldNormal );",
  9671. "}",
  9672. "#endif"
  9673. ].join("\n"),
  9674. // COLOR MAP (particles)
  9675. map_particle_pars_fragment: [
  9676. "#ifdef USE_MAP",
  9677. "uniform sampler2D map;",
  9678. "#endif"
  9679. ].join("\n"),
  9680. map_particle_fragment: [
  9681. "#ifdef USE_MAP",
  9682. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  9683. "#endif"
  9684. ].join("\n"),
  9685. // COLOR MAP (triangles)
  9686. map_pars_vertex: [
  9687. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9688. "varying vec2 vUv;",
  9689. "uniform vec4 offsetRepeat;",
  9690. "#endif"
  9691. ].join("\n"),
  9692. map_pars_fragment: [
  9693. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9694. "varying vec2 vUv;",
  9695. "#endif",
  9696. "#ifdef USE_MAP",
  9697. "uniform sampler2D map;",
  9698. "#endif"
  9699. ].join("\n"),
  9700. map_vertex: [
  9701. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  9702. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  9703. "#endif"
  9704. ].join("\n"),
  9705. map_fragment: [
  9706. "#ifdef USE_MAP",
  9707. "vec4 texelColor = texture2D( map, vUv );",
  9708. "#ifdef GAMMA_INPUT",
  9709. "texelColor.xyz *= texelColor.xyz;",
  9710. "#endif",
  9711. "gl_FragColor = gl_FragColor * texelColor;",
  9712. "#endif"
  9713. ].join("\n"),
  9714. // LIGHT MAP
  9715. lightmap_pars_fragment: [
  9716. "#ifdef USE_LIGHTMAP",
  9717. "varying vec2 vUv2;",
  9718. "uniform sampler2D lightMap;",
  9719. "#endif"
  9720. ].join("\n"),
  9721. lightmap_pars_vertex: [
  9722. "#ifdef USE_LIGHTMAP",
  9723. "varying vec2 vUv2;",
  9724. "#endif"
  9725. ].join("\n"),
  9726. lightmap_fragment: [
  9727. "#ifdef USE_LIGHTMAP",
  9728. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  9729. "#endif"
  9730. ].join("\n"),
  9731. lightmap_vertex: [
  9732. "#ifdef USE_LIGHTMAP",
  9733. "vUv2 = uv2;",
  9734. "#endif"
  9735. ].join("\n"),
  9736. // BUMP MAP
  9737. bumpmap_pars_fragment: [
  9738. "#ifdef USE_BUMPMAP",
  9739. "uniform sampler2D bumpMap;",
  9740. "uniform float bumpScale;",
  9741. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  9742. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  9743. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  9744. "vec2 dHdxy_fwd() {",
  9745. "vec2 dSTdx = dFdx( vUv );",
  9746. "vec2 dSTdy = dFdy( vUv );",
  9747. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  9748. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  9749. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  9750. "return vec2( dBx, dBy );",
  9751. "}",
  9752. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  9753. "vec3 vSigmaX = dFdx( surf_pos );",
  9754. "vec3 vSigmaY = dFdy( surf_pos );",
  9755. "vec3 vN = surf_norm;", // normalized
  9756. "vec3 R1 = cross( vSigmaY, vN );",
  9757. "vec3 R2 = cross( vN, vSigmaX );",
  9758. "float fDet = dot( vSigmaX, R1 );",
  9759. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  9760. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  9761. "}",
  9762. "#endif"
  9763. ].join("\n"),
  9764. // NORMAL MAP
  9765. normalmap_pars_fragment: [
  9766. "#ifdef USE_NORMALMAP",
  9767. "uniform sampler2D normalMap;",
  9768. "uniform vec2 normalScale;",
  9769. // Per-Pixel Tangent Space Normal Mapping
  9770. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  9771. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  9772. "vec3 q0 = dFdx( eye_pos.xyz );",
  9773. "vec3 q1 = dFdy( eye_pos.xyz );",
  9774. "vec2 st0 = dFdx( vUv.st );",
  9775. "vec2 st1 = dFdy( vUv.st );",
  9776. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  9777. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  9778. "vec3 N = normalize( surf_norm );",
  9779. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  9780. "mapN.xy = normalScale * mapN.xy;",
  9781. "mat3 tsn = mat3( S, T, N );",
  9782. "return normalize( tsn * mapN );",
  9783. "}",
  9784. "#endif"
  9785. ].join("\n"),
  9786. // SPECULAR MAP
  9787. specularmap_pars_fragment: [
  9788. "#ifdef USE_SPECULARMAP",
  9789. "uniform sampler2D specularMap;",
  9790. "#endif"
  9791. ].join("\n"),
  9792. specularmap_fragment: [
  9793. "float specularStrength;",
  9794. "#ifdef USE_SPECULARMAP",
  9795. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  9796. "specularStrength = texelSpecular.r;",
  9797. "#else",
  9798. "specularStrength = 1.0;",
  9799. "#endif"
  9800. ].join("\n"),
  9801. // LIGHTS LAMBERT
  9802. lights_lambert_pars_vertex: [
  9803. "uniform vec3 ambient;",
  9804. "uniform vec3 diffuse;",
  9805. "uniform vec3 emissive;",
  9806. "uniform vec3 ambientLightColor;",
  9807. "#if MAX_DIR_LIGHTS > 0",
  9808. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9809. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9810. "#endif",
  9811. "#if MAX_HEMI_LIGHTS > 0",
  9812. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9813. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9814. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9815. "#endif",
  9816. "#if MAX_POINT_LIGHTS > 0",
  9817. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9818. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9819. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9820. "#endif",
  9821. "#if MAX_SPOT_LIGHTS > 0",
  9822. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9823. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9824. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9825. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9826. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9827. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9828. "#endif",
  9829. "#ifdef WRAP_AROUND",
  9830. "uniform vec3 wrapRGB;",
  9831. "#endif"
  9832. ].join("\n"),
  9833. lights_lambert_vertex: [
  9834. "vLightFront = vec3( 0.0 );",
  9835. "#ifdef DOUBLE_SIDED",
  9836. "vLightBack = vec3( 0.0 );",
  9837. "#endif",
  9838. "transformedNormal = normalize( transformedNormal );",
  9839. "#if MAX_DIR_LIGHTS > 0",
  9840. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9841. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9842. "vec3 dirVector = normalize( lDirection.xyz );",
  9843. "float dotProduct = dot( transformedNormal, dirVector );",
  9844. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9845. "#ifdef DOUBLE_SIDED",
  9846. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9847. "#ifdef WRAP_AROUND",
  9848. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9849. "#endif",
  9850. "#endif",
  9851. "#ifdef WRAP_AROUND",
  9852. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9853. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  9854. "#ifdef DOUBLE_SIDED",
  9855. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  9856. "#endif",
  9857. "#endif",
  9858. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  9859. "#ifdef DOUBLE_SIDED",
  9860. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  9861. "#endif",
  9862. "}",
  9863. "#endif",
  9864. "#if MAX_POINT_LIGHTS > 0",
  9865. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9866. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9867. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9868. "float lDistance = 1.0;",
  9869. "if ( pointLightDistance[ i ] > 0.0 )",
  9870. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9871. "lVector = normalize( lVector );",
  9872. "float dotProduct = dot( transformedNormal, lVector );",
  9873. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9874. "#ifdef DOUBLE_SIDED",
  9875. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9876. "#ifdef WRAP_AROUND",
  9877. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9878. "#endif",
  9879. "#endif",
  9880. "#ifdef WRAP_AROUND",
  9881. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9882. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  9883. "#ifdef DOUBLE_SIDED",
  9884. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  9885. "#endif",
  9886. "#endif",
  9887. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  9888. "#ifdef DOUBLE_SIDED",
  9889. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  9890. "#endif",
  9891. "}",
  9892. "#endif",
  9893. "#if MAX_SPOT_LIGHTS > 0",
  9894. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9895. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9896. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9897. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  9898. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9899. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9900. "float lDistance = 1.0;",
  9901. "if ( spotLightDistance[ i ] > 0.0 )",
  9902. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9903. "lVector = normalize( lVector );",
  9904. "float dotProduct = dot( transformedNormal, lVector );",
  9905. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  9906. "#ifdef DOUBLE_SIDED",
  9907. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  9908. "#ifdef WRAP_AROUND",
  9909. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  9910. "#endif",
  9911. "#endif",
  9912. "#ifdef WRAP_AROUND",
  9913. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9914. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9915. "#ifdef DOUBLE_SIDED",
  9916. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9917. "#endif",
  9918. "#endif",
  9919. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9920. "#ifdef DOUBLE_SIDED",
  9921. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9922. "#endif",
  9923. "}",
  9924. "}",
  9925. "#endif",
  9926. "#if MAX_HEMI_LIGHTS > 0",
  9927. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9928. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9929. "vec3 lVector = normalize( lDirection.xyz );",
  9930. "float dotProduct = dot( transformedNormal, lVector );",
  9931. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9932. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9933. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9934. "#ifdef DOUBLE_SIDED",
  9935. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9936. "#endif",
  9937. "}",
  9938. "#endif",
  9939. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9940. "#ifdef DOUBLE_SIDED",
  9941. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9942. "#endif"
  9943. ].join("\n"),
  9944. // LIGHTS PHONG
  9945. lights_phong_pars_vertex: [
  9946. "#ifndef PHONG_PER_PIXEL",
  9947. "#if MAX_POINT_LIGHTS > 0",
  9948. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9949. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9950. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9951. "#endif",
  9952. "#if MAX_SPOT_LIGHTS > 0",
  9953. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9954. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9955. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9956. "#endif",
  9957. "#endif",
  9958. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9959. "varying vec3 vWorldPosition;",
  9960. "#endif"
  9961. ].join("\n"),
  9962. lights_phong_vertex: [
  9963. "#ifndef PHONG_PER_PIXEL",
  9964. "#if MAX_POINT_LIGHTS > 0",
  9965. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9966. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9967. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9968. "float lDistance = 1.0;",
  9969. "if ( pointLightDistance[ i ] > 0.0 )",
  9970. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9971. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9972. "}",
  9973. "#endif",
  9974. "#if MAX_SPOT_LIGHTS > 0",
  9975. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9976. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9977. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9978. "float lDistance = 1.0;",
  9979. "if ( spotLightDistance[ i ] > 0.0 )",
  9980. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9981. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9982. "}",
  9983. "#endif",
  9984. "#endif",
  9985. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9986. "vWorldPosition = worldPosition.xyz;",
  9987. "#endif"
  9988. ].join("\n"),
  9989. lights_phong_pars_fragment: [
  9990. "uniform vec3 ambientLightColor;",
  9991. "#if MAX_DIR_LIGHTS > 0",
  9992. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9993. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9994. "#endif",
  9995. "#if MAX_HEMI_LIGHTS > 0",
  9996. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9997. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9998. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9999. "#endif",
  10000. "#if MAX_POINT_LIGHTS > 0",
  10001. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  10002. "#ifdef PHONG_PER_PIXEL",
  10003. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  10004. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  10005. "#else",
  10006. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  10007. "#endif",
  10008. "#endif",
  10009. "#if MAX_SPOT_LIGHTS > 0",
  10010. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  10011. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  10012. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  10013. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  10014. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  10015. "#ifdef PHONG_PER_PIXEL",
  10016. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  10017. "#else",
  10018. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  10019. "#endif",
  10020. "#endif",
  10021. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  10022. "varying vec3 vWorldPosition;",
  10023. "#endif",
  10024. "#ifdef WRAP_AROUND",
  10025. "uniform vec3 wrapRGB;",
  10026. "#endif",
  10027. "varying vec3 vViewPosition;",
  10028. "varying vec3 vNormal;"
  10029. ].join("\n"),
  10030. lights_phong_fragment: [
  10031. "vec3 normal = normalize( vNormal );",
  10032. "vec3 viewPosition = normalize( vViewPosition );",
  10033. "#ifdef DOUBLE_SIDED",
  10034. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  10035. "#endif",
  10036. "#ifdef USE_NORMALMAP",
  10037. "normal = perturbNormal2Arb( -vViewPosition, normal );",
  10038. "#elif defined( USE_BUMPMAP )",
  10039. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  10040. "#endif",
  10041. "#if MAX_POINT_LIGHTS > 0",
  10042. "vec3 pointDiffuse = vec3( 0.0 );",
  10043. "vec3 pointSpecular = vec3( 0.0 );",
  10044. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  10045. "#ifdef PHONG_PER_PIXEL",
  10046. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  10047. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10048. "float lDistance = 1.0;",
  10049. "if ( pointLightDistance[ i ] > 0.0 )",
  10050. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  10051. "lVector = normalize( lVector );",
  10052. "#else",
  10053. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  10054. "float lDistance = vPointLight[ i ].w;",
  10055. "#endif",
  10056. // diffuse
  10057. "float dotProduct = dot( normal, lVector );",
  10058. "#ifdef WRAP_AROUND",
  10059. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  10060. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10061. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  10062. "#else",
  10063. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  10064. "#endif",
  10065. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  10066. // specular
  10067. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  10068. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  10069. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  10070. "#ifdef PHYSICALLY_BASED_SHADING",
  10071. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10072. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10073. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  10074. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  10075. "#else",
  10076. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  10077. "#endif",
  10078. "}",
  10079. "#endif",
  10080. "#if MAX_SPOT_LIGHTS > 0",
  10081. "vec3 spotDiffuse = vec3( 0.0 );",
  10082. "vec3 spotSpecular = vec3( 0.0 );",
  10083. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  10084. "#ifdef PHONG_PER_PIXEL",
  10085. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  10086. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  10087. "float lDistance = 1.0;",
  10088. "if ( spotLightDistance[ i ] > 0.0 )",
  10089. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  10090. "lVector = normalize( lVector );",
  10091. "#else",
  10092. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  10093. "float lDistance = vSpotLight[ i ].w;",
  10094. "#endif",
  10095. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  10096. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  10097. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  10098. // diffuse
  10099. "float dotProduct = dot( normal, lVector );",
  10100. "#ifdef WRAP_AROUND",
  10101. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  10102. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10103. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  10104. "#else",
  10105. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  10106. "#endif",
  10107. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  10108. // specular
  10109. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  10110. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  10111. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  10112. "#ifdef PHYSICALLY_BASED_SHADING",
  10113. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10114. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10115. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  10116. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  10117. "#else",
  10118. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  10119. "#endif",
  10120. "}",
  10121. "}",
  10122. "#endif",
  10123. "#if MAX_DIR_LIGHTS > 0",
  10124. "vec3 dirDiffuse = vec3( 0.0 );",
  10125. "vec3 dirSpecular = vec3( 0.0 );" ,
  10126. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  10127. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  10128. "vec3 dirVector = normalize( lDirection.xyz );",
  10129. // diffuse
  10130. "float dotProduct = dot( normal, dirVector );",
  10131. "#ifdef WRAP_AROUND",
  10132. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  10133. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  10134. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  10135. "#else",
  10136. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  10137. "#endif",
  10138. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  10139. // specular
  10140. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  10141. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  10142. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  10143. "#ifdef PHYSICALLY_BASED_SHADING",
  10144. /*
  10145. // fresnel term from skin shader
  10146. "const float F0 = 0.128;",
  10147. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  10148. "float exponential = pow( base, 5.0 );",
  10149. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  10150. */
  10151. /*
  10152. // fresnel term from fresnel shader
  10153. "const float mFresnelBias = 0.08;",
  10154. "const float mFresnelScale = 0.3;",
  10155. "const float mFresnelPower = 5.0;",
  10156. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  10157. */
  10158. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10159. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10160. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  10161. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  10162. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  10163. "#else",
  10164. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  10165. "#endif",
  10166. "}",
  10167. "#endif",
  10168. "#if MAX_HEMI_LIGHTS > 0",
  10169. "vec3 hemiDiffuse = vec3( 0.0 );",
  10170. "vec3 hemiSpecular = vec3( 0.0 );" ,
  10171. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  10172. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  10173. "vec3 lVector = normalize( lDirection.xyz );",
  10174. // diffuse
  10175. "float dotProduct = dot( normal, lVector );",
  10176. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  10177. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  10178. "hemiDiffuse += diffuse * hemiColor;",
  10179. // specular (sky light)
  10180. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  10181. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  10182. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  10183. // specular (ground light)
  10184. "vec3 lVectorGround = -lVector;",
  10185. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  10186. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  10187. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  10188. "#ifdef PHYSICALLY_BASED_SHADING",
  10189. "float dotProductGround = dot( normal, lVectorGround );",
  10190. // 2.0 => 2.0001 is hack to work around ANGLE bug
  10191. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  10192. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  10193. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  10194. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  10195. "#else",
  10196. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  10197. "#endif",
  10198. "}",
  10199. "#endif",
  10200. "vec3 totalDiffuse = vec3( 0.0 );",
  10201. "vec3 totalSpecular = vec3( 0.0 );",
  10202. "#if MAX_DIR_LIGHTS > 0",
  10203. "totalDiffuse += dirDiffuse;",
  10204. "totalSpecular += dirSpecular;",
  10205. "#endif",
  10206. "#if MAX_HEMI_LIGHTS > 0",
  10207. "totalDiffuse += hemiDiffuse;",
  10208. "totalSpecular += hemiSpecular;",
  10209. "#endif",
  10210. "#if MAX_POINT_LIGHTS > 0",
  10211. "totalDiffuse += pointDiffuse;",
  10212. "totalSpecular += pointSpecular;",
  10213. "#endif",
  10214. "#if MAX_SPOT_LIGHTS > 0",
  10215. "totalDiffuse += spotDiffuse;",
  10216. "totalSpecular += spotSpecular;",
  10217. "#endif",
  10218. "#ifdef METAL",
  10219. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  10220. "#else",
  10221. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  10222. "#endif"
  10223. ].join("\n"),
  10224. // VERTEX COLORS
  10225. color_pars_fragment: [
  10226. "#ifdef USE_COLOR",
  10227. "varying vec3 vColor;",
  10228. "#endif"
  10229. ].join("\n"),
  10230. color_fragment: [
  10231. "#ifdef USE_COLOR",
  10232. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  10233. "#endif"
  10234. ].join("\n"),
  10235. color_pars_vertex: [
  10236. "#ifdef USE_COLOR",
  10237. "varying vec3 vColor;",
  10238. "#endif"
  10239. ].join("\n"),
  10240. color_vertex: [
  10241. "#ifdef USE_COLOR",
  10242. "#ifdef GAMMA_INPUT",
  10243. "vColor = color * color;",
  10244. "#else",
  10245. "vColor = color;",
  10246. "#endif",
  10247. "#endif"
  10248. ].join("\n"),
  10249. // SKINNING
  10250. skinning_pars_vertex: [
  10251. "#ifdef USE_SKINNING",
  10252. "#ifdef BONE_TEXTURE",
  10253. "uniform sampler2D boneTexture;",
  10254. "mat4 getBoneMatrix( const in float i ) {",
  10255. "float j = i * 4.0;",
  10256. "float x = mod( j, N_BONE_PIXEL_X );",
  10257. "float y = floor( j / N_BONE_PIXEL_X );",
  10258. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  10259. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  10260. "y = dy * ( y + 0.5 );",
  10261. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  10262. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  10263. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  10264. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  10265. "mat4 bone = mat4( v1, v2, v3, v4 );",
  10266. "return bone;",
  10267. "}",
  10268. "#else",
  10269. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  10270. "mat4 getBoneMatrix( const in float i ) {",
  10271. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  10272. "return bone;",
  10273. "}",
  10274. "#endif",
  10275. "#endif"
  10276. ].join("\n"),
  10277. skinbase_vertex: [
  10278. "#ifdef USE_SKINNING",
  10279. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  10280. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  10281. "#endif"
  10282. ].join("\n"),
  10283. skinning_vertex: [
  10284. "#ifdef USE_SKINNING",
  10285. "#ifdef USE_MORPHTARGETS",
  10286. "vec4 skinVertex = vec4( morphed, 1.0 );",
  10287. "#else",
  10288. "vec4 skinVertex = vec4( position, 1.0 );",
  10289. "#endif",
  10290. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  10291. "skinned += boneMatY * skinVertex * skinWeight.y;",
  10292. "#endif"
  10293. ].join("\n"),
  10294. // MORPHING
  10295. morphtarget_pars_vertex: [
  10296. "#ifdef USE_MORPHTARGETS",
  10297. "#ifndef USE_MORPHNORMALS",
  10298. "uniform float morphTargetInfluences[ 8 ];",
  10299. "#else",
  10300. "uniform float morphTargetInfluences[ 4 ];",
  10301. "#endif",
  10302. "#endif"
  10303. ].join("\n"),
  10304. morphtarget_vertex: [
  10305. "#ifdef USE_MORPHTARGETS",
  10306. "vec3 morphed = vec3( 0.0 );",
  10307. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  10308. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  10309. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  10310. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  10311. "#ifndef USE_MORPHNORMALS",
  10312. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  10313. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  10314. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  10315. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  10316. "#endif",
  10317. "morphed += position;",
  10318. "#endif"
  10319. ].join("\n"),
  10320. default_vertex : [
  10321. "vec4 mvPosition;",
  10322. "#ifdef USE_SKINNING",
  10323. "mvPosition = modelViewMatrix * skinned;",
  10324. "#endif",
  10325. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  10326. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  10327. "#endif",
  10328. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  10329. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10330. "#endif",
  10331. "gl_Position = projectionMatrix * mvPosition;"
  10332. ].join("\n"),
  10333. morphnormal_vertex: [
  10334. "#ifdef USE_MORPHNORMALS",
  10335. "vec3 morphedNormal = vec3( 0.0 );",
  10336. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  10337. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  10338. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  10339. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  10340. "morphedNormal += normal;",
  10341. "#endif"
  10342. ].join("\n"),
  10343. skinnormal_vertex: [
  10344. "#ifdef USE_SKINNING",
  10345. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  10346. "skinMatrix += skinWeight.y * boneMatY;",
  10347. "#ifdef USE_MORPHNORMALS",
  10348. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  10349. "#else",
  10350. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  10351. "#endif",
  10352. "#endif"
  10353. ].join("\n"),
  10354. defaultnormal_vertex: [
  10355. "vec3 objectNormal;",
  10356. "#ifdef USE_SKINNING",
  10357. "objectNormal = skinnedNormal.xyz;",
  10358. "#endif",
  10359. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  10360. "objectNormal = morphedNormal;",
  10361. "#endif",
  10362. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  10363. "objectNormal = normal;",
  10364. "#endif",
  10365. "#ifdef FLIP_SIDED",
  10366. "objectNormal = -objectNormal;",
  10367. "#endif",
  10368. "vec3 transformedNormal = normalMatrix * objectNormal;"
  10369. ].join("\n"),
  10370. // SHADOW MAP
  10371. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  10372. // http://spidergl.org/example.php?id=6
  10373. // http://fabiensanglard.net/shadowmapping
  10374. shadowmap_pars_fragment: [
  10375. "#ifdef USE_SHADOWMAP",
  10376. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  10377. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  10378. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  10379. "uniform float shadowBias[ MAX_SHADOWS ];",
  10380. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10381. "float unpackDepth( const in vec4 rgba_depth ) {",
  10382. "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 );",
  10383. "float depth = dot( rgba_depth, bit_shift );",
  10384. "return depth;",
  10385. "}",
  10386. "#endif"
  10387. ].join("\n"),
  10388. shadowmap_fragment: [
  10389. "#ifdef USE_SHADOWMAP",
  10390. "#ifdef SHADOWMAP_DEBUG",
  10391. "vec3 frustumColors[3];",
  10392. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  10393. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  10394. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  10395. "#endif",
  10396. "#ifdef SHADOWMAP_CASCADE",
  10397. "int inFrustumCount = 0;",
  10398. "#endif",
  10399. "float fDepth;",
  10400. "vec3 shadowColor = vec3( 1.0 );",
  10401. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10402. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  10403. // "if ( something && something )" breaks ATI OpenGL shader compiler
  10404. // "if ( all( something, something ) )" using this instead
  10405. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  10406. "bool inFrustum = all( inFrustumVec );",
  10407. // don't shadow pixels outside of light frustum
  10408. // use just first frustum (for cascades)
  10409. // don't shadow pixels behind far plane of light frustum
  10410. "#ifdef SHADOWMAP_CASCADE",
  10411. "inFrustumCount += int( inFrustum );",
  10412. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  10413. "#else",
  10414. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  10415. "#endif",
  10416. "bool frustumTest = all( frustumTestVec );",
  10417. "if ( frustumTest ) {",
  10418. "shadowCoord.z += shadowBias[ i ];",
  10419. "#if defined( SHADOWMAP_TYPE_PCF )",
  10420. // Percentage-close filtering
  10421. // (9 pixel kernel)
  10422. // http://fabiensanglard.net/shadowmappingPCF/
  10423. "float shadow = 0.0;",
  10424. /*
  10425. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  10426. // must enroll loop manually
  10427. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  10428. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  10429. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  10430. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  10431. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  10432. "float fDepth = unpackDepth( rgbaDepth );",
  10433. "if ( fDepth < shadowCoord.z )",
  10434. "shadow += 1.0;",
  10435. "}",
  10436. "shadow /= 9.0;",
  10437. */
  10438. "const float shadowDelta = 1.0 / 9.0;",
  10439. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10440. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10441. "float dx0 = -1.25 * xPixelOffset;",
  10442. "float dy0 = -1.25 * yPixelOffset;",
  10443. "float dx1 = 1.25 * xPixelOffset;",
  10444. "float dy1 = 1.25 * yPixelOffset;",
  10445. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10446. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10447. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10448. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10449. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10450. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10451. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10452. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10453. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10454. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10455. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10456. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10457. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10458. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10459. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10460. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10461. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10462. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  10463. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10464. "#elif defined( SHADOWMAP_TYPE_PCF_SOFT )",
  10465. // Percentage-close filtering
  10466. // (9 pixel kernel)
  10467. // http://fabiensanglard.net/shadowmappingPCF/
  10468. "float shadow = 0.0;",
  10469. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  10470. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  10471. "float dx0 = -1.0 * xPixelOffset;",
  10472. "float dy0 = -1.0 * yPixelOffset;",
  10473. "float dx1 = 1.0 * xPixelOffset;",
  10474. "float dy1 = 1.0 * yPixelOffset;",
  10475. "mat3 shadowKernel;",
  10476. "mat3 depthKernel;",
  10477. "depthKernel[0][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  10478. "depthKernel[0][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  10479. "depthKernel[0][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  10480. "depthKernel[1][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  10481. "depthKernel[1][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  10482. "depthKernel[1][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  10483. "depthKernel[2][0] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  10484. "depthKernel[2][1] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  10485. "depthKernel[2][2] = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  10486. "vec3 shadowZ = vec3( shadowCoord.z );",
  10487. "shadowKernel[0] = vec3(lessThan(depthKernel[0], shadowZ ));",
  10488. "shadowKernel[0] *= vec3(0.25);",
  10489. "shadowKernel[1] = vec3(lessThan(depthKernel[1], shadowZ ));",
  10490. "shadowKernel[1] *= vec3(0.25);",
  10491. "shadowKernel[2] = vec3(lessThan(depthKernel[2], shadowZ ));",
  10492. "shadowKernel[2] *= vec3(0.25);",
  10493. "vec2 fractionalCoord = 1.0 - fract( shadowCoord.xy * shadowMapSize[i].xy );",
  10494. "shadowKernel[0] = mix( shadowKernel[1], shadowKernel[0], fractionalCoord.x );",
  10495. "shadowKernel[1] = mix( shadowKernel[2], shadowKernel[1], fractionalCoord.x );",
  10496. "vec4 shadowValues;",
  10497. "shadowValues.x = mix( shadowKernel[0][1], shadowKernel[0][0], fractionalCoord.y );",
  10498. "shadowValues.y = mix( shadowKernel[0][2], shadowKernel[0][1], fractionalCoord.y );",
  10499. "shadowValues.z = mix( shadowKernel[1][1], shadowKernel[1][0], fractionalCoord.y );",
  10500. "shadowValues.w = mix( shadowKernel[1][2], shadowKernel[1][1], fractionalCoord.y );",
  10501. "shadow = dot( shadowValues, vec4( 1.0 ) );",
  10502. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  10503. "#else",
  10504. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  10505. "float fDepth = unpackDepth( rgbaDepth );",
  10506. "if ( fDepth < shadowCoord.z )",
  10507. // spot with multiple shadows is darker
  10508. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  10509. // spot with multiple shadows has the same color as single shadow spot
  10510. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  10511. "#endif",
  10512. "}",
  10513. "#ifdef SHADOWMAP_DEBUG",
  10514. "#ifdef SHADOWMAP_CASCADE",
  10515. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  10516. "#else",
  10517. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  10518. "#endif",
  10519. "#endif",
  10520. "}",
  10521. "#ifdef GAMMA_OUTPUT",
  10522. "shadowColor *= shadowColor;",
  10523. "#endif",
  10524. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  10525. "#endif"
  10526. ].join("\n"),
  10527. shadowmap_pars_vertex: [
  10528. "#ifdef USE_SHADOWMAP",
  10529. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  10530. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  10531. "#endif"
  10532. ].join("\n"),
  10533. shadowmap_vertex: [
  10534. "#ifdef USE_SHADOWMAP",
  10535. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  10536. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  10537. "}",
  10538. "#endif"
  10539. ].join("\n"),
  10540. // ALPHATEST
  10541. alphatest_fragment: [
  10542. "#ifdef ALPHATEST",
  10543. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  10544. "#endif"
  10545. ].join("\n"),
  10546. // LINEAR SPACE
  10547. linear_to_gamma_fragment: [
  10548. "#ifdef GAMMA_OUTPUT",
  10549. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  10550. "#endif"
  10551. ].join("\n")
  10552. };
  10553. THREE.UniformsUtils = {
  10554. merge: function ( uniforms ) {
  10555. var u, p, tmp, merged = {};
  10556. for ( u = 0; u < uniforms.length; u ++ ) {
  10557. tmp = this.clone( uniforms[ u ] );
  10558. for ( p in tmp ) {
  10559. merged[ p ] = tmp[ p ];
  10560. }
  10561. }
  10562. return merged;
  10563. },
  10564. clone: function ( uniforms_src ) {
  10565. var u, p, parameter, parameter_src, uniforms_dst = {};
  10566. for ( u in uniforms_src ) {
  10567. uniforms_dst[ u ] = {};
  10568. for ( p in uniforms_src[ u ] ) {
  10569. parameter_src = uniforms_src[ u ][ p ];
  10570. if ( parameter_src instanceof THREE.Color ||
  10571. parameter_src instanceof THREE.Vector2 ||
  10572. parameter_src instanceof THREE.Vector3 ||
  10573. parameter_src instanceof THREE.Vector4 ||
  10574. parameter_src instanceof THREE.Matrix4 ||
  10575. parameter_src instanceof THREE.Texture ) {
  10576. uniforms_dst[ u ][ p ] = parameter_src.clone();
  10577. } else if ( parameter_src instanceof Array ) {
  10578. uniforms_dst[ u ][ p ] = parameter_src.slice();
  10579. } else {
  10580. uniforms_dst[ u ][ p ] = parameter_src;
  10581. }
  10582. }
  10583. }
  10584. return uniforms_dst;
  10585. }
  10586. };
  10587. THREE.UniformsLib = {
  10588. common: {
  10589. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10590. "opacity" : { type: "f", value: 1.0 },
  10591. "map" : { type: "t", value: null },
  10592. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  10593. "lightMap" : { type: "t", value: null },
  10594. "specularMap" : { type: "t", value: null },
  10595. "envMap" : { type: "t", value: null },
  10596. "flipEnvMap" : { type: "f", value: -1 },
  10597. "useRefract" : { type: "i", value: 0 },
  10598. "reflectivity" : { type: "f", value: 1.0 },
  10599. "refractionRatio" : { type: "f", value: 0.98 },
  10600. "combine" : { type: "i", value: 0 },
  10601. "morphTargetInfluences" : { type: "f", value: 0 }
  10602. },
  10603. bump: {
  10604. "bumpMap" : { type: "t", value: null },
  10605. "bumpScale" : { type: "f", value: 1 }
  10606. },
  10607. normalmap: {
  10608. "normalMap" : { type: "t", value: null },
  10609. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  10610. },
  10611. fog : {
  10612. "fogDensity" : { type: "f", value: 0.00025 },
  10613. "fogNear" : { type: "f", value: 1 },
  10614. "fogFar" : { type: "f", value: 2000 },
  10615. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10616. },
  10617. lights: {
  10618. "ambientLightColor" : { type: "fv", value: [] },
  10619. "directionalLightDirection" : { type: "fv", value: [] },
  10620. "directionalLightColor" : { type: "fv", value: [] },
  10621. "hemisphereLightDirection" : { type: "fv", value: [] },
  10622. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  10623. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  10624. "pointLightColor" : { type: "fv", value: [] },
  10625. "pointLightPosition" : { type: "fv", value: [] },
  10626. "pointLightDistance" : { type: "fv1", value: [] },
  10627. "spotLightColor" : { type: "fv", value: [] },
  10628. "spotLightPosition" : { type: "fv", value: [] },
  10629. "spotLightDirection" : { type: "fv", value: [] },
  10630. "spotLightDistance" : { type: "fv1", value: [] },
  10631. "spotLightAngleCos" : { type: "fv1", value: [] },
  10632. "spotLightExponent" : { type: "fv1", value: [] }
  10633. },
  10634. particle: {
  10635. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  10636. "opacity" : { type: "f", value: 1.0 },
  10637. "size" : { type: "f", value: 1.0 },
  10638. "scale" : { type: "f", value: 1.0 },
  10639. "map" : { type: "t", value: null },
  10640. "fogDensity" : { type: "f", value: 0.00025 },
  10641. "fogNear" : { type: "f", value: 1 },
  10642. "fogFar" : { type: "f", value: 2000 },
  10643. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  10644. },
  10645. shadowmap: {
  10646. "shadowMap": { type: "tv", value: [] },
  10647. "shadowMapSize": { type: "v2v", value: [] },
  10648. "shadowBias" : { type: "fv1", value: [] },
  10649. "shadowDarkness": { type: "fv1", value: [] },
  10650. "shadowMatrix" : { type: "m4v", value: [] }
  10651. }
  10652. };
  10653. THREE.ShaderLib = {
  10654. 'basic': {
  10655. uniforms: THREE.UniformsUtils.merge( [
  10656. THREE.UniformsLib[ "common" ],
  10657. THREE.UniformsLib[ "fog" ],
  10658. THREE.UniformsLib[ "shadowmap" ]
  10659. ] ),
  10660. vertexShader: [
  10661. THREE.ShaderChunk[ "map_pars_vertex" ],
  10662. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10663. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10664. THREE.ShaderChunk[ "color_pars_vertex" ],
  10665. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10666. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10667. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10668. "void main() {",
  10669. THREE.ShaderChunk[ "map_vertex" ],
  10670. THREE.ShaderChunk[ "lightmap_vertex" ],
  10671. THREE.ShaderChunk[ "color_vertex" ],
  10672. THREE.ShaderChunk[ "skinbase_vertex" ],
  10673. "#ifdef USE_ENVMAP",
  10674. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10675. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10676. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10677. "#endif",
  10678. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10679. THREE.ShaderChunk[ "skinning_vertex" ],
  10680. THREE.ShaderChunk[ "default_vertex" ],
  10681. THREE.ShaderChunk[ "worldpos_vertex" ],
  10682. THREE.ShaderChunk[ "envmap_vertex" ],
  10683. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10684. "}"
  10685. ].join("\n"),
  10686. fragmentShader: [
  10687. "uniform vec3 diffuse;",
  10688. "uniform float opacity;",
  10689. THREE.ShaderChunk[ "color_pars_fragment" ],
  10690. THREE.ShaderChunk[ "map_pars_fragment" ],
  10691. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10692. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10693. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10694. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10695. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10696. "void main() {",
  10697. "gl_FragColor = vec4( diffuse, opacity );",
  10698. THREE.ShaderChunk[ "map_fragment" ],
  10699. THREE.ShaderChunk[ "alphatest_fragment" ],
  10700. THREE.ShaderChunk[ "specularmap_fragment" ],
  10701. THREE.ShaderChunk[ "lightmap_fragment" ],
  10702. THREE.ShaderChunk[ "color_fragment" ],
  10703. THREE.ShaderChunk[ "envmap_fragment" ],
  10704. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10705. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10706. THREE.ShaderChunk[ "fog_fragment" ],
  10707. "}"
  10708. ].join("\n")
  10709. },
  10710. 'lambert': {
  10711. uniforms: THREE.UniformsUtils.merge( [
  10712. THREE.UniformsLib[ "common" ],
  10713. THREE.UniformsLib[ "fog" ],
  10714. THREE.UniformsLib[ "lights" ],
  10715. THREE.UniformsLib[ "shadowmap" ],
  10716. {
  10717. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10718. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10719. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10720. }
  10721. ] ),
  10722. vertexShader: [
  10723. "#define LAMBERT",
  10724. "varying vec3 vLightFront;",
  10725. "#ifdef DOUBLE_SIDED",
  10726. "varying vec3 vLightBack;",
  10727. "#endif",
  10728. THREE.ShaderChunk[ "map_pars_vertex" ],
  10729. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10730. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10731. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  10732. THREE.ShaderChunk[ "color_pars_vertex" ],
  10733. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10734. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10735. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10736. "void main() {",
  10737. THREE.ShaderChunk[ "map_vertex" ],
  10738. THREE.ShaderChunk[ "lightmap_vertex" ],
  10739. THREE.ShaderChunk[ "color_vertex" ],
  10740. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10741. THREE.ShaderChunk[ "skinbase_vertex" ],
  10742. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10743. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10744. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10745. THREE.ShaderChunk[ "skinning_vertex" ],
  10746. THREE.ShaderChunk[ "default_vertex" ],
  10747. THREE.ShaderChunk[ "worldpos_vertex" ],
  10748. THREE.ShaderChunk[ "envmap_vertex" ],
  10749. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  10750. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10751. "}"
  10752. ].join("\n"),
  10753. fragmentShader: [
  10754. "uniform float opacity;",
  10755. "varying vec3 vLightFront;",
  10756. "#ifdef DOUBLE_SIDED",
  10757. "varying vec3 vLightBack;",
  10758. "#endif",
  10759. THREE.ShaderChunk[ "color_pars_fragment" ],
  10760. THREE.ShaderChunk[ "map_pars_fragment" ],
  10761. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10762. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10763. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10764. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10765. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10766. "void main() {",
  10767. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10768. THREE.ShaderChunk[ "map_fragment" ],
  10769. THREE.ShaderChunk[ "alphatest_fragment" ],
  10770. THREE.ShaderChunk[ "specularmap_fragment" ],
  10771. "#ifdef DOUBLE_SIDED",
  10772. //"float isFront = float( gl_FrontFacing );",
  10773. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  10774. "if ( gl_FrontFacing )",
  10775. "gl_FragColor.xyz *= vLightFront;",
  10776. "else",
  10777. "gl_FragColor.xyz *= vLightBack;",
  10778. "#else",
  10779. "gl_FragColor.xyz *= vLightFront;",
  10780. "#endif",
  10781. THREE.ShaderChunk[ "lightmap_fragment" ],
  10782. THREE.ShaderChunk[ "color_fragment" ],
  10783. THREE.ShaderChunk[ "envmap_fragment" ],
  10784. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10785. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10786. THREE.ShaderChunk[ "fog_fragment" ],
  10787. "}"
  10788. ].join("\n")
  10789. },
  10790. 'phong': {
  10791. uniforms: THREE.UniformsUtils.merge( [
  10792. THREE.UniformsLib[ "common" ],
  10793. THREE.UniformsLib[ "bump" ],
  10794. THREE.UniformsLib[ "normalmap" ],
  10795. THREE.UniformsLib[ "fog" ],
  10796. THREE.UniformsLib[ "lights" ],
  10797. THREE.UniformsLib[ "shadowmap" ],
  10798. {
  10799. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  10800. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  10801. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  10802. "shininess": { type: "f", value: 30 },
  10803. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  10804. }
  10805. ] ),
  10806. vertexShader: [
  10807. "#define PHONG",
  10808. "varying vec3 vViewPosition;",
  10809. "varying vec3 vNormal;",
  10810. THREE.ShaderChunk[ "map_pars_vertex" ],
  10811. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  10812. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  10813. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  10814. THREE.ShaderChunk[ "color_pars_vertex" ],
  10815. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10816. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10817. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10818. "void main() {",
  10819. THREE.ShaderChunk[ "map_vertex" ],
  10820. THREE.ShaderChunk[ "lightmap_vertex" ],
  10821. THREE.ShaderChunk[ "color_vertex" ],
  10822. THREE.ShaderChunk[ "morphnormal_vertex" ],
  10823. THREE.ShaderChunk[ "skinbase_vertex" ],
  10824. THREE.ShaderChunk[ "skinnormal_vertex" ],
  10825. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  10826. "vNormal = normalize( transformedNormal );",
  10827. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10828. THREE.ShaderChunk[ "skinning_vertex" ],
  10829. THREE.ShaderChunk[ "default_vertex" ],
  10830. "vViewPosition = -mvPosition.xyz;",
  10831. THREE.ShaderChunk[ "worldpos_vertex" ],
  10832. THREE.ShaderChunk[ "envmap_vertex" ],
  10833. THREE.ShaderChunk[ "lights_phong_vertex" ],
  10834. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10835. "}"
  10836. ].join("\n"),
  10837. fragmentShader: [
  10838. "uniform vec3 diffuse;",
  10839. "uniform float opacity;",
  10840. "uniform vec3 ambient;",
  10841. "uniform vec3 emissive;",
  10842. "uniform vec3 specular;",
  10843. "uniform float shininess;",
  10844. THREE.ShaderChunk[ "color_pars_fragment" ],
  10845. THREE.ShaderChunk[ "map_pars_fragment" ],
  10846. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  10847. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  10848. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10849. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  10850. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10851. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  10852. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  10853. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  10854. "void main() {",
  10855. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  10856. THREE.ShaderChunk[ "map_fragment" ],
  10857. THREE.ShaderChunk[ "alphatest_fragment" ],
  10858. THREE.ShaderChunk[ "specularmap_fragment" ],
  10859. THREE.ShaderChunk[ "lights_phong_fragment" ],
  10860. THREE.ShaderChunk[ "lightmap_fragment" ],
  10861. THREE.ShaderChunk[ "color_fragment" ],
  10862. THREE.ShaderChunk[ "envmap_fragment" ],
  10863. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10864. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  10865. THREE.ShaderChunk[ "fog_fragment" ],
  10866. "}"
  10867. ].join("\n")
  10868. },
  10869. 'particle_basic': {
  10870. uniforms: THREE.UniformsUtils.merge( [
  10871. THREE.UniformsLib[ "particle" ],
  10872. THREE.UniformsLib[ "shadowmap" ]
  10873. ] ),
  10874. vertexShader: [
  10875. "uniform float size;",
  10876. "uniform float scale;",
  10877. THREE.ShaderChunk[ "color_pars_vertex" ],
  10878. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  10879. "void main() {",
  10880. THREE.ShaderChunk[ "color_vertex" ],
  10881. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10882. "#ifdef USE_SIZEATTENUATION",
  10883. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  10884. "#else",
  10885. "gl_PointSize = size;",
  10886. "#endif",
  10887. "gl_Position = projectionMatrix * mvPosition;",
  10888. THREE.ShaderChunk[ "worldpos_vertex" ],
  10889. THREE.ShaderChunk[ "shadowmap_vertex" ],
  10890. "}"
  10891. ].join("\n"),
  10892. fragmentShader: [
  10893. "uniform vec3 psColor;",
  10894. "uniform float opacity;",
  10895. THREE.ShaderChunk[ "color_pars_fragment" ],
  10896. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  10897. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10898. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  10899. "void main() {",
  10900. "gl_FragColor = vec4( psColor, opacity );",
  10901. THREE.ShaderChunk[ "map_particle_fragment" ],
  10902. THREE.ShaderChunk[ "alphatest_fragment" ],
  10903. THREE.ShaderChunk[ "color_fragment" ],
  10904. THREE.ShaderChunk[ "shadowmap_fragment" ],
  10905. THREE.ShaderChunk[ "fog_fragment" ],
  10906. "}"
  10907. ].join("\n")
  10908. },
  10909. 'dashed': {
  10910. uniforms: THREE.UniformsUtils.merge( [
  10911. THREE.UniformsLib[ "common" ],
  10912. THREE.UniformsLib[ "fog" ],
  10913. {
  10914. "scale": { type: "f", value: 1 },
  10915. "dashSize": { type: "f", value: 1 },
  10916. "totalSize": { type: "f", value: 2 }
  10917. }
  10918. ] ),
  10919. vertexShader: [
  10920. "uniform float scale;",
  10921. "attribute float lineDistance;",
  10922. "varying float vLineDistance;",
  10923. THREE.ShaderChunk[ "color_pars_vertex" ],
  10924. "void main() {",
  10925. THREE.ShaderChunk[ "color_vertex" ],
  10926. "vLineDistance = scale * lineDistance;",
  10927. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10928. "gl_Position = projectionMatrix * mvPosition;",
  10929. "}"
  10930. ].join("\n"),
  10931. fragmentShader: [
  10932. "uniform vec3 diffuse;",
  10933. "uniform float opacity;",
  10934. "uniform float dashSize;",
  10935. "uniform float totalSize;",
  10936. "varying float vLineDistance;",
  10937. THREE.ShaderChunk[ "color_pars_fragment" ],
  10938. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10939. "void main() {",
  10940. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10941. "discard;",
  10942. "}",
  10943. "gl_FragColor = vec4( diffuse, opacity );",
  10944. THREE.ShaderChunk[ "color_fragment" ],
  10945. THREE.ShaderChunk[ "fog_fragment" ],
  10946. "}"
  10947. ].join("\n")
  10948. },
  10949. 'depth': {
  10950. uniforms: {
  10951. "mNear": { type: "f", value: 1.0 },
  10952. "mFar" : { type: "f", value: 2000.0 },
  10953. "opacity" : { type: "f", value: 1.0 }
  10954. },
  10955. vertexShader: [
  10956. "void main() {",
  10957. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  10958. "}"
  10959. ].join("\n"),
  10960. fragmentShader: [
  10961. "uniform float mNear;",
  10962. "uniform float mFar;",
  10963. "uniform float opacity;",
  10964. "void main() {",
  10965. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  10966. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  10967. "gl_FragColor = vec4( vec3( color ), opacity );",
  10968. "}"
  10969. ].join("\n")
  10970. },
  10971. 'normal': {
  10972. uniforms: {
  10973. "opacity" : { type: "f", value: 1.0 }
  10974. },
  10975. vertexShader: [
  10976. "varying vec3 vNormal;",
  10977. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10978. "void main() {",
  10979. "vNormal = normalize( normalMatrix * normal );",
  10980. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10981. THREE.ShaderChunk[ "default_vertex" ],
  10982. "}"
  10983. ].join("\n"),
  10984. fragmentShader: [
  10985. "uniform float opacity;",
  10986. "varying vec3 vNormal;",
  10987. "void main() {",
  10988. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  10989. "}"
  10990. ].join("\n")
  10991. },
  10992. /* -------------------------------------------------------------------------
  10993. // Normal map shader
  10994. // - Blinn-Phong
  10995. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10996. // - point and directional lights (use with "lights: true" material option)
  10997. ------------------------------------------------------------------------- */
  10998. 'normalmap' : {
  10999. uniforms: THREE.UniformsUtils.merge( [
  11000. THREE.UniformsLib[ "fog" ],
  11001. THREE.UniformsLib[ "lights" ],
  11002. THREE.UniformsLib[ "shadowmap" ],
  11003. {
  11004. "enableAO" : { type: "i", value: 0 },
  11005. "enableDiffuse" : { type: "i", value: 0 },
  11006. "enableSpecular" : { type: "i", value: 0 },
  11007. "enableReflection": { type: "i", value: 0 },
  11008. "enableDisplacement": { type: "i", value: 0 },
  11009. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  11010. "tDiffuse" : { type: "t", value: null },
  11011. "tCube" : { type: "t", value: null },
  11012. "tNormal" : { type: "t", value: null },
  11013. "tSpecular" : { type: "t", value: null },
  11014. "tAO" : { type: "t", value: null },
  11015. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11016. "uDisplacementBias": { type: "f", value: 0.0 },
  11017. "uDisplacementScale": { type: "f", value: 1.0 },
  11018. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11019. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11020. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11021. "uShininess": { type: "f", value: 30 },
  11022. "uOpacity": { type: "f", value: 1 },
  11023. "useRefract": { type: "i", value: 0 },
  11024. "uRefractionRatio": { type: "f", value: 0.98 },
  11025. "uReflectivity": { type: "f", value: 0.5 },
  11026. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11027. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11028. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11029. }
  11030. ] ),
  11031. fragmentShader: [
  11032. "uniform vec3 uAmbientColor;",
  11033. "uniform vec3 uDiffuseColor;",
  11034. "uniform vec3 uSpecularColor;",
  11035. "uniform float uShininess;",
  11036. "uniform float uOpacity;",
  11037. "uniform bool enableDiffuse;",
  11038. "uniform bool enableSpecular;",
  11039. "uniform bool enableAO;",
  11040. "uniform bool enableReflection;",
  11041. "uniform sampler2D tDiffuse;",
  11042. "uniform sampler2D tNormal;",
  11043. "uniform sampler2D tSpecular;",
  11044. "uniform sampler2D tAO;",
  11045. "uniform samplerCube tCube;",
  11046. "uniform vec2 uNormalScale;",
  11047. "uniform bool useRefract;",
  11048. "uniform float uRefractionRatio;",
  11049. "uniform float uReflectivity;",
  11050. "varying vec3 vTangent;",
  11051. "varying vec3 vBinormal;",
  11052. "varying vec3 vNormal;",
  11053. "varying vec2 vUv;",
  11054. "uniform vec3 ambientLightColor;",
  11055. "#if MAX_DIR_LIGHTS > 0",
  11056. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11057. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11058. "#endif",
  11059. "#if MAX_HEMI_LIGHTS > 0",
  11060. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  11061. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  11062. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  11063. "#endif",
  11064. "#if MAX_POINT_LIGHTS > 0",
  11065. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11066. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11067. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11068. "#endif",
  11069. "#if MAX_SPOT_LIGHTS > 0",
  11070. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  11071. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  11072. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  11073. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  11074. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  11075. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  11076. "#endif",
  11077. "#ifdef WRAP_AROUND",
  11078. "uniform vec3 wrapRGB;",
  11079. "#endif",
  11080. "varying vec3 vWorldPosition;",
  11081. "varying vec3 vViewPosition;",
  11082. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11083. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11084. "void main() {",
  11085. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11086. "vec3 specularTex = vec3( 1.0 );",
  11087. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11088. "normalTex.xy *= uNormalScale;",
  11089. "normalTex = normalize( normalTex );",
  11090. "if( enableDiffuse ) {",
  11091. "#ifdef GAMMA_INPUT",
  11092. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11093. "texelColor.xyz *= texelColor.xyz;",
  11094. "gl_FragColor = gl_FragColor * texelColor;",
  11095. "#else",
  11096. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11097. "#endif",
  11098. "}",
  11099. "if( enableAO ) {",
  11100. "#ifdef GAMMA_INPUT",
  11101. "vec4 aoColor = texture2D( tAO, vUv );",
  11102. "aoColor.xyz *= aoColor.xyz;",
  11103. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11104. "#else",
  11105. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11106. "#endif",
  11107. "}",
  11108. "if( enableSpecular )",
  11109. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11110. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11111. "vec3 finalNormal = tsb * normalTex;",
  11112. "#ifdef FLIP_SIDED",
  11113. "finalNormal = -finalNormal;",
  11114. "#endif",
  11115. "vec3 normal = normalize( finalNormal );",
  11116. "vec3 viewPosition = normalize( vViewPosition );",
  11117. // point lights
  11118. "#if MAX_POINT_LIGHTS > 0",
  11119. "vec3 pointDiffuse = vec3( 0.0 );",
  11120. "vec3 pointSpecular = vec3( 0.0 );",
  11121. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11122. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11123. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  11124. "float pointDistance = 1.0;",
  11125. "if ( pointLightDistance[ i ] > 0.0 )",
  11126. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  11127. "pointVector = normalize( pointVector );",
  11128. // diffuse
  11129. "#ifdef WRAP_AROUND",
  11130. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11131. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11132. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11133. "#else",
  11134. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11135. "#endif",
  11136. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11137. // specular
  11138. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11139. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11140. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11141. "#ifdef PHYSICALLY_BASED_SHADING",
  11142. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11143. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11144. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11145. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11146. "#else",
  11147. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11148. "#endif",
  11149. "}",
  11150. "#endif",
  11151. // spot lights
  11152. "#if MAX_SPOT_LIGHTS > 0",
  11153. "vec3 spotDiffuse = vec3( 0.0 );",
  11154. "vec3 spotSpecular = vec3( 0.0 );",
  11155. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  11156. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  11157. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  11158. "float spotDistance = 1.0;",
  11159. "if ( spotLightDistance[ i ] > 0.0 )",
  11160. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  11161. "spotVector = normalize( spotVector );",
  11162. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  11163. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  11164. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  11165. // diffuse
  11166. "#ifdef WRAP_AROUND",
  11167. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  11168. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  11169. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  11170. "#else",
  11171. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  11172. "#endif",
  11173. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  11174. // specular
  11175. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  11176. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  11177. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  11178. "#ifdef PHYSICALLY_BASED_SHADING",
  11179. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11180. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11181. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  11182. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  11183. "#else",
  11184. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  11185. "#endif",
  11186. "}",
  11187. "}",
  11188. "#endif",
  11189. // directional lights
  11190. "#if MAX_DIR_LIGHTS > 0",
  11191. "vec3 dirDiffuse = vec3( 0.0 );",
  11192. "vec3 dirSpecular = vec3( 0.0 );",
  11193. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11194. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11195. "vec3 dirVector = normalize( lDirection.xyz );",
  11196. // diffuse
  11197. "#ifdef WRAP_AROUND",
  11198. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11199. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11200. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11201. "#else",
  11202. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11203. "#endif",
  11204. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11205. // specular
  11206. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11207. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11208. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11209. "#ifdef PHYSICALLY_BASED_SHADING",
  11210. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11211. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11212. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11213. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11214. "#else",
  11215. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11216. "#endif",
  11217. "}",
  11218. "#endif",
  11219. // hemisphere lights
  11220. "#if MAX_HEMI_LIGHTS > 0",
  11221. "vec3 hemiDiffuse = vec3( 0.0 );",
  11222. "vec3 hemiSpecular = vec3( 0.0 );" ,
  11223. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  11224. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  11225. "vec3 lVector = normalize( lDirection.xyz );",
  11226. // diffuse
  11227. "float dotProduct = dot( normal, lVector );",
  11228. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  11229. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  11230. "hemiDiffuse += uDiffuseColor * hemiColor;",
  11231. // specular (sky light)
  11232. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  11233. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  11234. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  11235. // specular (ground light)
  11236. "vec3 lVectorGround = -lVector;",
  11237. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  11238. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  11239. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  11240. "#ifdef PHYSICALLY_BASED_SHADING",
  11241. "float dotProductGround = dot( normal, lVectorGround );",
  11242. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11243. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11244. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  11245. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  11246. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  11247. "#else",
  11248. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  11249. "#endif",
  11250. "}",
  11251. "#endif",
  11252. // all lights contribution summation
  11253. "vec3 totalDiffuse = vec3( 0.0 );",
  11254. "vec3 totalSpecular = vec3( 0.0 );",
  11255. "#if MAX_DIR_LIGHTS > 0",
  11256. "totalDiffuse += dirDiffuse;",
  11257. "totalSpecular += dirSpecular;",
  11258. "#endif",
  11259. "#if MAX_HEMI_LIGHTS > 0",
  11260. "totalDiffuse += hemiDiffuse;",
  11261. "totalSpecular += hemiSpecular;",
  11262. "#endif",
  11263. "#if MAX_POINT_LIGHTS > 0",
  11264. "totalDiffuse += pointDiffuse;",
  11265. "totalSpecular += pointSpecular;",
  11266. "#endif",
  11267. "#if MAX_SPOT_LIGHTS > 0",
  11268. "totalDiffuse += spotDiffuse;",
  11269. "totalSpecular += spotSpecular;",
  11270. "#endif",
  11271. "#ifdef METAL",
  11272. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  11273. "#else",
  11274. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  11275. "#endif",
  11276. "if ( enableReflection ) {",
  11277. "vec3 vReflect;",
  11278. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  11279. "if ( useRefract ) {",
  11280. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  11281. "} else {",
  11282. "vReflect = reflect( cameraToVertex, normal );",
  11283. "}",
  11284. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11285. "#ifdef GAMMA_INPUT",
  11286. "cubeColor.xyz *= cubeColor.xyz;",
  11287. "#endif",
  11288. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11289. "}",
  11290. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11291. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11292. THREE.ShaderChunk[ "fog_fragment" ],
  11293. "}"
  11294. ].join("\n"),
  11295. vertexShader: [
  11296. "attribute vec4 tangent;",
  11297. "uniform vec2 uOffset;",
  11298. "uniform vec2 uRepeat;",
  11299. "uniform bool enableDisplacement;",
  11300. "#ifdef VERTEX_TEXTURES",
  11301. "uniform sampler2D tDisplacement;",
  11302. "uniform float uDisplacementScale;",
  11303. "uniform float uDisplacementBias;",
  11304. "#endif",
  11305. "varying vec3 vTangent;",
  11306. "varying vec3 vBinormal;",
  11307. "varying vec3 vNormal;",
  11308. "varying vec2 vUv;",
  11309. "varying vec3 vWorldPosition;",
  11310. "varying vec3 vViewPosition;",
  11311. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11312. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11313. "void main() {",
  11314. THREE.ShaderChunk[ "skinbase_vertex" ],
  11315. THREE.ShaderChunk[ "skinnormal_vertex" ],
  11316. // normal, tangent and binormal vectors
  11317. "#ifdef USE_SKINNING",
  11318. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  11319. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  11320. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  11321. "#else",
  11322. "vNormal = normalize( normalMatrix * normal );",
  11323. "vTangent = normalize( normalMatrix * tangent.xyz );",
  11324. "#endif",
  11325. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  11326. "vUv = uv * uRepeat + uOffset;",
  11327. // displacement mapping
  11328. "vec3 displacedPosition;",
  11329. "#ifdef VERTEX_TEXTURES",
  11330. "if ( enableDisplacement ) {",
  11331. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11332. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11333. "displacedPosition = position + normalize( normal ) * df;",
  11334. "} else {",
  11335. "#ifdef USE_SKINNING",
  11336. "vec4 skinVertex = vec4( position, 1.0 );",
  11337. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11338. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11339. "displacedPosition = skinned.xyz;",
  11340. "#else",
  11341. "displacedPosition = position;",
  11342. "#endif",
  11343. "}",
  11344. "#else",
  11345. "#ifdef USE_SKINNING",
  11346. "vec4 skinVertex = vec4( position, 1.0 );",
  11347. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  11348. "skinned += boneMatY * skinVertex * skinWeight.y;",
  11349. "displacedPosition = skinned.xyz;",
  11350. "#else",
  11351. "displacedPosition = position;",
  11352. "#endif",
  11353. "#endif",
  11354. //
  11355. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  11356. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  11357. "gl_Position = projectionMatrix * mvPosition;",
  11358. //
  11359. "vWorldPosition = worldPosition.xyz;",
  11360. "vViewPosition = -mvPosition.xyz;",
  11361. // shadows
  11362. "#ifdef USE_SHADOWMAP",
  11363. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  11364. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  11365. "}",
  11366. "#endif",
  11367. "}"
  11368. ].join("\n")
  11369. },
  11370. /* -------------------------------------------------------------------------
  11371. // Cube map shader
  11372. ------------------------------------------------------------------------- */
  11373. 'cube': {
  11374. uniforms: { "tCube": { type: "t", value: null },
  11375. "tFlip": { type: "f", value: -1 } },
  11376. vertexShader: [
  11377. "varying vec3 vWorldPosition;",
  11378. "void main() {",
  11379. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  11380. "vWorldPosition = worldPosition.xyz;",
  11381. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11382. "}"
  11383. ].join("\n"),
  11384. fragmentShader: [
  11385. "uniform samplerCube tCube;",
  11386. "uniform float tFlip;",
  11387. "varying vec3 vWorldPosition;",
  11388. "void main() {",
  11389. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  11390. "}"
  11391. ].join("\n")
  11392. },
  11393. // Depth encoding into RGBA texture
  11394. // based on SpiderGL shadow map example
  11395. // http://spidergl.org/example.php?id=6
  11396. // originally from
  11397. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  11398. // see also here:
  11399. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  11400. 'depthRGBA': {
  11401. uniforms: {},
  11402. vertexShader: [
  11403. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  11404. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  11405. "void main() {",
  11406. THREE.ShaderChunk[ "skinbase_vertex" ],
  11407. THREE.ShaderChunk[ "morphtarget_vertex" ],
  11408. THREE.ShaderChunk[ "skinning_vertex" ],
  11409. THREE.ShaderChunk[ "default_vertex" ],
  11410. "}"
  11411. ].join("\n"),
  11412. fragmentShader: [
  11413. "vec4 pack_depth( const in float depth ) {",
  11414. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  11415. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  11416. "vec4 res = fract( depth * bit_shift );",
  11417. "res -= res.xxyz * bit_mask;",
  11418. "return res;",
  11419. "}",
  11420. "void main() {",
  11421. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  11422. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  11423. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  11424. //"gl_FragData[ 0 ] = pack_depth( z );",
  11425. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  11426. "}"
  11427. ].join("\n")
  11428. }
  11429. };
  11430. /**
  11431. * @author supereggbert / http://www.paulbrunt.co.uk/
  11432. * @author mrdoob / http://mrdoob.com/
  11433. * @author alteredq / http://alteredqualia.com/
  11434. * @author szimek / https://github.com/szimek/
  11435. */
  11436. THREE.WebGLRenderer = function ( parameters ) {
  11437. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  11438. parameters = parameters || {};
  11439. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  11440. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  11441. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  11442. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  11443. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  11444. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  11445. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  11446. _clearColor = new THREE.Color( 0x000000 ),
  11447. _clearAlpha = 0;
  11448. if ( parameters.clearColor !== undefined ) {
  11449. console.warn( 'DEPRECATED: clearColor in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11450. _clearColor.setHex( parameters.clearColor );
  11451. }
  11452. if ( parameters.clearAlpha !== undefined ) {
  11453. console.warn( 'DEPRECATED: clearAlpha in WebGLRenderer constructor parameters is being removed. Use .setClearColor() instead.' );
  11454. _clearAlpha = parameters.clearAlpha;
  11455. }
  11456. // public properties
  11457. this.domElement = _canvas;
  11458. this.context = null;
  11459. this.devicePixelRatio = parameters.devicePixelRatio !== undefined
  11460. ? parameters.devicePixelRatio
  11461. : window.devicePixelRatio !== undefined
  11462. ? window.devicePixelRatio
  11463. : 1;
  11464. // clearing
  11465. this.autoClear = true;
  11466. this.autoClearColor = true;
  11467. this.autoClearDepth = true;
  11468. this.autoClearStencil = true;
  11469. // scene graph
  11470. this.sortObjects = true;
  11471. this.autoUpdateObjects = true;
  11472. // physically based shading
  11473. this.gammaInput = false;
  11474. this.gammaOutput = false;
  11475. this.physicallyBasedShading = false;
  11476. // shadow map
  11477. this.shadowMapEnabled = false;
  11478. this.shadowMapAutoUpdate = true;
  11479. this.shadowMapType = THREE.PCFShadowMap;
  11480. this.shadowMapCullFace = THREE.CullFaceFront;
  11481. this.shadowMapDebug = false;
  11482. this.shadowMapCascade = false;
  11483. // morphs
  11484. this.maxMorphTargets = 8;
  11485. this.maxMorphNormals = 4;
  11486. // flags
  11487. this.autoScaleCubemaps = true;
  11488. // custom render plugins
  11489. this.renderPluginsPre = [];
  11490. this.renderPluginsPost = [];
  11491. // info
  11492. this.info = {
  11493. memory: {
  11494. programs: 0,
  11495. geometries: 0,
  11496. textures: 0
  11497. },
  11498. render: {
  11499. calls: 0,
  11500. vertices: 0,
  11501. faces: 0,
  11502. points: 0
  11503. }
  11504. };
  11505. // internal properties
  11506. var _this = this,
  11507. _programs = [],
  11508. _programs_counter = 0,
  11509. // internal state cache
  11510. _currentProgram = null,
  11511. _currentFramebuffer = null,
  11512. _currentMaterialId = -1,
  11513. _currentGeometryGroupHash = null,
  11514. _currentCamera = null,
  11515. _geometryGroupCounter = 0,
  11516. _usedTextureUnits = 0,
  11517. // GL state cache
  11518. _oldDoubleSided = -1,
  11519. _oldFlipSided = -1,
  11520. _oldBlending = -1,
  11521. _oldBlendEquation = -1,
  11522. _oldBlendSrc = -1,
  11523. _oldBlendDst = -1,
  11524. _oldDepthTest = -1,
  11525. _oldDepthWrite = -1,
  11526. _oldPolygonOffset = null,
  11527. _oldPolygonOffsetFactor = null,
  11528. _oldPolygonOffsetUnits = null,
  11529. _oldLineWidth = null,
  11530. _viewportX = 0,
  11531. _viewportY = 0,
  11532. _viewportWidth = 0,
  11533. _viewportHeight = 0,
  11534. _currentWidth = 0,
  11535. _currentHeight = 0,
  11536. _enabledAttributes = {},
  11537. // frustum
  11538. _frustum = new THREE.Frustum(),
  11539. // camera matrices cache
  11540. _projScreenMatrix = new THREE.Matrix4(),
  11541. _projScreenMatrixPS = new THREE.Matrix4(),
  11542. _vector3 = new THREE.Vector3(),
  11543. // light arrays cache
  11544. _direction = new THREE.Vector3(),
  11545. _lightsNeedUpdate = true,
  11546. _lights = {
  11547. ambient: [ 0, 0, 0 ],
  11548. directional: { length: 0, colors: new Array(), positions: new Array() },
  11549. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  11550. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  11551. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  11552. };
  11553. // initialize
  11554. var _gl;
  11555. var _glExtensionTextureFloat;
  11556. var _glExtensionTextureFloatLinear;
  11557. var _glExtensionStandardDerivatives;
  11558. var _glExtensionTextureFilterAnisotropic;
  11559. var _glExtensionCompressedTextureS3TC;
  11560. initGL();
  11561. setDefaultGLState();
  11562. this.context = _gl;
  11563. // GPU capabilities
  11564. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  11565. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  11566. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  11567. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  11568. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  11569. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  11570. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  11571. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  11572. //
  11573. var _vertexShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_FLOAT );
  11574. var _vertexShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_FLOAT );
  11575. var _vertexShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_FLOAT );
  11576. var _fragmentShaderPrecisionHighpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_FLOAT );
  11577. var _fragmentShaderPrecisionMediumpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_FLOAT );
  11578. var _fragmentShaderPrecisionLowpFloat = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_FLOAT );
  11579. var _vertexShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.HIGH_INT );
  11580. var _vertexShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.MEDIUM_INT );
  11581. var _vertexShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.VERTEX_SHADER, _gl.LOW_INT );
  11582. var _fragmentShaderPrecisionHighpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.HIGH_INT );
  11583. var _fragmentShaderPrecisionMediumpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.MEDIUM_INT );
  11584. var _fragmentShaderPrecisionLowpInt = _gl.getShaderPrecisionFormat( _gl.FRAGMENT_SHADER, _gl.LOW_INT );
  11585. // clamp precision to maximum available
  11586. var highpAvailable = _vertexShaderPrecisionHighpFloat.precision > 0 && _fragmentShaderPrecisionHighpFloat.precision > 0;
  11587. var mediumpAvailable = _vertexShaderPrecisionMediumpFloat.precision > 0 && _fragmentShaderPrecisionMediumpFloat.precision > 0;
  11588. if ( _precision === "highp" && ! highpAvailable ) {
  11589. if ( mediumpAvailable ) {
  11590. _precision = "mediump";
  11591. console.warn( "WebGLRenderer: highp not supported, using mediump" );
  11592. } else {
  11593. _precision = "lowp";
  11594. console.warn( "WebGLRenderer: highp and mediump not supported, using lowp" );
  11595. }
  11596. }
  11597. if ( _precision === "mediump" && ! mediumpAvailable ) {
  11598. _precision = "lowp";
  11599. console.warn( "WebGLRenderer: mediump not supported, using lowp" );
  11600. }
  11601. // API
  11602. this.getContext = function () {
  11603. return _gl;
  11604. };
  11605. this.supportsVertexTextures = function () {
  11606. return _supportsVertexTextures;
  11607. };
  11608. this.supportsFloatTextures = function () {
  11609. return _glExtensionTextureFloat;
  11610. };
  11611. this.supportsStandardDerivatives = function () {
  11612. return _glExtensionStandardDerivatives;
  11613. };
  11614. this.supportsCompressedTextureS3TC = function () {
  11615. return _glExtensionCompressedTextureS3TC;
  11616. };
  11617. this.getMaxAnisotropy = function () {
  11618. return _maxAnisotropy;
  11619. };
  11620. this.getPrecision = function () {
  11621. return _precision;
  11622. };
  11623. this.setSize = function ( width, height, updateStyle ) {
  11624. _canvas.width = width * this.devicePixelRatio;
  11625. _canvas.height = height * this.devicePixelRatio;
  11626. if ( this.devicePixelRatio !== 1 && updateStyle !== false ) {
  11627. _canvas.style.width = width + 'px';
  11628. _canvas.style.height = height + 'px';
  11629. }
  11630. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  11631. };
  11632. this.setViewport = function ( x, y, width, height ) {
  11633. _viewportX = x !== undefined ? x : 0;
  11634. _viewportY = y !== undefined ? y : 0;
  11635. _viewportWidth = width !== undefined ? width : _canvas.width;
  11636. _viewportHeight = height !== undefined ? height : _canvas.height;
  11637. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  11638. };
  11639. this.setScissor = function ( x, y, width, height ) {
  11640. _gl.scissor( x, y, width, height );
  11641. };
  11642. this.enableScissorTest = function ( enable ) {
  11643. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  11644. };
  11645. // Clearing
  11646. this.setClearColor = function ( color, alpha ) {
  11647. _clearColor.set( color );
  11648. _clearAlpha = alpha !== undefined ? alpha : 1;
  11649. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  11650. };
  11651. this.setClearColorHex = function ( hex, alpha ) {
  11652. console.warn( 'DEPRECATED: .setClearColorHex() is being removed. Use .setClearColor() instead.' );
  11653. this.setClearColor( hex, alpha );
  11654. };
  11655. this.getClearColor = function () {
  11656. return _clearColor;
  11657. };
  11658. this.getClearAlpha = function () {
  11659. return _clearAlpha;
  11660. };
  11661. this.clear = function ( color, depth, stencil ) {
  11662. var bits = 0;
  11663. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  11664. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  11665. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  11666. _gl.clear( bits );
  11667. };
  11668. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  11669. this.setRenderTarget( renderTarget );
  11670. this.clear( color, depth, stencil );
  11671. };
  11672. // Plugins
  11673. this.addPostPlugin = function ( plugin ) {
  11674. plugin.init( this );
  11675. this.renderPluginsPost.push( plugin );
  11676. };
  11677. this.addPrePlugin = function ( plugin ) {
  11678. plugin.init( this );
  11679. this.renderPluginsPre.push( plugin );
  11680. };
  11681. // Rendering
  11682. this.updateShadowMap = function ( scene, camera ) {
  11683. _currentProgram = null;
  11684. _oldBlending = -1;
  11685. _oldDepthTest = -1;
  11686. _oldDepthWrite = -1;
  11687. _currentGeometryGroupHash = -1;
  11688. _currentMaterialId = -1;
  11689. _lightsNeedUpdate = true;
  11690. _oldDoubleSided = -1;
  11691. _oldFlipSided = -1;
  11692. this.shadowMapPlugin.update( scene, camera );
  11693. };
  11694. // Internal functions
  11695. // Buffer allocation
  11696. function createParticleBuffers ( geometry ) {
  11697. geometry.__webglVertexBuffer = _gl.createBuffer();
  11698. geometry.__webglColorBuffer = _gl.createBuffer();
  11699. _this.info.memory.geometries ++;
  11700. };
  11701. function createLineBuffers ( geometry ) {
  11702. geometry.__webglVertexBuffer = _gl.createBuffer();
  11703. geometry.__webglColorBuffer = _gl.createBuffer();
  11704. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  11705. _this.info.memory.geometries ++;
  11706. };
  11707. function createRibbonBuffers ( geometry ) {
  11708. geometry.__webglVertexBuffer = _gl.createBuffer();
  11709. geometry.__webglColorBuffer = _gl.createBuffer();
  11710. geometry.__webglNormalBuffer = _gl.createBuffer();
  11711. _this.info.memory.geometries ++;
  11712. };
  11713. function createMeshBuffers ( geometryGroup ) {
  11714. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  11715. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  11716. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  11717. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  11718. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  11719. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  11720. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  11721. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  11722. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  11723. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  11724. var m, ml;
  11725. if ( geometryGroup.numMorphTargets ) {
  11726. geometryGroup.__webglMorphTargetsBuffers = [];
  11727. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11728. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  11729. }
  11730. }
  11731. if ( geometryGroup.numMorphNormals ) {
  11732. geometryGroup.__webglMorphNormalsBuffers = [];
  11733. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11734. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  11735. }
  11736. }
  11737. _this.info.memory.geometries ++;
  11738. };
  11739. // Events
  11740. var onGeometryDispose = function ( event ) {
  11741. var geometry = event.target;
  11742. geometry.removeEventListener( 'dispose', onGeometryDispose );
  11743. deallocateGeometry( geometry );
  11744. _this.info.memory.geometries --;
  11745. };
  11746. var onTextureDispose = function ( event ) {
  11747. var texture = event.target;
  11748. texture.removeEventListener( 'dispose', onTextureDispose );
  11749. deallocateTexture( texture );
  11750. _this.info.memory.textures --;
  11751. };
  11752. var onRenderTargetDispose = function ( event ) {
  11753. var renderTarget = event.target;
  11754. renderTarget.removeEventListener( 'dispose', onRenderTargetDispose );
  11755. deallocateRenderTarget( renderTarget );
  11756. _this.info.memory.textures --;
  11757. };
  11758. var onMaterialDispose = function ( event ) {
  11759. var material = event.target;
  11760. material.removeEventListener( 'dispose', onMaterialDispose );
  11761. deallocateMaterial( material );
  11762. };
  11763. // Buffer deallocation
  11764. var deallocateGeometry = function ( geometry ) {
  11765. geometry.__webglInit = undefined;
  11766. if ( geometry.__webglVertexBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglVertexBuffer );
  11767. if ( geometry.__webglNormalBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglNormalBuffer );
  11768. if ( geometry.__webglTangentBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglTangentBuffer );
  11769. if ( geometry.__webglColorBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglColorBuffer );
  11770. if ( geometry.__webglUVBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglUVBuffer );
  11771. if ( geometry.__webglUV2Buffer !== undefined ) _gl.deleteBuffer( geometry.__webglUV2Buffer );
  11772. if ( geometry.__webglSkinIndicesBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinIndicesBuffer );
  11773. if ( geometry.__webglSkinWeightsBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglSkinWeightsBuffer );
  11774. if ( geometry.__webglFaceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglFaceBuffer );
  11775. if ( geometry.__webglLineBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineBuffer );
  11776. if ( geometry.__webglLineDistanceBuffer !== undefined ) _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  11777. // geometry groups
  11778. if ( geometry.geometryGroups !== undefined ) {
  11779. for ( var g in geometry.geometryGroups ) {
  11780. var geometryGroup = geometry.geometryGroups[ g ];
  11781. if ( geometryGroup.numMorphTargets !== undefined ) {
  11782. for ( var m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11783. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  11784. }
  11785. }
  11786. if ( geometryGroup.numMorphNormals !== undefined ) {
  11787. for ( var m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11788. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  11789. }
  11790. }
  11791. deleteCustomAttributesBuffers( geometryGroup );
  11792. }
  11793. }
  11794. deleteCustomAttributesBuffers( geometry );
  11795. };
  11796. var deallocateTexture = function ( texture ) {
  11797. if ( texture.image && texture.image.__webglTextureCube ) {
  11798. // cube texture
  11799. _gl.deleteTexture( texture.image.__webglTextureCube );
  11800. } else {
  11801. // 2D texture
  11802. if ( ! texture.__webglInit ) return;
  11803. texture.__webglInit = false;
  11804. _gl.deleteTexture( texture.__webglTexture );
  11805. }
  11806. };
  11807. var deallocateRenderTarget = function ( renderTarget ) {
  11808. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  11809. _gl.deleteTexture( renderTarget.__webglTexture );
  11810. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  11811. for ( var i = 0; i < 6; i ++ ) {
  11812. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  11813. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  11814. }
  11815. } else {
  11816. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  11817. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  11818. }
  11819. };
  11820. var deallocateMaterial = function ( material ) {
  11821. var program = material.program;
  11822. if ( program === undefined ) return;
  11823. material.program = undefined;
  11824. // only deallocate GL program if this was the last use of shared program
  11825. // assumed there is only single copy of any program in the _programs list
  11826. // (that's how it's constructed)
  11827. var i, il, programInfo;
  11828. var deleteProgram = false;
  11829. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11830. programInfo = _programs[ i ];
  11831. if ( programInfo.program === program ) {
  11832. programInfo.usedTimes --;
  11833. if ( programInfo.usedTimes === 0 ) {
  11834. deleteProgram = true;
  11835. }
  11836. break;
  11837. }
  11838. }
  11839. if ( deleteProgram === true ) {
  11840. // avoid using array.splice, this is costlier than creating new array from scratch
  11841. var newPrograms = [];
  11842. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  11843. programInfo = _programs[ i ];
  11844. if ( programInfo.program !== program ) {
  11845. newPrograms.push( programInfo );
  11846. }
  11847. }
  11848. _programs = newPrograms;
  11849. _gl.deleteProgram( program );
  11850. _this.info.memory.programs --;
  11851. }
  11852. };
  11853. //
  11854. function deleteCustomAttributesBuffers( geometry ) {
  11855. if ( geometry.__webglCustomAttributesList ) {
  11856. for ( var id in geometry.__webglCustomAttributesList ) {
  11857. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  11858. }
  11859. }
  11860. };
  11861. // Buffer initialization
  11862. function initCustomAttributes ( geometry, object ) {
  11863. var nvertices = geometry.vertices.length;
  11864. var material = object.material;
  11865. if ( material.attributes ) {
  11866. if ( geometry.__webglCustomAttributesList === undefined ) {
  11867. geometry.__webglCustomAttributesList = [];
  11868. }
  11869. for ( var a in material.attributes ) {
  11870. var attribute = material.attributes[ a ];
  11871. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11872. attribute.__webglInitialized = true;
  11873. var size = 1; // "f" and "i"
  11874. if ( attribute.type === "v2" ) size = 2;
  11875. else if ( attribute.type === "v3" ) size = 3;
  11876. else if ( attribute.type === "v4" ) size = 4;
  11877. else if ( attribute.type === "c" ) size = 3;
  11878. attribute.size = size;
  11879. attribute.array = new Float32Array( nvertices * size );
  11880. attribute.buffer = _gl.createBuffer();
  11881. attribute.buffer.belongsToAttribute = a;
  11882. attribute.needsUpdate = true;
  11883. }
  11884. geometry.__webglCustomAttributesList.push( attribute );
  11885. }
  11886. }
  11887. };
  11888. function initParticleBuffers ( geometry, object ) {
  11889. var nvertices = geometry.vertices.length;
  11890. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11891. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11892. geometry.__sortArray = [];
  11893. geometry.__webglParticleCount = nvertices;
  11894. initCustomAttributes ( geometry, object );
  11895. };
  11896. function initLineBuffers ( geometry, object ) {
  11897. var nvertices = geometry.vertices.length;
  11898. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11899. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11900. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  11901. geometry.__webglLineCount = nvertices;
  11902. initCustomAttributes ( geometry, object );
  11903. };
  11904. function initRibbonBuffers ( geometry, object ) {
  11905. var nvertices = geometry.vertices.length;
  11906. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  11907. geometry.__colorArray = new Float32Array( nvertices * 3 );
  11908. geometry.__normalArray = new Float32Array( nvertices * 3 );
  11909. geometry.__webglVertexCount = nvertices;
  11910. initCustomAttributes ( geometry, object );
  11911. };
  11912. function initMeshBuffers ( geometryGroup, object ) {
  11913. var geometry = object.geometry,
  11914. faces3 = geometryGroup.faces3,
  11915. faces4 = geometryGroup.faces4,
  11916. nvertices = faces3.length * 3 + faces4.length * 4,
  11917. ntris = faces3.length * 1 + faces4.length * 2,
  11918. nlines = faces3.length * 3 + faces4.length * 4,
  11919. material = getBufferMaterial( object, geometryGroup ),
  11920. uvType = bufferGuessUVType( material ),
  11921. normalType = bufferGuessNormalType( material ),
  11922. vertexColorType = bufferGuessVertexColorType( material );
  11923. // console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  11924. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  11925. if ( normalType ) {
  11926. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  11927. }
  11928. if ( geometry.hasTangents ) {
  11929. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  11930. }
  11931. if ( vertexColorType ) {
  11932. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  11933. }
  11934. if ( uvType ) {
  11935. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  11936. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  11937. }
  11938. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  11939. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  11940. }
  11941. }
  11942. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  11943. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  11944. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  11945. }
  11946. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  11947. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  11948. var m, ml;
  11949. if ( geometryGroup.numMorphTargets ) {
  11950. geometryGroup.__morphTargetsArrays = [];
  11951. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  11952. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  11953. }
  11954. }
  11955. if ( geometryGroup.numMorphNormals ) {
  11956. geometryGroup.__morphNormalsArrays = [];
  11957. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  11958. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  11959. }
  11960. }
  11961. geometryGroup.__webglFaceCount = ntris * 3;
  11962. geometryGroup.__webglLineCount = nlines * 2;
  11963. // custom attributes
  11964. if ( material.attributes ) {
  11965. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  11966. geometryGroup.__webglCustomAttributesList = [];
  11967. }
  11968. for ( var a in material.attributes ) {
  11969. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  11970. // attribute buffers which are correctly indexed in the setMeshBuffers function
  11971. var originalAttribute = material.attributes[ a ];
  11972. var attribute = {};
  11973. for ( var property in originalAttribute ) {
  11974. attribute[ property ] = originalAttribute[ property ];
  11975. }
  11976. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  11977. attribute.__webglInitialized = true;
  11978. var size = 1; // "f" and "i"
  11979. if( attribute.type === "v2" ) size = 2;
  11980. else if( attribute.type === "v3" ) size = 3;
  11981. else if( attribute.type === "v4" ) size = 4;
  11982. else if( attribute.type === "c" ) size = 3;
  11983. attribute.size = size;
  11984. attribute.array = new Float32Array( nvertices * size );
  11985. attribute.buffer = _gl.createBuffer();
  11986. attribute.buffer.belongsToAttribute = a;
  11987. originalAttribute.needsUpdate = true;
  11988. attribute.__original = originalAttribute;
  11989. }
  11990. geometryGroup.__webglCustomAttributesList.push( attribute );
  11991. }
  11992. }
  11993. geometryGroup.__inittedArrays = true;
  11994. };
  11995. function getBufferMaterial( object, geometryGroup ) {
  11996. return object.material instanceof THREE.MeshFaceMaterial
  11997. ? object.material.materials[ geometryGroup.materialIndex ]
  11998. : object.material;
  11999. };
  12000. function materialNeedsSmoothNormals ( material ) {
  12001. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  12002. };
  12003. function bufferGuessNormalType ( material ) {
  12004. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  12005. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  12006. return false;
  12007. }
  12008. if ( materialNeedsSmoothNormals( material ) ) {
  12009. return THREE.SmoothShading;
  12010. } else {
  12011. return THREE.FlatShading;
  12012. }
  12013. };
  12014. function bufferGuessVertexColorType( material ) {
  12015. if ( material.vertexColors ) {
  12016. return material.vertexColors;
  12017. }
  12018. return false;
  12019. };
  12020. function bufferGuessUVType( material ) {
  12021. // material must use some texture to require uvs
  12022. if ( material.map ||
  12023. material.lightMap ||
  12024. material.bumpMap ||
  12025. material.normalMap ||
  12026. material.specularMap ||
  12027. material instanceof THREE.ShaderMaterial ) {
  12028. return true;
  12029. }
  12030. return false;
  12031. };
  12032. //
  12033. function initDirectBuffers( geometry ) {
  12034. var a, attribute, type;
  12035. for ( a in geometry.attributes ) {
  12036. if ( a === "index" ) {
  12037. type = _gl.ELEMENT_ARRAY_BUFFER;
  12038. } else {
  12039. type = _gl.ARRAY_BUFFER;
  12040. }
  12041. attribute = geometry.attributes[ a ];
  12042. if ( attribute.numItems === undefined ) {
  12043. attribute.numItems = attribute.array.length;
  12044. }
  12045. attribute.buffer = _gl.createBuffer();
  12046. _gl.bindBuffer( type, attribute.buffer );
  12047. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  12048. }
  12049. };
  12050. // Buffer setting
  12051. function setParticleBuffers ( geometry, hint, object ) {
  12052. var v, c, vertex, offset, index, color,
  12053. vertices = geometry.vertices,
  12054. vl = vertices.length,
  12055. colors = geometry.colors,
  12056. cl = colors.length,
  12057. vertexArray = geometry.__vertexArray,
  12058. colorArray = geometry.__colorArray,
  12059. sortArray = geometry.__sortArray,
  12060. dirtyVertices = geometry.verticesNeedUpdate,
  12061. dirtyElements = geometry.elementsNeedUpdate,
  12062. dirtyColors = geometry.colorsNeedUpdate,
  12063. customAttributes = geometry.__webglCustomAttributesList,
  12064. i, il,
  12065. a, ca, cal, value,
  12066. customAttribute;
  12067. if ( object.sortParticles ) {
  12068. _projScreenMatrixPS.copy( _projScreenMatrix );
  12069. _projScreenMatrixPS.multiply( object.matrixWorld );
  12070. for ( v = 0; v < vl; v ++ ) {
  12071. vertex = vertices[ v ];
  12072. _vector3.copy( vertex );
  12073. _vector3.applyProjection( _projScreenMatrixPS );
  12074. sortArray[ v ] = [ _vector3.z, v ];
  12075. }
  12076. sortArray.sort( numericalSort );
  12077. for ( v = 0; v < vl; v ++ ) {
  12078. vertex = vertices[ sortArray[v][1] ];
  12079. offset = v * 3;
  12080. vertexArray[ offset ] = vertex.x;
  12081. vertexArray[ offset + 1 ] = vertex.y;
  12082. vertexArray[ offset + 2 ] = vertex.z;
  12083. }
  12084. for ( c = 0; c < cl; c ++ ) {
  12085. offset = c * 3;
  12086. color = colors[ sortArray[c][1] ];
  12087. colorArray[ offset ] = color.r;
  12088. colorArray[ offset + 1 ] = color.g;
  12089. colorArray[ offset + 2 ] = color.b;
  12090. }
  12091. if ( customAttributes ) {
  12092. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12093. customAttribute = customAttributes[ i ];
  12094. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  12095. offset = 0;
  12096. cal = customAttribute.value.length;
  12097. if ( customAttribute.size === 1 ) {
  12098. for ( ca = 0; ca < cal; ca ++ ) {
  12099. index = sortArray[ ca ][ 1 ];
  12100. customAttribute.array[ ca ] = customAttribute.value[ index ];
  12101. }
  12102. } else if ( customAttribute.size === 2 ) {
  12103. for ( ca = 0; ca < cal; ca ++ ) {
  12104. index = sortArray[ ca ][ 1 ];
  12105. value = customAttribute.value[ index ];
  12106. customAttribute.array[ offset ] = value.x;
  12107. customAttribute.array[ offset + 1 ] = value.y;
  12108. offset += 2;
  12109. }
  12110. } else if ( customAttribute.size === 3 ) {
  12111. if ( customAttribute.type === "c" ) {
  12112. for ( ca = 0; ca < cal; ca ++ ) {
  12113. index = sortArray[ ca ][ 1 ];
  12114. value = customAttribute.value[ index ];
  12115. customAttribute.array[ offset ] = value.r;
  12116. customAttribute.array[ offset + 1 ] = value.g;
  12117. customAttribute.array[ offset + 2 ] = value.b;
  12118. offset += 3;
  12119. }
  12120. } else {
  12121. for ( ca = 0; ca < cal; ca ++ ) {
  12122. index = sortArray[ ca ][ 1 ];
  12123. value = customAttribute.value[ index ];
  12124. customAttribute.array[ offset ] = value.x;
  12125. customAttribute.array[ offset + 1 ] = value.y;
  12126. customAttribute.array[ offset + 2 ] = value.z;
  12127. offset += 3;
  12128. }
  12129. }
  12130. } else if ( customAttribute.size === 4 ) {
  12131. for ( ca = 0; ca < cal; ca ++ ) {
  12132. index = sortArray[ ca ][ 1 ];
  12133. value = customAttribute.value[ index ];
  12134. customAttribute.array[ offset ] = value.x;
  12135. customAttribute.array[ offset + 1 ] = value.y;
  12136. customAttribute.array[ offset + 2 ] = value.z;
  12137. customAttribute.array[ offset + 3 ] = value.w;
  12138. offset += 4;
  12139. }
  12140. }
  12141. }
  12142. }
  12143. } else {
  12144. if ( dirtyVertices ) {
  12145. for ( v = 0; v < vl; v ++ ) {
  12146. vertex = vertices[ v ];
  12147. offset = v * 3;
  12148. vertexArray[ offset ] = vertex.x;
  12149. vertexArray[ offset + 1 ] = vertex.y;
  12150. vertexArray[ offset + 2 ] = vertex.z;
  12151. }
  12152. }
  12153. if ( dirtyColors ) {
  12154. for ( c = 0; c < cl; c ++ ) {
  12155. color = colors[ c ];
  12156. offset = c * 3;
  12157. colorArray[ offset ] = color.r;
  12158. colorArray[ offset + 1 ] = color.g;
  12159. colorArray[ offset + 2 ] = color.b;
  12160. }
  12161. }
  12162. if ( customAttributes ) {
  12163. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12164. customAttribute = customAttributes[ i ];
  12165. if ( customAttribute.needsUpdate &&
  12166. ( customAttribute.boundTo === undefined ||
  12167. customAttribute.boundTo === "vertices") ) {
  12168. cal = customAttribute.value.length;
  12169. offset = 0;
  12170. if ( customAttribute.size === 1 ) {
  12171. for ( ca = 0; ca < cal; ca ++ ) {
  12172. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12173. }
  12174. } else if ( customAttribute.size === 2 ) {
  12175. for ( ca = 0; ca < cal; ca ++ ) {
  12176. value = customAttribute.value[ ca ];
  12177. customAttribute.array[ offset ] = value.x;
  12178. customAttribute.array[ offset + 1 ] = value.y;
  12179. offset += 2;
  12180. }
  12181. } else if ( customAttribute.size === 3 ) {
  12182. if ( customAttribute.type === "c" ) {
  12183. for ( ca = 0; ca < cal; ca ++ ) {
  12184. value = customAttribute.value[ ca ];
  12185. customAttribute.array[ offset ] = value.r;
  12186. customAttribute.array[ offset + 1 ] = value.g;
  12187. customAttribute.array[ offset + 2 ] = value.b;
  12188. offset += 3;
  12189. }
  12190. } else {
  12191. for ( ca = 0; ca < cal; ca ++ ) {
  12192. value = customAttribute.value[ ca ];
  12193. customAttribute.array[ offset ] = value.x;
  12194. customAttribute.array[ offset + 1 ] = value.y;
  12195. customAttribute.array[ offset + 2 ] = value.z;
  12196. offset += 3;
  12197. }
  12198. }
  12199. } else if ( customAttribute.size === 4 ) {
  12200. for ( ca = 0; ca < cal; ca ++ ) {
  12201. value = customAttribute.value[ ca ];
  12202. customAttribute.array[ offset ] = value.x;
  12203. customAttribute.array[ offset + 1 ] = value.y;
  12204. customAttribute.array[ offset + 2 ] = value.z;
  12205. customAttribute.array[ offset + 3 ] = value.w;
  12206. offset += 4;
  12207. }
  12208. }
  12209. }
  12210. }
  12211. }
  12212. }
  12213. if ( dirtyVertices || object.sortParticles ) {
  12214. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12215. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12216. }
  12217. if ( dirtyColors || object.sortParticles ) {
  12218. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12219. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12220. }
  12221. if ( customAttributes ) {
  12222. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12223. customAttribute = customAttributes[ i ];
  12224. if ( customAttribute.needsUpdate || object.sortParticles ) {
  12225. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12226. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12227. }
  12228. }
  12229. }
  12230. };
  12231. function setLineBuffers ( geometry, hint ) {
  12232. var v, c, d, vertex, offset, color,
  12233. vertices = geometry.vertices,
  12234. colors = geometry.colors,
  12235. lineDistances = geometry.lineDistances,
  12236. vl = vertices.length,
  12237. cl = colors.length,
  12238. dl = lineDistances.length,
  12239. vertexArray = geometry.__vertexArray,
  12240. colorArray = geometry.__colorArray,
  12241. lineDistanceArray = geometry.__lineDistanceArray,
  12242. dirtyVertices = geometry.verticesNeedUpdate,
  12243. dirtyColors = geometry.colorsNeedUpdate,
  12244. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  12245. customAttributes = geometry.__webglCustomAttributesList,
  12246. i, il,
  12247. a, ca, cal, value,
  12248. customAttribute;
  12249. if ( dirtyVertices ) {
  12250. for ( v = 0; v < vl; v ++ ) {
  12251. vertex = vertices[ v ];
  12252. offset = v * 3;
  12253. vertexArray[ offset ] = vertex.x;
  12254. vertexArray[ offset + 1 ] = vertex.y;
  12255. vertexArray[ offset + 2 ] = vertex.z;
  12256. }
  12257. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12258. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12259. }
  12260. if ( dirtyColors ) {
  12261. for ( c = 0; c < cl; c ++ ) {
  12262. color = colors[ c ];
  12263. offset = c * 3;
  12264. colorArray[ offset ] = color.r;
  12265. colorArray[ offset + 1 ] = color.g;
  12266. colorArray[ offset + 2 ] = color.b;
  12267. }
  12268. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12269. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12270. }
  12271. if ( dirtyLineDistances ) {
  12272. for ( d = 0; d < dl; d ++ ) {
  12273. lineDistanceArray[ d ] = lineDistances[ d ];
  12274. }
  12275. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  12276. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  12277. }
  12278. if ( customAttributes ) {
  12279. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12280. customAttribute = customAttributes[ i ];
  12281. if ( customAttribute.needsUpdate &&
  12282. ( customAttribute.boundTo === undefined ||
  12283. customAttribute.boundTo === "vertices" ) ) {
  12284. offset = 0;
  12285. cal = customAttribute.value.length;
  12286. if ( customAttribute.size === 1 ) {
  12287. for ( ca = 0; ca < cal; ca ++ ) {
  12288. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12289. }
  12290. } else if ( customAttribute.size === 2 ) {
  12291. for ( ca = 0; ca < cal; ca ++ ) {
  12292. value = customAttribute.value[ ca ];
  12293. customAttribute.array[ offset ] = value.x;
  12294. customAttribute.array[ offset + 1 ] = value.y;
  12295. offset += 2;
  12296. }
  12297. } else if ( customAttribute.size === 3 ) {
  12298. if ( customAttribute.type === "c" ) {
  12299. for ( ca = 0; ca < cal; ca ++ ) {
  12300. value = customAttribute.value[ ca ];
  12301. customAttribute.array[ offset ] = value.r;
  12302. customAttribute.array[ offset + 1 ] = value.g;
  12303. customAttribute.array[ offset + 2 ] = value.b;
  12304. offset += 3;
  12305. }
  12306. } else {
  12307. for ( ca = 0; ca < cal; ca ++ ) {
  12308. value = customAttribute.value[ ca ];
  12309. customAttribute.array[ offset ] = value.x;
  12310. customAttribute.array[ offset + 1 ] = value.y;
  12311. customAttribute.array[ offset + 2 ] = value.z;
  12312. offset += 3;
  12313. }
  12314. }
  12315. } else if ( customAttribute.size === 4 ) {
  12316. for ( ca = 0; ca < cal; ca ++ ) {
  12317. value = customAttribute.value[ ca ];
  12318. customAttribute.array[ offset ] = value.x;
  12319. customAttribute.array[ offset + 1 ] = value.y;
  12320. customAttribute.array[ offset + 2 ] = value.z;
  12321. customAttribute.array[ offset + 3 ] = value.w;
  12322. offset += 4;
  12323. }
  12324. }
  12325. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12326. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12327. }
  12328. }
  12329. }
  12330. };
  12331. function setRibbonBuffers ( geometry, hint ) {
  12332. var v, c, n, vertex, offset, color, normal,
  12333. i, il, ca, cal, customAttribute, value,
  12334. vertices = geometry.vertices,
  12335. colors = geometry.colors,
  12336. normals = geometry.normals,
  12337. vl = vertices.length,
  12338. cl = colors.length,
  12339. nl = normals.length,
  12340. vertexArray = geometry.__vertexArray,
  12341. colorArray = geometry.__colorArray,
  12342. normalArray = geometry.__normalArray,
  12343. dirtyVertices = geometry.verticesNeedUpdate,
  12344. dirtyColors = geometry.colorsNeedUpdate,
  12345. dirtyNormals = geometry.normalsNeedUpdate,
  12346. customAttributes = geometry.__webglCustomAttributesList;
  12347. if ( dirtyVertices ) {
  12348. for ( v = 0; v < vl; v ++ ) {
  12349. vertex = vertices[ v ];
  12350. offset = v * 3;
  12351. vertexArray[ offset ] = vertex.x;
  12352. vertexArray[ offset + 1 ] = vertex.y;
  12353. vertexArray[ offset + 2 ] = vertex.z;
  12354. }
  12355. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  12356. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12357. }
  12358. if ( dirtyColors ) {
  12359. for ( c = 0; c < cl; c ++ ) {
  12360. color = colors[ c ];
  12361. offset = c * 3;
  12362. colorArray[ offset ] = color.r;
  12363. colorArray[ offset + 1 ] = color.g;
  12364. colorArray[ offset + 2 ] = color.b;
  12365. }
  12366. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  12367. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12368. }
  12369. if ( dirtyNormals ) {
  12370. for ( n = 0; n < nl; n ++ ) {
  12371. normal = normals[ n ];
  12372. offset = n * 3;
  12373. normalArray[ offset ] = normal.x;
  12374. normalArray[ offset + 1 ] = normal.y;
  12375. normalArray[ offset + 2 ] = normal.z;
  12376. }
  12377. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  12378. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12379. }
  12380. if ( customAttributes ) {
  12381. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12382. customAttribute = customAttributes[ i ];
  12383. if ( customAttribute.needsUpdate &&
  12384. ( customAttribute.boundTo === undefined ||
  12385. customAttribute.boundTo === "vertices" ) ) {
  12386. offset = 0;
  12387. cal = customAttribute.value.length;
  12388. if ( customAttribute.size === 1 ) {
  12389. for ( ca = 0; ca < cal; ca ++ ) {
  12390. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  12391. }
  12392. } else if ( customAttribute.size === 2 ) {
  12393. for ( ca = 0; ca < cal; ca ++ ) {
  12394. value = customAttribute.value[ ca ];
  12395. customAttribute.array[ offset ] = value.x;
  12396. customAttribute.array[ offset + 1 ] = value.y;
  12397. offset += 2;
  12398. }
  12399. } else if ( customAttribute.size === 3 ) {
  12400. if ( customAttribute.type === "c" ) {
  12401. for ( ca = 0; ca < cal; ca ++ ) {
  12402. value = customAttribute.value[ ca ];
  12403. customAttribute.array[ offset ] = value.r;
  12404. customAttribute.array[ offset + 1 ] = value.g;
  12405. customAttribute.array[ offset + 2 ] = value.b;
  12406. offset += 3;
  12407. }
  12408. } else {
  12409. for ( ca = 0; ca < cal; ca ++ ) {
  12410. value = customAttribute.value[ ca ];
  12411. customAttribute.array[ offset ] = value.x;
  12412. customAttribute.array[ offset + 1 ] = value.y;
  12413. customAttribute.array[ offset + 2 ] = value.z;
  12414. offset += 3;
  12415. }
  12416. }
  12417. } else if ( customAttribute.size === 4 ) {
  12418. for ( ca = 0; ca < cal; ca ++ ) {
  12419. value = customAttribute.value[ ca ];
  12420. customAttribute.array[ offset ] = value.x;
  12421. customAttribute.array[ offset + 1 ] = value.y;
  12422. customAttribute.array[ offset + 2 ] = value.z;
  12423. customAttribute.array[ offset + 3 ] = value.w;
  12424. offset += 4;
  12425. }
  12426. }
  12427. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  12428. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  12429. }
  12430. }
  12431. }
  12432. };
  12433. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  12434. if ( ! geometryGroup.__inittedArrays ) {
  12435. return;
  12436. }
  12437. var normalType = bufferGuessNormalType( material ),
  12438. vertexColorType = bufferGuessVertexColorType( material ),
  12439. uvType = bufferGuessUVType( material ),
  12440. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  12441. var f, fl, fi, face,
  12442. vertexNormals, faceNormal, normal,
  12443. vertexColors, faceColor,
  12444. vertexTangents,
  12445. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  12446. c1, c2, c3, c4,
  12447. sw1, sw2, sw3, sw4,
  12448. si1, si2, si3, si4,
  12449. sa1, sa2, sa3, sa4,
  12450. sb1, sb2, sb3, sb4,
  12451. m, ml, i, il,
  12452. vn, uvi, uv2i,
  12453. vk, vkl, vka,
  12454. nka, chf, faceVertexNormals,
  12455. a,
  12456. vertexIndex = 0,
  12457. offset = 0,
  12458. offset_uv = 0,
  12459. offset_uv2 = 0,
  12460. offset_face = 0,
  12461. offset_normal = 0,
  12462. offset_tangent = 0,
  12463. offset_line = 0,
  12464. offset_color = 0,
  12465. offset_skin = 0,
  12466. offset_morphTarget = 0,
  12467. offset_custom = 0,
  12468. offset_customSrc = 0,
  12469. value,
  12470. vertexArray = geometryGroup.__vertexArray,
  12471. uvArray = geometryGroup.__uvArray,
  12472. uv2Array = geometryGroup.__uv2Array,
  12473. normalArray = geometryGroup.__normalArray,
  12474. tangentArray = geometryGroup.__tangentArray,
  12475. colorArray = geometryGroup.__colorArray,
  12476. skinIndexArray = geometryGroup.__skinIndexArray,
  12477. skinWeightArray = geometryGroup.__skinWeightArray,
  12478. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  12479. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  12480. customAttributes = geometryGroup.__webglCustomAttributesList,
  12481. customAttribute,
  12482. faceArray = geometryGroup.__faceArray,
  12483. lineArray = geometryGroup.__lineArray,
  12484. geometry = object.geometry, // this is shared for all chunks
  12485. dirtyVertices = geometry.verticesNeedUpdate,
  12486. dirtyElements = geometry.elementsNeedUpdate,
  12487. dirtyUvs = geometry.uvsNeedUpdate,
  12488. dirtyNormals = geometry.normalsNeedUpdate,
  12489. dirtyTangents = geometry.tangentsNeedUpdate,
  12490. dirtyColors = geometry.colorsNeedUpdate,
  12491. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  12492. vertices = geometry.vertices,
  12493. chunk_faces3 = geometryGroup.faces3,
  12494. chunk_faces4 = geometryGroup.faces4,
  12495. obj_faces = geometry.faces,
  12496. obj_uvs = geometry.faceVertexUvs[ 0 ],
  12497. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  12498. obj_colors = geometry.colors,
  12499. obj_skinIndices = geometry.skinIndices,
  12500. obj_skinWeights = geometry.skinWeights,
  12501. morphTargets = geometry.morphTargets,
  12502. morphNormals = geometry.morphNormals;
  12503. if ( dirtyVertices ) {
  12504. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12505. face = obj_faces[ chunk_faces3[ f ] ];
  12506. v1 = vertices[ face.a ];
  12507. v2 = vertices[ face.b ];
  12508. v3 = vertices[ face.c ];
  12509. vertexArray[ offset ] = v1.x;
  12510. vertexArray[ offset + 1 ] = v1.y;
  12511. vertexArray[ offset + 2 ] = v1.z;
  12512. vertexArray[ offset + 3 ] = v2.x;
  12513. vertexArray[ offset + 4 ] = v2.y;
  12514. vertexArray[ offset + 5 ] = v2.z;
  12515. vertexArray[ offset + 6 ] = v3.x;
  12516. vertexArray[ offset + 7 ] = v3.y;
  12517. vertexArray[ offset + 8 ] = v3.z;
  12518. offset += 9;
  12519. }
  12520. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12521. face = obj_faces[ chunk_faces4[ f ] ];
  12522. v1 = vertices[ face.a ];
  12523. v2 = vertices[ face.b ];
  12524. v3 = vertices[ face.c ];
  12525. v4 = vertices[ face.d ];
  12526. vertexArray[ offset ] = v1.x;
  12527. vertexArray[ offset + 1 ] = v1.y;
  12528. vertexArray[ offset + 2 ] = v1.z;
  12529. vertexArray[ offset + 3 ] = v2.x;
  12530. vertexArray[ offset + 4 ] = v2.y;
  12531. vertexArray[ offset + 5 ] = v2.z;
  12532. vertexArray[ offset + 6 ] = v3.x;
  12533. vertexArray[ offset + 7 ] = v3.y;
  12534. vertexArray[ offset + 8 ] = v3.z;
  12535. vertexArray[ offset + 9 ] = v4.x;
  12536. vertexArray[ offset + 10 ] = v4.y;
  12537. vertexArray[ offset + 11 ] = v4.z;
  12538. offset += 12;
  12539. }
  12540. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12541. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  12542. }
  12543. if ( dirtyMorphTargets ) {
  12544. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  12545. offset_morphTarget = 0;
  12546. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12547. chf = chunk_faces3[ f ];
  12548. face = obj_faces[ chf ];
  12549. // morph positions
  12550. v1 = morphTargets[ vk ].vertices[ face.a ];
  12551. v2 = morphTargets[ vk ].vertices[ face.b ];
  12552. v3 = morphTargets[ vk ].vertices[ face.c ];
  12553. vka = morphTargetsArrays[ vk ];
  12554. vka[ offset_morphTarget ] = v1.x;
  12555. vka[ offset_morphTarget + 1 ] = v1.y;
  12556. vka[ offset_morphTarget + 2 ] = v1.z;
  12557. vka[ offset_morphTarget + 3 ] = v2.x;
  12558. vka[ offset_morphTarget + 4 ] = v2.y;
  12559. vka[ offset_morphTarget + 5 ] = v2.z;
  12560. vka[ offset_morphTarget + 6 ] = v3.x;
  12561. vka[ offset_morphTarget + 7 ] = v3.y;
  12562. vka[ offset_morphTarget + 8 ] = v3.z;
  12563. // morph normals
  12564. if ( material.morphNormals ) {
  12565. if ( needsSmoothNormals ) {
  12566. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12567. n1 = faceVertexNormals.a;
  12568. n2 = faceVertexNormals.b;
  12569. n3 = faceVertexNormals.c;
  12570. } else {
  12571. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12572. n2 = n1;
  12573. n3 = n1;
  12574. }
  12575. nka = morphNormalsArrays[ vk ];
  12576. nka[ offset_morphTarget ] = n1.x;
  12577. nka[ offset_morphTarget + 1 ] = n1.y;
  12578. nka[ offset_morphTarget + 2 ] = n1.z;
  12579. nka[ offset_morphTarget + 3 ] = n2.x;
  12580. nka[ offset_morphTarget + 4 ] = n2.y;
  12581. nka[ offset_morphTarget + 5 ] = n2.z;
  12582. nka[ offset_morphTarget + 6 ] = n3.x;
  12583. nka[ offset_morphTarget + 7 ] = n3.y;
  12584. nka[ offset_morphTarget + 8 ] = n3.z;
  12585. }
  12586. //
  12587. offset_morphTarget += 9;
  12588. }
  12589. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12590. chf = chunk_faces4[ f ];
  12591. face = obj_faces[ chf ];
  12592. // morph positions
  12593. v1 = morphTargets[ vk ].vertices[ face.a ];
  12594. v2 = morphTargets[ vk ].vertices[ face.b ];
  12595. v3 = morphTargets[ vk ].vertices[ face.c ];
  12596. v4 = morphTargets[ vk ].vertices[ face.d ];
  12597. vka = morphTargetsArrays[ vk ];
  12598. vka[ offset_morphTarget ] = v1.x;
  12599. vka[ offset_morphTarget + 1 ] = v1.y;
  12600. vka[ offset_morphTarget + 2 ] = v1.z;
  12601. vka[ offset_morphTarget + 3 ] = v2.x;
  12602. vka[ offset_morphTarget + 4 ] = v2.y;
  12603. vka[ offset_morphTarget + 5 ] = v2.z;
  12604. vka[ offset_morphTarget + 6 ] = v3.x;
  12605. vka[ offset_morphTarget + 7 ] = v3.y;
  12606. vka[ offset_morphTarget + 8 ] = v3.z;
  12607. vka[ offset_morphTarget + 9 ] = v4.x;
  12608. vka[ offset_morphTarget + 10 ] = v4.y;
  12609. vka[ offset_morphTarget + 11 ] = v4.z;
  12610. // morph normals
  12611. if ( material.morphNormals ) {
  12612. if ( needsSmoothNormals ) {
  12613. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  12614. n1 = faceVertexNormals.a;
  12615. n2 = faceVertexNormals.b;
  12616. n3 = faceVertexNormals.c;
  12617. n4 = faceVertexNormals.d;
  12618. } else {
  12619. n1 = morphNormals[ vk ].faceNormals[ chf ];
  12620. n2 = n1;
  12621. n3 = n1;
  12622. n4 = n1;
  12623. }
  12624. nka = morphNormalsArrays[ vk ];
  12625. nka[ offset_morphTarget ] = n1.x;
  12626. nka[ offset_morphTarget + 1 ] = n1.y;
  12627. nka[ offset_morphTarget + 2 ] = n1.z;
  12628. nka[ offset_morphTarget + 3 ] = n2.x;
  12629. nka[ offset_morphTarget + 4 ] = n2.y;
  12630. nka[ offset_morphTarget + 5 ] = n2.z;
  12631. nka[ offset_morphTarget + 6 ] = n3.x;
  12632. nka[ offset_morphTarget + 7 ] = n3.y;
  12633. nka[ offset_morphTarget + 8 ] = n3.z;
  12634. nka[ offset_morphTarget + 9 ] = n4.x;
  12635. nka[ offset_morphTarget + 10 ] = n4.y;
  12636. nka[ offset_morphTarget + 11 ] = n4.z;
  12637. }
  12638. //
  12639. offset_morphTarget += 12;
  12640. }
  12641. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  12642. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  12643. if ( material.morphNormals ) {
  12644. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  12645. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  12646. }
  12647. }
  12648. }
  12649. if ( obj_skinWeights.length ) {
  12650. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12651. face = obj_faces[ chunk_faces3[ f ] ];
  12652. // weights
  12653. sw1 = obj_skinWeights[ face.a ];
  12654. sw2 = obj_skinWeights[ face.b ];
  12655. sw3 = obj_skinWeights[ face.c ];
  12656. skinWeightArray[ offset_skin ] = sw1.x;
  12657. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12658. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12659. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12660. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12661. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12662. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12663. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12664. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12665. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12666. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12667. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12668. // indices
  12669. si1 = obj_skinIndices[ face.a ];
  12670. si2 = obj_skinIndices[ face.b ];
  12671. si3 = obj_skinIndices[ face.c ];
  12672. skinIndexArray[ offset_skin ] = si1.x;
  12673. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12674. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12675. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12676. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12677. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12678. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12679. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12680. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12681. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12682. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12683. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12684. offset_skin += 12;
  12685. }
  12686. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12687. face = obj_faces[ chunk_faces4[ f ] ];
  12688. // weights
  12689. sw1 = obj_skinWeights[ face.a ];
  12690. sw2 = obj_skinWeights[ face.b ];
  12691. sw3 = obj_skinWeights[ face.c ];
  12692. sw4 = obj_skinWeights[ face.d ];
  12693. skinWeightArray[ offset_skin ] = sw1.x;
  12694. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  12695. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  12696. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  12697. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  12698. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  12699. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  12700. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  12701. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  12702. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  12703. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  12704. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  12705. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  12706. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  12707. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  12708. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  12709. // indices
  12710. si1 = obj_skinIndices[ face.a ];
  12711. si2 = obj_skinIndices[ face.b ];
  12712. si3 = obj_skinIndices[ face.c ];
  12713. si4 = obj_skinIndices[ face.d ];
  12714. skinIndexArray[ offset_skin ] = si1.x;
  12715. skinIndexArray[ offset_skin + 1 ] = si1.y;
  12716. skinIndexArray[ offset_skin + 2 ] = si1.z;
  12717. skinIndexArray[ offset_skin + 3 ] = si1.w;
  12718. skinIndexArray[ offset_skin + 4 ] = si2.x;
  12719. skinIndexArray[ offset_skin + 5 ] = si2.y;
  12720. skinIndexArray[ offset_skin + 6 ] = si2.z;
  12721. skinIndexArray[ offset_skin + 7 ] = si2.w;
  12722. skinIndexArray[ offset_skin + 8 ] = si3.x;
  12723. skinIndexArray[ offset_skin + 9 ] = si3.y;
  12724. skinIndexArray[ offset_skin + 10 ] = si3.z;
  12725. skinIndexArray[ offset_skin + 11 ] = si3.w;
  12726. skinIndexArray[ offset_skin + 12 ] = si4.x;
  12727. skinIndexArray[ offset_skin + 13 ] = si4.y;
  12728. skinIndexArray[ offset_skin + 14 ] = si4.z;
  12729. skinIndexArray[ offset_skin + 15 ] = si4.w;
  12730. offset_skin += 16;
  12731. }
  12732. if ( offset_skin > 0 ) {
  12733. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12734. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  12735. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12736. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  12737. }
  12738. }
  12739. if ( dirtyColors && vertexColorType ) {
  12740. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12741. face = obj_faces[ chunk_faces3[ f ] ];
  12742. vertexColors = face.vertexColors;
  12743. faceColor = face.color;
  12744. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  12745. c1 = vertexColors[ 0 ];
  12746. c2 = vertexColors[ 1 ];
  12747. c3 = vertexColors[ 2 ];
  12748. } else {
  12749. c1 = faceColor;
  12750. c2 = faceColor;
  12751. c3 = faceColor;
  12752. }
  12753. colorArray[ offset_color ] = c1.r;
  12754. colorArray[ offset_color + 1 ] = c1.g;
  12755. colorArray[ offset_color + 2 ] = c1.b;
  12756. colorArray[ offset_color + 3 ] = c2.r;
  12757. colorArray[ offset_color + 4 ] = c2.g;
  12758. colorArray[ offset_color + 5 ] = c2.b;
  12759. colorArray[ offset_color + 6 ] = c3.r;
  12760. colorArray[ offset_color + 7 ] = c3.g;
  12761. colorArray[ offset_color + 8 ] = c3.b;
  12762. offset_color += 9;
  12763. }
  12764. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12765. face = obj_faces[ chunk_faces4[ f ] ];
  12766. vertexColors = face.vertexColors;
  12767. faceColor = face.color;
  12768. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  12769. c1 = vertexColors[ 0 ];
  12770. c2 = vertexColors[ 1 ];
  12771. c3 = vertexColors[ 2 ];
  12772. c4 = vertexColors[ 3 ];
  12773. } else {
  12774. c1 = faceColor;
  12775. c2 = faceColor;
  12776. c3 = faceColor;
  12777. c4 = faceColor;
  12778. }
  12779. colorArray[ offset_color ] = c1.r;
  12780. colorArray[ offset_color + 1 ] = c1.g;
  12781. colorArray[ offset_color + 2 ] = c1.b;
  12782. colorArray[ offset_color + 3 ] = c2.r;
  12783. colorArray[ offset_color + 4 ] = c2.g;
  12784. colorArray[ offset_color + 5 ] = c2.b;
  12785. colorArray[ offset_color + 6 ] = c3.r;
  12786. colorArray[ offset_color + 7 ] = c3.g;
  12787. colorArray[ offset_color + 8 ] = c3.b;
  12788. colorArray[ offset_color + 9 ] = c4.r;
  12789. colorArray[ offset_color + 10 ] = c4.g;
  12790. colorArray[ offset_color + 11 ] = c4.b;
  12791. offset_color += 12;
  12792. }
  12793. if ( offset_color > 0 ) {
  12794. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12795. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  12796. }
  12797. }
  12798. if ( dirtyTangents && geometry.hasTangents ) {
  12799. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12800. face = obj_faces[ chunk_faces3[ f ] ];
  12801. vertexTangents = face.vertexTangents;
  12802. t1 = vertexTangents[ 0 ];
  12803. t2 = vertexTangents[ 1 ];
  12804. t3 = vertexTangents[ 2 ];
  12805. tangentArray[ offset_tangent ] = t1.x;
  12806. tangentArray[ offset_tangent + 1 ] = t1.y;
  12807. tangentArray[ offset_tangent + 2 ] = t1.z;
  12808. tangentArray[ offset_tangent + 3 ] = t1.w;
  12809. tangentArray[ offset_tangent + 4 ] = t2.x;
  12810. tangentArray[ offset_tangent + 5 ] = t2.y;
  12811. tangentArray[ offset_tangent + 6 ] = t2.z;
  12812. tangentArray[ offset_tangent + 7 ] = t2.w;
  12813. tangentArray[ offset_tangent + 8 ] = t3.x;
  12814. tangentArray[ offset_tangent + 9 ] = t3.y;
  12815. tangentArray[ offset_tangent + 10 ] = t3.z;
  12816. tangentArray[ offset_tangent + 11 ] = t3.w;
  12817. offset_tangent += 12;
  12818. }
  12819. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12820. face = obj_faces[ chunk_faces4[ f ] ];
  12821. vertexTangents = face.vertexTangents;
  12822. t1 = vertexTangents[ 0 ];
  12823. t2 = vertexTangents[ 1 ];
  12824. t3 = vertexTangents[ 2 ];
  12825. t4 = vertexTangents[ 3 ];
  12826. tangentArray[ offset_tangent ] = t1.x;
  12827. tangentArray[ offset_tangent + 1 ] = t1.y;
  12828. tangentArray[ offset_tangent + 2 ] = t1.z;
  12829. tangentArray[ offset_tangent + 3 ] = t1.w;
  12830. tangentArray[ offset_tangent + 4 ] = t2.x;
  12831. tangentArray[ offset_tangent + 5 ] = t2.y;
  12832. tangentArray[ offset_tangent + 6 ] = t2.z;
  12833. tangentArray[ offset_tangent + 7 ] = t2.w;
  12834. tangentArray[ offset_tangent + 8 ] = t3.x;
  12835. tangentArray[ offset_tangent + 9 ] = t3.y;
  12836. tangentArray[ offset_tangent + 10 ] = t3.z;
  12837. tangentArray[ offset_tangent + 11 ] = t3.w;
  12838. tangentArray[ offset_tangent + 12 ] = t4.x;
  12839. tangentArray[ offset_tangent + 13 ] = t4.y;
  12840. tangentArray[ offset_tangent + 14 ] = t4.z;
  12841. tangentArray[ offset_tangent + 15 ] = t4.w;
  12842. offset_tangent += 16;
  12843. }
  12844. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12845. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  12846. }
  12847. if ( dirtyNormals && normalType ) {
  12848. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12849. face = obj_faces[ chunk_faces3[ f ] ];
  12850. vertexNormals = face.vertexNormals;
  12851. faceNormal = face.normal;
  12852. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  12853. for ( i = 0; i < 3; i ++ ) {
  12854. vn = vertexNormals[ i ];
  12855. normalArray[ offset_normal ] = vn.x;
  12856. normalArray[ offset_normal + 1 ] = vn.y;
  12857. normalArray[ offset_normal + 2 ] = vn.z;
  12858. offset_normal += 3;
  12859. }
  12860. } else {
  12861. for ( i = 0; i < 3; i ++ ) {
  12862. normalArray[ offset_normal ] = faceNormal.x;
  12863. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12864. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12865. offset_normal += 3;
  12866. }
  12867. }
  12868. }
  12869. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12870. face = obj_faces[ chunk_faces4[ f ] ];
  12871. vertexNormals = face.vertexNormals;
  12872. faceNormal = face.normal;
  12873. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  12874. for ( i = 0; i < 4; i ++ ) {
  12875. vn = vertexNormals[ i ];
  12876. normalArray[ offset_normal ] = vn.x;
  12877. normalArray[ offset_normal + 1 ] = vn.y;
  12878. normalArray[ offset_normal + 2 ] = vn.z;
  12879. offset_normal += 3;
  12880. }
  12881. } else {
  12882. for ( i = 0; i < 4; i ++ ) {
  12883. normalArray[ offset_normal ] = faceNormal.x;
  12884. normalArray[ offset_normal + 1 ] = faceNormal.y;
  12885. normalArray[ offset_normal + 2 ] = faceNormal.z;
  12886. offset_normal += 3;
  12887. }
  12888. }
  12889. }
  12890. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12891. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  12892. }
  12893. if ( dirtyUvs && obj_uvs && uvType ) {
  12894. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12895. fi = chunk_faces3[ f ];
  12896. uv = obj_uvs[ fi ];
  12897. if ( uv === undefined ) continue;
  12898. for ( i = 0; i < 3; i ++ ) {
  12899. uvi = uv[ i ];
  12900. uvArray[ offset_uv ] = uvi.x;
  12901. uvArray[ offset_uv + 1 ] = uvi.y;
  12902. offset_uv += 2;
  12903. }
  12904. }
  12905. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12906. fi = chunk_faces4[ f ];
  12907. uv = obj_uvs[ fi ];
  12908. if ( uv === undefined ) continue;
  12909. for ( i = 0; i < 4; i ++ ) {
  12910. uvi = uv[ i ];
  12911. uvArray[ offset_uv ] = uvi.x;
  12912. uvArray[ offset_uv + 1 ] = uvi.y;
  12913. offset_uv += 2;
  12914. }
  12915. }
  12916. if ( offset_uv > 0 ) {
  12917. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12918. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  12919. }
  12920. }
  12921. if ( dirtyUvs && obj_uvs2 && uvType ) {
  12922. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12923. fi = chunk_faces3[ f ];
  12924. uv2 = obj_uvs2[ fi ];
  12925. if ( uv2 === undefined ) continue;
  12926. for ( i = 0; i < 3; i ++ ) {
  12927. uv2i = uv2[ i ];
  12928. uv2Array[ offset_uv2 ] = uv2i.x;
  12929. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12930. offset_uv2 += 2;
  12931. }
  12932. }
  12933. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12934. fi = chunk_faces4[ f ];
  12935. uv2 = obj_uvs2[ fi ];
  12936. if ( uv2 === undefined ) continue;
  12937. for ( i = 0; i < 4; i ++ ) {
  12938. uv2i = uv2[ i ];
  12939. uv2Array[ offset_uv2 ] = uv2i.x;
  12940. uv2Array[ offset_uv2 + 1 ] = uv2i.y;
  12941. offset_uv2 += 2;
  12942. }
  12943. }
  12944. if ( offset_uv2 > 0 ) {
  12945. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12946. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  12947. }
  12948. }
  12949. if ( dirtyElements ) {
  12950. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12951. faceArray[ offset_face ] = vertexIndex;
  12952. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12953. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  12954. offset_face += 3;
  12955. lineArray[ offset_line ] = vertexIndex;
  12956. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12957. lineArray[ offset_line + 2 ] = vertexIndex;
  12958. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  12959. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12960. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12961. offset_line += 6;
  12962. vertexIndex += 3;
  12963. }
  12964. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  12965. faceArray[ offset_face ] = vertexIndex;
  12966. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  12967. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  12968. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  12969. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  12970. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  12971. offset_face += 6;
  12972. lineArray[ offset_line ] = vertexIndex;
  12973. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  12974. lineArray[ offset_line + 2 ] = vertexIndex;
  12975. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  12976. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  12977. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  12978. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  12979. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  12980. offset_line += 8;
  12981. vertexIndex += 4;
  12982. }
  12983. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12984. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  12985. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12986. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  12987. }
  12988. if ( customAttributes ) {
  12989. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  12990. customAttribute = customAttributes[ i ];
  12991. if ( ! customAttribute.__original.needsUpdate ) continue;
  12992. offset_custom = 0;
  12993. offset_customSrc = 0;
  12994. if ( customAttribute.size === 1 ) {
  12995. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  12996. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  12997. face = obj_faces[ chunk_faces3[ f ] ];
  12998. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  12999. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13000. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13001. offset_custom += 3;
  13002. }
  13003. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13004. face = obj_faces[ chunk_faces4[ f ] ];
  13005. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  13006. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  13007. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  13008. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  13009. offset_custom += 4;
  13010. }
  13011. } else if ( customAttribute.boundTo === "faces" ) {
  13012. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13013. value = customAttribute.value[ chunk_faces3[ f ] ];
  13014. customAttribute.array[ offset_custom ] = value;
  13015. customAttribute.array[ offset_custom + 1 ] = value;
  13016. customAttribute.array[ offset_custom + 2 ] = value;
  13017. offset_custom += 3;
  13018. }
  13019. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13020. value = customAttribute.value[ chunk_faces4[ f ] ];
  13021. customAttribute.array[ offset_custom ] = value;
  13022. customAttribute.array[ offset_custom + 1 ] = value;
  13023. customAttribute.array[ offset_custom + 2 ] = value;
  13024. customAttribute.array[ offset_custom + 3 ] = value;
  13025. offset_custom += 4;
  13026. }
  13027. }
  13028. } else if ( customAttribute.size === 2 ) {
  13029. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13030. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13031. face = obj_faces[ chunk_faces3[ f ] ];
  13032. v1 = customAttribute.value[ face.a ];
  13033. v2 = customAttribute.value[ face.b ];
  13034. v3 = customAttribute.value[ face.c ];
  13035. customAttribute.array[ offset_custom ] = v1.x;
  13036. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13037. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13038. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13039. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13040. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13041. offset_custom += 6;
  13042. }
  13043. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13044. face = obj_faces[ chunk_faces4[ f ] ];
  13045. v1 = customAttribute.value[ face.a ];
  13046. v2 = customAttribute.value[ face.b ];
  13047. v3 = customAttribute.value[ face.c ];
  13048. v4 = customAttribute.value[ face.d ];
  13049. customAttribute.array[ offset_custom ] = v1.x;
  13050. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13051. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13052. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13053. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13054. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13055. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13056. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13057. offset_custom += 8;
  13058. }
  13059. } else if ( customAttribute.boundTo === "faces" ) {
  13060. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13061. value = customAttribute.value[ chunk_faces3[ f ] ];
  13062. v1 = value;
  13063. v2 = value;
  13064. v3 = value;
  13065. customAttribute.array[ offset_custom ] = v1.x;
  13066. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13067. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13068. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13069. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13070. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13071. offset_custom += 6;
  13072. }
  13073. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13074. value = customAttribute.value[ chunk_faces4[ f ] ];
  13075. v1 = value;
  13076. v2 = value;
  13077. v3 = value;
  13078. v4 = value;
  13079. customAttribute.array[ offset_custom ] = v1.x;
  13080. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13081. customAttribute.array[ offset_custom + 2 ] = v2.x;
  13082. customAttribute.array[ offset_custom + 3 ] = v2.y;
  13083. customAttribute.array[ offset_custom + 4 ] = v3.x;
  13084. customAttribute.array[ offset_custom + 5 ] = v3.y;
  13085. customAttribute.array[ offset_custom + 6 ] = v4.x;
  13086. customAttribute.array[ offset_custom + 7 ] = v4.y;
  13087. offset_custom += 8;
  13088. }
  13089. }
  13090. } else if ( customAttribute.size === 3 ) {
  13091. var pp;
  13092. if ( customAttribute.type === "c" ) {
  13093. pp = [ "r", "g", "b" ];
  13094. } else {
  13095. pp = [ "x", "y", "z" ];
  13096. }
  13097. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13098. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13099. face = obj_faces[ chunk_faces3[ f ] ];
  13100. v1 = customAttribute.value[ face.a ];
  13101. v2 = customAttribute.value[ face.b ];
  13102. v3 = customAttribute.value[ face.c ];
  13103. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13104. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13105. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13106. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13107. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13108. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13109. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13110. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13111. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13112. offset_custom += 9;
  13113. }
  13114. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13115. face = obj_faces[ chunk_faces4[ f ] ];
  13116. v1 = customAttribute.value[ face.a ];
  13117. v2 = customAttribute.value[ face.b ];
  13118. v3 = customAttribute.value[ face.c ];
  13119. v4 = customAttribute.value[ face.d ];
  13120. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13121. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13122. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13123. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13124. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13125. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13126. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13127. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13128. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13129. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13130. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13131. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13132. offset_custom += 12;
  13133. }
  13134. } else if ( customAttribute.boundTo === "faces" ) {
  13135. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13136. value = customAttribute.value[ chunk_faces3[ f ] ];
  13137. v1 = value;
  13138. v2 = value;
  13139. v3 = value;
  13140. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13141. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13142. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13143. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13144. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13145. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13146. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13147. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13148. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13149. offset_custom += 9;
  13150. }
  13151. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13152. value = customAttribute.value[ chunk_faces4[ f ] ];
  13153. v1 = value;
  13154. v2 = value;
  13155. v3 = value;
  13156. v4 = value;
  13157. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13158. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13159. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13160. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13161. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13162. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13163. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13164. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13165. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13166. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13167. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13168. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13169. offset_custom += 12;
  13170. }
  13171. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13172. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13173. value = customAttribute.value[ chunk_faces3[ f ] ];
  13174. v1 = value[ 0 ];
  13175. v2 = value[ 1 ];
  13176. v3 = value[ 2 ];
  13177. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13178. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13179. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13180. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13181. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13182. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13183. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13184. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13185. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13186. offset_custom += 9;
  13187. }
  13188. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13189. value = customAttribute.value[ chunk_faces4[ f ] ];
  13190. v1 = value[ 0 ];
  13191. v2 = value[ 1 ];
  13192. v3 = value[ 2 ];
  13193. v4 = value[ 3 ];
  13194. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  13195. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  13196. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  13197. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  13198. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  13199. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  13200. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  13201. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  13202. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  13203. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  13204. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  13205. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  13206. offset_custom += 12;
  13207. }
  13208. }
  13209. } else if ( customAttribute.size === 4 ) {
  13210. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  13211. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13212. face = obj_faces[ chunk_faces3[ f ] ];
  13213. v1 = customAttribute.value[ face.a ];
  13214. v2 = customAttribute.value[ face.b ];
  13215. v3 = customAttribute.value[ face.c ];
  13216. customAttribute.array[ offset_custom ] = v1.x;
  13217. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13218. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13219. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13220. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13221. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13222. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13223. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13224. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13225. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13226. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13227. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13228. offset_custom += 12;
  13229. }
  13230. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13231. face = obj_faces[ chunk_faces4[ f ] ];
  13232. v1 = customAttribute.value[ face.a ];
  13233. v2 = customAttribute.value[ face.b ];
  13234. v3 = customAttribute.value[ face.c ];
  13235. v4 = customAttribute.value[ face.d ];
  13236. customAttribute.array[ offset_custom ] = v1.x;
  13237. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13238. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13239. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13240. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13241. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13242. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13243. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13244. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13245. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13246. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13247. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13248. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13249. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13250. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13251. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13252. offset_custom += 16;
  13253. }
  13254. } else if ( customAttribute.boundTo === "faces" ) {
  13255. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13256. value = customAttribute.value[ chunk_faces3[ f ] ];
  13257. v1 = value;
  13258. v2 = value;
  13259. v3 = value;
  13260. customAttribute.array[ offset_custom ] = v1.x;
  13261. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13262. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13263. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13264. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13265. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13266. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13267. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13268. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13269. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13270. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13271. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13272. offset_custom += 12;
  13273. }
  13274. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13275. value = customAttribute.value[ chunk_faces4[ f ] ];
  13276. v1 = value;
  13277. v2 = value;
  13278. v3 = value;
  13279. v4 = value;
  13280. customAttribute.array[ offset_custom ] = v1.x;
  13281. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13282. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13283. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13284. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13285. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13286. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13287. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13288. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13289. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13290. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13291. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13292. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13293. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13294. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13295. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13296. offset_custom += 16;
  13297. }
  13298. } else if ( customAttribute.boundTo === "faceVertices" ) {
  13299. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  13300. value = customAttribute.value[ chunk_faces3[ f ] ];
  13301. v1 = value[ 0 ];
  13302. v2 = value[ 1 ];
  13303. v3 = value[ 2 ];
  13304. customAttribute.array[ offset_custom ] = v1.x;
  13305. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13306. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13307. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13308. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13309. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13310. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13311. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13312. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13313. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13314. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13315. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13316. offset_custom += 12;
  13317. }
  13318. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  13319. value = customAttribute.value[ chunk_faces4[ f ] ];
  13320. v1 = value[ 0 ];
  13321. v2 = value[ 1 ];
  13322. v3 = value[ 2 ];
  13323. v4 = value[ 3 ];
  13324. customAttribute.array[ offset_custom ] = v1.x;
  13325. customAttribute.array[ offset_custom + 1 ] = v1.y;
  13326. customAttribute.array[ offset_custom + 2 ] = v1.z;
  13327. customAttribute.array[ offset_custom + 3 ] = v1.w;
  13328. customAttribute.array[ offset_custom + 4 ] = v2.x;
  13329. customAttribute.array[ offset_custom + 5 ] = v2.y;
  13330. customAttribute.array[ offset_custom + 6 ] = v2.z;
  13331. customAttribute.array[ offset_custom + 7 ] = v2.w;
  13332. customAttribute.array[ offset_custom + 8 ] = v3.x;
  13333. customAttribute.array[ offset_custom + 9 ] = v3.y;
  13334. customAttribute.array[ offset_custom + 10 ] = v3.z;
  13335. customAttribute.array[ offset_custom + 11 ] = v3.w;
  13336. customAttribute.array[ offset_custom + 12 ] = v4.x;
  13337. customAttribute.array[ offset_custom + 13 ] = v4.y;
  13338. customAttribute.array[ offset_custom + 14 ] = v4.z;
  13339. customAttribute.array[ offset_custom + 15 ] = v4.w;
  13340. offset_custom += 16;
  13341. }
  13342. }
  13343. }
  13344. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  13345. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  13346. }
  13347. }
  13348. if ( dispose ) {
  13349. delete geometryGroup.__inittedArrays;
  13350. delete geometryGroup.__colorArray;
  13351. delete geometryGroup.__normalArray;
  13352. delete geometryGroup.__tangentArray;
  13353. delete geometryGroup.__uvArray;
  13354. delete geometryGroup.__uv2Array;
  13355. delete geometryGroup.__faceArray;
  13356. delete geometryGroup.__vertexArray;
  13357. delete geometryGroup.__lineArray;
  13358. delete geometryGroup.__skinIndexArray;
  13359. delete geometryGroup.__skinWeightArray;
  13360. }
  13361. };
  13362. function setDirectBuffers ( geometry, hint, dispose ) {
  13363. var attributes = geometry.attributes;
  13364. var attributeName, attributeItem;
  13365. for ( attributeName in attributes ) {
  13366. attributeItem = attributes[ attributeName ];
  13367. if ( attributeItem.needsUpdate ) {
  13368. if ( attributeName === 'index' ) {
  13369. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.buffer );
  13370. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, attributeItem.array, hint );
  13371. } else {
  13372. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13373. _gl.bufferData( _gl.ARRAY_BUFFER, attributeItem.array, hint );
  13374. }
  13375. attributeItem.needsUpdate = false;
  13376. }
  13377. if ( dispose && ! attributeItem.dynamic ) {
  13378. attributeItem.array = null;
  13379. }
  13380. }
  13381. };
  13382. // Buffer rendering
  13383. this.renderBufferImmediate = function ( object, program, material ) {
  13384. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  13385. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  13386. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  13387. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  13388. if ( object.hasPositions ) {
  13389. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  13390. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  13391. _gl.enableVertexAttribArray( program.attributes.position );
  13392. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13393. }
  13394. if ( object.hasNormals ) {
  13395. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  13396. if ( material.shading === THREE.FlatShading ) {
  13397. var nx, ny, nz,
  13398. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  13399. normalArray,
  13400. i, il = object.count * 3;
  13401. for( i = 0; i < il; i += 9 ) {
  13402. normalArray = object.normalArray;
  13403. nax = normalArray[ i ];
  13404. nay = normalArray[ i + 1 ];
  13405. naz = normalArray[ i + 2 ];
  13406. nbx = normalArray[ i + 3 ];
  13407. nby = normalArray[ i + 4 ];
  13408. nbz = normalArray[ i + 5 ];
  13409. ncx = normalArray[ i + 6 ];
  13410. ncy = normalArray[ i + 7 ];
  13411. ncz = normalArray[ i + 8 ];
  13412. nx = ( nax + nbx + ncx ) / 3;
  13413. ny = ( nay + nby + ncy ) / 3;
  13414. nz = ( naz + nbz + ncz ) / 3;
  13415. normalArray[ i ] = nx;
  13416. normalArray[ i + 1 ] = ny;
  13417. normalArray[ i + 2 ] = nz;
  13418. normalArray[ i + 3 ] = nx;
  13419. normalArray[ i + 4 ] = ny;
  13420. normalArray[ i + 5 ] = nz;
  13421. normalArray[ i + 6 ] = nx;
  13422. normalArray[ i + 7 ] = ny;
  13423. normalArray[ i + 8 ] = nz;
  13424. }
  13425. }
  13426. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  13427. _gl.enableVertexAttribArray( program.attributes.normal );
  13428. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13429. }
  13430. if ( object.hasUvs && material.map ) {
  13431. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  13432. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  13433. _gl.enableVertexAttribArray( program.attributes.uv );
  13434. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13435. }
  13436. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  13437. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  13438. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  13439. _gl.enableVertexAttribArray( program.attributes.color );
  13440. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13441. }
  13442. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  13443. object.count = 0;
  13444. };
  13445. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  13446. if ( material.visible === false ) return;
  13447. var linewidth, a, attribute;
  13448. var attributeItem, attributeName, attributePointer, attributeSize;
  13449. var program = setProgram( camera, lights, fog, material, object );
  13450. var programAttributes = program.attributes;
  13451. var geometryAttributes = geometry.attributes;
  13452. var updateBuffers = false,
  13453. wireframeBit = material.wireframe ? 1 : 0,
  13454. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13455. if ( geometryHash !== _currentGeometryGroupHash ) {
  13456. _currentGeometryGroupHash = geometryHash;
  13457. updateBuffers = true;
  13458. }
  13459. if ( updateBuffers ) {
  13460. disableAttributes();
  13461. }
  13462. // render mesh
  13463. if ( object instanceof THREE.Mesh ) {
  13464. var index = geometryAttributes[ "index" ];
  13465. // indexed triangles
  13466. if ( index ) {
  13467. var offsets = geometry.offsets;
  13468. // if there is more than 1 chunk
  13469. // must set attribute pointers to use new offsets for each chunk
  13470. // even if geometry and materials didn't change
  13471. if ( offsets.length > 1 ) updateBuffers = true;
  13472. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  13473. var startIndex = offsets[ i ].index;
  13474. if ( updateBuffers ) {
  13475. for ( attributeName in geometryAttributes ) {
  13476. if ( attributeName === 'index' ) continue;
  13477. attributePointer = programAttributes[ attributeName ];
  13478. attributeItem = geometryAttributes[ attributeName ];
  13479. attributeSize = attributeItem.itemSize;
  13480. if ( attributePointer >= 0 ) {
  13481. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13482. enableAttribute( attributePointer );
  13483. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, startIndex * attributeSize * 4 ); // 4 bytes per Float32
  13484. }
  13485. }
  13486. // indices
  13487. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  13488. }
  13489. // render indexed triangles
  13490. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  13491. _this.info.render.calls ++;
  13492. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  13493. _this.info.render.faces += offsets[ i ].count / 3;
  13494. }
  13495. // non-indexed triangles
  13496. } else {
  13497. if ( updateBuffers ) {
  13498. for ( attributeName in geometryAttributes ) {
  13499. if ( attributeName === 'index') continue;
  13500. attributePointer = programAttributes[ attributeName ];
  13501. attributeItem = geometryAttributes[ attributeName ];
  13502. attributeSize = attributeItem.itemSize;
  13503. if ( attributePointer >= 0 ) {
  13504. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13505. enableAttribute( attributePointer );
  13506. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13507. }
  13508. }
  13509. }
  13510. var position = geometry.attributes[ "position" ];
  13511. // render non-indexed triangles
  13512. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  13513. _this.info.render.calls ++;
  13514. _this.info.render.vertices += position.numItems / 3;
  13515. _this.info.render.faces += position.numItems / 3 / 3;
  13516. }
  13517. // render particles
  13518. } else if ( object instanceof THREE.ParticleSystem ) {
  13519. if ( updateBuffers ) {
  13520. for ( attributeName in geometryAttributes ) {
  13521. attributePointer = programAttributes[ attributeName ];
  13522. attributeItem = geometryAttributes[ attributeName ];
  13523. attributeSize = attributeItem.itemSize;
  13524. if ( attributePointer >= 0 ) {
  13525. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13526. enableAttribute( attributePointer );
  13527. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13528. }
  13529. }
  13530. var position = geometryAttributes[ "position" ];
  13531. // render particles
  13532. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  13533. _this.info.render.calls ++;
  13534. _this.info.render.points += position.numItems / 3;
  13535. }
  13536. } else if ( object instanceof THREE.Line ) {
  13537. if ( updateBuffers ) {
  13538. for ( attributeName in geometryAttributes ) {
  13539. attributePointer = programAttributes[ attributeName ];
  13540. attributeItem = geometryAttributes[ attributeName ];
  13541. attributeSize = attributeItem.itemSize;
  13542. if ( attributePointer >= 0 ) {
  13543. _gl.bindBuffer( _gl.ARRAY_BUFFER, attributeItem.buffer );
  13544. enableAttribute( attributePointer );
  13545. _gl.vertexAttribPointer( attributePointer, attributeSize, _gl.FLOAT, false, 0, 0 );
  13546. }
  13547. }
  13548. // render lines
  13549. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13550. setLineWidth( material.linewidth );
  13551. var position = geometryAttributes[ "position" ];
  13552. _gl.drawArrays( primitives, 0, position.numItems / 3 );
  13553. _this.info.render.calls ++;
  13554. _this.info.render.points += position.numItems;
  13555. }
  13556. }
  13557. };
  13558. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  13559. if ( material.visible === false ) return;
  13560. var linewidth, a, attribute, i, il;
  13561. var program = setProgram( camera, lights, fog, material, object );
  13562. var attributes = program.attributes;
  13563. var updateBuffers = false,
  13564. wireframeBit = material.wireframe ? 1 : 0,
  13565. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  13566. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  13567. _currentGeometryGroupHash = geometryGroupHash;
  13568. updateBuffers = true;
  13569. }
  13570. if ( updateBuffers ) {
  13571. disableAttributes();
  13572. }
  13573. // vertices
  13574. if ( !material.morphTargets && attributes.position >= 0 ) {
  13575. if ( updateBuffers ) {
  13576. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13577. enableAttribute( attributes.position );
  13578. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13579. }
  13580. } else {
  13581. if ( object.morphTargetBase ) {
  13582. setupMorphTargets( material, geometryGroup, object );
  13583. }
  13584. }
  13585. if ( updateBuffers ) {
  13586. // custom attributes
  13587. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  13588. if ( geometryGroup.__webglCustomAttributesList ) {
  13589. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  13590. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  13591. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  13592. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  13593. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  13594. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  13595. }
  13596. }
  13597. }
  13598. // colors
  13599. if ( attributes.color >= 0 ) {
  13600. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  13601. enableAttribute( attributes.color );
  13602. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  13603. }
  13604. // normals
  13605. if ( attributes.normal >= 0 ) {
  13606. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  13607. enableAttribute( attributes.normal );
  13608. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  13609. }
  13610. // tangents
  13611. if ( attributes.tangent >= 0 ) {
  13612. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  13613. enableAttribute( attributes.tangent );
  13614. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  13615. }
  13616. // uvs
  13617. if ( attributes.uv >= 0 ) {
  13618. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  13619. enableAttribute( attributes.uv );
  13620. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  13621. }
  13622. if ( attributes.uv2 >= 0 ) {
  13623. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  13624. enableAttribute( attributes.uv2 );
  13625. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  13626. }
  13627. if ( material.skinning &&
  13628. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  13629. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  13630. enableAttribute( attributes.skinIndex );
  13631. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  13632. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  13633. enableAttribute( attributes.skinWeight );
  13634. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  13635. }
  13636. // line distances
  13637. if ( attributes.lineDistance >= 0 ) {
  13638. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  13639. enableAttribute( attributes.lineDistance );
  13640. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  13641. }
  13642. }
  13643. // render mesh
  13644. if ( object instanceof THREE.Mesh ) {
  13645. // wireframe
  13646. if ( material.wireframe ) {
  13647. setLineWidth( material.wireframeLinewidth );
  13648. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  13649. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  13650. // triangles
  13651. } else {
  13652. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  13653. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  13654. }
  13655. _this.info.render.calls ++;
  13656. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  13657. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  13658. // render lines
  13659. } else if ( object instanceof THREE.Line ) {
  13660. var primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  13661. setLineWidth( material.linewidth );
  13662. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  13663. _this.info.render.calls ++;
  13664. // render particles
  13665. } else if ( object instanceof THREE.ParticleSystem ) {
  13666. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  13667. _this.info.render.calls ++;
  13668. _this.info.render.points += geometryGroup.__webglParticleCount;
  13669. // render ribbon
  13670. } else if ( object instanceof THREE.Ribbon ) {
  13671. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  13672. _this.info.render.calls ++;
  13673. }
  13674. };
  13675. function enableAttribute( attribute ) {
  13676. if ( ! _enabledAttributes[ attribute ] ) {
  13677. _gl.enableVertexAttribArray( attribute );
  13678. _enabledAttributes[ attribute ] = true;
  13679. }
  13680. };
  13681. function disableAttributes() {
  13682. for ( var attribute in _enabledAttributes ) {
  13683. if ( _enabledAttributes[ attribute ] ) {
  13684. _gl.disableVertexAttribArray( attribute );
  13685. _enabledAttributes[ attribute ] = false;
  13686. }
  13687. }
  13688. };
  13689. function setupMorphTargets ( material, geometryGroup, object ) {
  13690. // set base
  13691. var attributes = material.program.attributes;
  13692. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  13693. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  13694. enableAttribute( attributes.position );
  13695. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13696. } else if ( attributes.position >= 0 ) {
  13697. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  13698. enableAttribute( attributes.position );
  13699. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  13700. }
  13701. if ( object.morphTargetForcedOrder.length ) {
  13702. // set forced order
  13703. var m = 0;
  13704. var order = object.morphTargetForcedOrder;
  13705. var influences = object.morphTargetInfluences;
  13706. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  13707. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13708. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  13709. enableAttribute( attributes[ "morphTarget" + m ] );
  13710. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13711. }
  13712. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13713. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  13714. enableAttribute( attributes[ "morphNormal" + m ] );
  13715. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13716. }
  13717. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  13718. m ++;
  13719. }
  13720. } else {
  13721. // find the most influencing
  13722. var influence, activeInfluenceIndices = [];
  13723. var influences = object.morphTargetInfluences;
  13724. var i, il = influences.length;
  13725. for ( i = 0; i < il; i ++ ) {
  13726. influence = influences[ i ];
  13727. if ( influence > 0 ) {
  13728. activeInfluenceIndices.push( [ influence, i ] );
  13729. }
  13730. }
  13731. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  13732. activeInfluenceIndices.sort( numericalSort );
  13733. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  13734. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  13735. activeInfluenceIndices.sort( numericalSort );
  13736. } else if ( activeInfluenceIndices.length === 0 ) {
  13737. activeInfluenceIndices.push( [ 0, 0 ] );
  13738. };
  13739. var influenceIndex, m = 0;
  13740. while ( m < material.numSupportedMorphTargets ) {
  13741. if ( activeInfluenceIndices[ m ] ) {
  13742. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  13743. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  13744. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  13745. enableAttribute( attributes[ "morphTarget" + m ] );
  13746. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13747. }
  13748. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  13749. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  13750. enableAttribute( attributes[ "morphNormal" + m ] );
  13751. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13752. }
  13753. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  13754. } else {
  13755. /*
  13756. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13757. if ( material.morphNormals ) {
  13758. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  13759. }
  13760. */
  13761. object.__webglMorphTargetInfluences[ m ] = 0;
  13762. }
  13763. m ++;
  13764. }
  13765. }
  13766. // load updated influences uniform
  13767. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  13768. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  13769. }
  13770. };
  13771. // Sorting
  13772. function painterSortStable ( a, b ) {
  13773. if ( a.z !== b.z ) {
  13774. return b.z - a.z;
  13775. } else {
  13776. return a.id - b.id;
  13777. }
  13778. };
  13779. function numericalSort ( a, b ) {
  13780. return b[ 0 ] - a[ 0 ];
  13781. };
  13782. // Rendering
  13783. this.render = function ( scene, camera, renderTarget, forceClear ) {
  13784. if ( camera instanceof THREE.Camera === false ) {
  13785. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  13786. return;
  13787. }
  13788. var i, il,
  13789. webglObject, object,
  13790. renderList,
  13791. lights = scene.__lights,
  13792. fog = scene.fog;
  13793. // reset caching for this frame
  13794. _currentMaterialId = -1;
  13795. _lightsNeedUpdate = true;
  13796. // update scene graph
  13797. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  13798. // update camera matrices and frustum
  13799. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  13800. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  13801. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  13802. _frustum.setFromMatrix( _projScreenMatrix );
  13803. // update WebGL objects
  13804. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  13805. // custom render plugins (pre pass)
  13806. renderPlugins( this.renderPluginsPre, scene, camera );
  13807. //
  13808. _this.info.render.calls = 0;
  13809. _this.info.render.vertices = 0;
  13810. _this.info.render.faces = 0;
  13811. _this.info.render.points = 0;
  13812. this.setRenderTarget( renderTarget );
  13813. if ( this.autoClear || forceClear ) {
  13814. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  13815. }
  13816. // set matrices for regular objects (frustum culled)
  13817. renderList = scene.__webglObjects;
  13818. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13819. webglObject = renderList[ i ];
  13820. object = webglObject.object;
  13821. webglObject.id = i;
  13822. webglObject.render = false;
  13823. if ( object.visible ) {
  13824. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  13825. setupMatrices( object, camera );
  13826. unrollBufferMaterial( webglObject );
  13827. webglObject.render = true;
  13828. if ( this.sortObjects === true ) {
  13829. if ( object.renderDepth !== null ) {
  13830. webglObject.z = object.renderDepth;
  13831. } else {
  13832. _vector3.getPositionFromMatrix( object.matrixWorld );
  13833. _vector3.applyProjection( _projScreenMatrix );
  13834. webglObject.z = _vector3.z;
  13835. }
  13836. }
  13837. }
  13838. }
  13839. }
  13840. if ( this.sortObjects ) {
  13841. renderList.sort( painterSortStable );
  13842. }
  13843. // set matrices for immediate objects
  13844. renderList = scene.__webglObjectsImmediate;
  13845. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  13846. webglObject = renderList[ i ];
  13847. object = webglObject.object;
  13848. if ( object.visible ) {
  13849. setupMatrices( object, camera );
  13850. unrollImmediateBufferMaterial( webglObject );
  13851. }
  13852. }
  13853. if ( scene.overrideMaterial ) {
  13854. var material = scene.overrideMaterial;
  13855. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13856. this.setDepthTest( material.depthTest );
  13857. this.setDepthWrite( material.depthWrite );
  13858. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13859. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  13860. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  13861. } else {
  13862. var material = null;
  13863. // opaque pass (front-to-back order)
  13864. this.setBlending( THREE.NoBlending );
  13865. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  13866. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  13867. // transparent pass (back-to-front order)
  13868. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  13869. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  13870. }
  13871. // custom render plugins (post pass)
  13872. renderPlugins( this.renderPluginsPost, scene, camera );
  13873. // Generate mipmap if we're using any kind of mipmap filtering
  13874. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  13875. updateRenderTargetMipmap( renderTarget );
  13876. }
  13877. // Ensure depth buffer writing is enabled so it can be cleared on next render
  13878. this.setDepthTest( true );
  13879. this.setDepthWrite( true );
  13880. // _gl.finish();
  13881. };
  13882. function renderPlugins( plugins, scene, camera ) {
  13883. if ( ! plugins.length ) return;
  13884. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  13885. // reset state for plugin (to start from clean slate)
  13886. _currentProgram = null;
  13887. _currentCamera = null;
  13888. _oldBlending = -1;
  13889. _oldDepthTest = -1;
  13890. _oldDepthWrite = -1;
  13891. _oldDoubleSided = -1;
  13892. _oldFlipSided = -1;
  13893. _currentGeometryGroupHash = -1;
  13894. _currentMaterialId = -1;
  13895. _lightsNeedUpdate = true;
  13896. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  13897. // reset state after plugin (anything could have changed)
  13898. _currentProgram = null;
  13899. _currentCamera = null;
  13900. _oldBlending = -1;
  13901. _oldDepthTest = -1;
  13902. _oldDepthWrite = -1;
  13903. _oldDoubleSided = -1;
  13904. _oldFlipSided = -1;
  13905. _currentGeometryGroupHash = -1;
  13906. _currentMaterialId = -1;
  13907. _lightsNeedUpdate = true;
  13908. }
  13909. };
  13910. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13911. var webglObject, object, buffer, material, start, end, delta;
  13912. if ( reverse ) {
  13913. start = renderList.length - 1;
  13914. end = -1;
  13915. delta = -1;
  13916. } else {
  13917. start = 0;
  13918. end = renderList.length;
  13919. delta = 1;
  13920. }
  13921. for ( var i = start; i !== end; i += delta ) {
  13922. webglObject = renderList[ i ];
  13923. if ( webglObject.render ) {
  13924. object = webglObject.object;
  13925. buffer = webglObject.buffer;
  13926. if ( overrideMaterial ) {
  13927. material = overrideMaterial;
  13928. } else {
  13929. material = webglObject[ materialType ];
  13930. if ( ! material ) continue;
  13931. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13932. _this.setDepthTest( material.depthTest );
  13933. _this.setDepthWrite( material.depthWrite );
  13934. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13935. }
  13936. _this.setMaterialFaces( material );
  13937. if ( buffer instanceof THREE.BufferGeometry ) {
  13938. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  13939. } else {
  13940. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  13941. }
  13942. }
  13943. }
  13944. };
  13945. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  13946. var webglObject, object, material, program;
  13947. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  13948. webglObject = renderList[ i ];
  13949. object = webglObject.object;
  13950. if ( object.visible ) {
  13951. if ( overrideMaterial ) {
  13952. material = overrideMaterial;
  13953. } else {
  13954. material = webglObject[ materialType ];
  13955. if ( ! material ) continue;
  13956. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  13957. _this.setDepthTest( material.depthTest );
  13958. _this.setDepthWrite( material.depthWrite );
  13959. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  13960. }
  13961. _this.renderImmediateObject( camera, lights, fog, material, object );
  13962. }
  13963. }
  13964. };
  13965. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  13966. var program = setProgram( camera, lights, fog, material, object );
  13967. _currentGeometryGroupHash = -1;
  13968. _this.setMaterialFaces( material );
  13969. if ( object.immediateRenderCallback ) {
  13970. object.immediateRenderCallback( program, _gl, _frustum );
  13971. } else {
  13972. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  13973. }
  13974. };
  13975. function unrollImmediateBufferMaterial ( globject ) {
  13976. var object = globject.object,
  13977. material = object.material;
  13978. if ( material.transparent ) {
  13979. globject.transparent = material;
  13980. globject.opaque = null;
  13981. } else {
  13982. globject.opaque = material;
  13983. globject.transparent = null;
  13984. }
  13985. };
  13986. function unrollBufferMaterial ( globject ) {
  13987. var object = globject.object,
  13988. buffer = globject.buffer,
  13989. material, materialIndex, meshMaterial;
  13990. meshMaterial = object.material;
  13991. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  13992. materialIndex = buffer.materialIndex;
  13993. material = meshMaterial.materials[ materialIndex ];
  13994. if ( material.transparent ) {
  13995. globject.transparent = material;
  13996. globject.opaque = null;
  13997. } else {
  13998. globject.opaque = material;
  13999. globject.transparent = null;
  14000. }
  14001. } else {
  14002. material = meshMaterial;
  14003. if ( material ) {
  14004. if ( material.transparent ) {
  14005. globject.transparent = material;
  14006. globject.opaque = null;
  14007. } else {
  14008. globject.opaque = material;
  14009. globject.transparent = null;
  14010. }
  14011. }
  14012. }
  14013. };
  14014. // Geometry splitting
  14015. function sortFacesByMaterial ( geometry, material ) {
  14016. var f, fl, face, materialIndex, vertices,
  14017. groupHash, hash_map = {};
  14018. var numMorphTargets = geometry.morphTargets.length;
  14019. var numMorphNormals = geometry.morphNormals.length;
  14020. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  14021. geometry.geometryGroups = {};
  14022. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  14023. face = geometry.faces[ f ];
  14024. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  14025. if ( hash_map[ materialIndex ] === undefined ) {
  14026. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  14027. }
  14028. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14029. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14030. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14031. }
  14032. vertices = face instanceof THREE.Face3 ? 3 : 4;
  14033. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  14034. hash_map[ materialIndex ].counter += 1;
  14035. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  14036. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  14037. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  14038. }
  14039. }
  14040. if ( face instanceof THREE.Face3 ) {
  14041. geometry.geometryGroups[ groupHash ].faces3.push( f );
  14042. } else {
  14043. geometry.geometryGroups[ groupHash ].faces4.push( f );
  14044. }
  14045. geometry.geometryGroups[ groupHash ].vertices += vertices;
  14046. }
  14047. geometry.geometryGroupsList = [];
  14048. for ( var g in geometry.geometryGroups ) {
  14049. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  14050. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  14051. }
  14052. };
  14053. // Objects refresh
  14054. this.initWebGLObjects = function ( scene ) {
  14055. if ( !scene.__webglObjects ) {
  14056. scene.__webglObjects = [];
  14057. scene.__webglObjectsImmediate = [];
  14058. scene.__webglSprites = [];
  14059. scene.__webglFlares = [];
  14060. }
  14061. while ( scene.__objectsAdded.length ) {
  14062. addObject( scene.__objectsAdded[ 0 ], scene );
  14063. scene.__objectsAdded.splice( 0, 1 );
  14064. }
  14065. while ( scene.__objectsRemoved.length ) {
  14066. removeObject( scene.__objectsRemoved[ 0 ], scene );
  14067. scene.__objectsRemoved.splice( 0, 1 );
  14068. }
  14069. // update must be called after objects adding / removal
  14070. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  14071. var object = scene.__webglObjects[ o ].object;
  14072. // TODO: Remove this hack (WebGLRenderer refactoring)
  14073. if ( object.__webglInit === undefined ) {
  14074. if ( object.__webglActive !== undefined ) {
  14075. removeObject( object, scene );
  14076. }
  14077. addObject( object, scene );
  14078. }
  14079. updateObject( object );
  14080. }
  14081. };
  14082. // Objects adding
  14083. function addObject( object, scene ) {
  14084. var g, geometry, material, geometryGroup;
  14085. if ( object.__webglInit === undefined ) {
  14086. object.__webglInit = true;
  14087. object._modelViewMatrix = new THREE.Matrix4();
  14088. object._normalMatrix = new THREE.Matrix3();
  14089. if ( object.geometry !== undefined && object.geometry.__webglInit === undefined ) {
  14090. object.geometry.__webglInit = true;
  14091. object.geometry.addEventListener( 'dispose', onGeometryDispose );
  14092. }
  14093. geometry = object.geometry;
  14094. if ( geometry === undefined ) {
  14095. // fail silently for now
  14096. } else if ( geometry instanceof THREE.BufferGeometry ) {
  14097. initDirectBuffers( geometry );
  14098. } else if ( object instanceof THREE.Mesh ) {
  14099. material = object.material;
  14100. if ( geometry.geometryGroups === undefined ) {
  14101. sortFacesByMaterial( geometry, material );
  14102. }
  14103. // create separate VBOs per geometry chunk
  14104. for ( g in geometry.geometryGroups ) {
  14105. geometryGroup = geometry.geometryGroups[ g ];
  14106. // initialise VBO on the first access
  14107. if ( ! geometryGroup.__webglVertexBuffer ) {
  14108. createMeshBuffers( geometryGroup );
  14109. initMeshBuffers( geometryGroup, object );
  14110. geometry.verticesNeedUpdate = true;
  14111. geometry.morphTargetsNeedUpdate = true;
  14112. geometry.elementsNeedUpdate = true;
  14113. geometry.uvsNeedUpdate = true;
  14114. geometry.normalsNeedUpdate = true;
  14115. geometry.tangentsNeedUpdate = true;
  14116. geometry.colorsNeedUpdate = true;
  14117. }
  14118. }
  14119. } else if ( object instanceof THREE.Ribbon ) {
  14120. if ( ! geometry.__webglVertexBuffer ) {
  14121. createRibbonBuffers( geometry );
  14122. initRibbonBuffers( geometry, object );
  14123. geometry.verticesNeedUpdate = true;
  14124. geometry.colorsNeedUpdate = true;
  14125. geometry.normalsNeedUpdate = true;
  14126. }
  14127. } else if ( object instanceof THREE.Line ) {
  14128. if ( ! geometry.__webglVertexBuffer ) {
  14129. createLineBuffers( geometry );
  14130. initLineBuffers( geometry, object );
  14131. geometry.verticesNeedUpdate = true;
  14132. geometry.colorsNeedUpdate = true;
  14133. geometry.lineDistancesNeedUpdate = true;
  14134. }
  14135. } else if ( object instanceof THREE.ParticleSystem ) {
  14136. if ( ! geometry.__webglVertexBuffer ) {
  14137. createParticleBuffers( geometry );
  14138. initParticleBuffers( geometry, object );
  14139. geometry.verticesNeedUpdate = true;
  14140. geometry.colorsNeedUpdate = true;
  14141. }
  14142. }
  14143. }
  14144. if ( object.__webglActive === undefined ) {
  14145. if ( object instanceof THREE.Mesh ) {
  14146. geometry = object.geometry;
  14147. if ( geometry instanceof THREE.BufferGeometry ) {
  14148. addBuffer( scene.__webglObjects, geometry, object );
  14149. } else if ( geometry instanceof THREE.Geometry ) {
  14150. for ( g in geometry.geometryGroups ) {
  14151. geometryGroup = geometry.geometryGroups[ g ];
  14152. addBuffer( scene.__webglObjects, geometryGroup, object );
  14153. }
  14154. }
  14155. } else if ( object instanceof THREE.Ribbon ||
  14156. object instanceof THREE.Line ||
  14157. object instanceof THREE.ParticleSystem ) {
  14158. geometry = object.geometry;
  14159. addBuffer( scene.__webglObjects, geometry, object );
  14160. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14161. addBufferImmediate( scene.__webglObjectsImmediate, object );
  14162. } else if ( object instanceof THREE.Sprite ) {
  14163. scene.__webglSprites.push( object );
  14164. } else if ( object instanceof THREE.LensFlare ) {
  14165. scene.__webglFlares.push( object );
  14166. }
  14167. object.__webglActive = true;
  14168. }
  14169. };
  14170. function addBuffer( objlist, buffer, object ) {
  14171. objlist.push(
  14172. {
  14173. id: null,
  14174. buffer: buffer,
  14175. object: object,
  14176. opaque: null,
  14177. transparent: null,
  14178. z: 0
  14179. }
  14180. );
  14181. };
  14182. function addBufferImmediate( objlist, object ) {
  14183. objlist.push(
  14184. {
  14185. id: null,
  14186. object: object,
  14187. opaque: null,
  14188. transparent: null,
  14189. z: 0
  14190. }
  14191. );
  14192. };
  14193. // Objects updates
  14194. function updateObject( object ) {
  14195. var geometry = object.geometry,
  14196. geometryGroup, customAttributesDirty, material;
  14197. if ( geometry instanceof THREE.BufferGeometry ) {
  14198. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  14199. } else if ( object instanceof THREE.Mesh ) {
  14200. // check all geometry groups
  14201. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  14202. geometryGroup = geometry.geometryGroupsList[ i ];
  14203. material = getBufferMaterial( object, geometryGroup );
  14204. if ( geometry.buffersNeedUpdate ) {
  14205. initMeshBuffers( geometryGroup, object );
  14206. }
  14207. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14208. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  14209. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  14210. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  14211. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  14212. }
  14213. }
  14214. geometry.verticesNeedUpdate = false;
  14215. geometry.morphTargetsNeedUpdate = false;
  14216. geometry.elementsNeedUpdate = false;
  14217. geometry.uvsNeedUpdate = false;
  14218. geometry.normalsNeedUpdate = false;
  14219. geometry.colorsNeedUpdate = false;
  14220. geometry.tangentsNeedUpdate = false;
  14221. geometry.buffersNeedUpdate = false;
  14222. material.attributes && clearCustomAttributes( material );
  14223. } else if ( object instanceof THREE.Ribbon ) {
  14224. material = getBufferMaterial( object, geometry );
  14225. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14226. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  14227. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  14228. }
  14229. geometry.verticesNeedUpdate = false;
  14230. geometry.colorsNeedUpdate = false;
  14231. geometry.normalsNeedUpdate = false;
  14232. material.attributes && clearCustomAttributes( material );
  14233. } else if ( object instanceof THREE.Line ) {
  14234. material = getBufferMaterial( object, geometry );
  14235. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14236. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  14237. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  14238. }
  14239. geometry.verticesNeedUpdate = false;
  14240. geometry.colorsNeedUpdate = false;
  14241. geometry.lineDistancesNeedUpdate = false;
  14242. material.attributes && clearCustomAttributes( material );
  14243. } else if ( object instanceof THREE.ParticleSystem ) {
  14244. material = getBufferMaterial( object, geometry );
  14245. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  14246. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  14247. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  14248. }
  14249. geometry.verticesNeedUpdate = false;
  14250. geometry.colorsNeedUpdate = false;
  14251. material.attributes && clearCustomAttributes( material );
  14252. }
  14253. };
  14254. // Objects updates - custom attributes check
  14255. function areCustomAttributesDirty( material ) {
  14256. for ( var a in material.attributes ) {
  14257. if ( material.attributes[ a ].needsUpdate ) return true;
  14258. }
  14259. return false;
  14260. };
  14261. function clearCustomAttributes( material ) {
  14262. for ( var a in material.attributes ) {
  14263. material.attributes[ a ].needsUpdate = false;
  14264. }
  14265. };
  14266. // Objects removal
  14267. function removeObject( object, scene ) {
  14268. if ( object instanceof THREE.Mesh ||
  14269. object instanceof THREE.ParticleSystem ||
  14270. object instanceof THREE.Ribbon ||
  14271. object instanceof THREE.Line ) {
  14272. removeInstances( scene.__webglObjects, object );
  14273. } else if ( object instanceof THREE.Sprite ) {
  14274. removeInstancesDirect( scene.__webglSprites, object );
  14275. } else if ( object instanceof THREE.LensFlare ) {
  14276. removeInstancesDirect( scene.__webglFlares, object );
  14277. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  14278. removeInstances( scene.__webglObjectsImmediate, object );
  14279. }
  14280. delete object.__webglActive;
  14281. };
  14282. function removeInstances( objlist, object ) {
  14283. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14284. if ( objlist[ o ].object === object ) {
  14285. objlist.splice( o, 1 );
  14286. }
  14287. }
  14288. };
  14289. function removeInstancesDirect( objlist, object ) {
  14290. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  14291. if ( objlist[ o ] === object ) {
  14292. objlist.splice( o, 1 );
  14293. }
  14294. }
  14295. };
  14296. // Materials
  14297. this.initMaterial = function ( material, lights, fog, object ) {
  14298. material.addEventListener( 'dispose', onMaterialDispose );
  14299. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  14300. if ( material instanceof THREE.MeshDepthMaterial ) {
  14301. shaderID = 'depth';
  14302. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14303. shaderID = 'normal';
  14304. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  14305. shaderID = 'basic';
  14306. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14307. shaderID = 'lambert';
  14308. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14309. shaderID = 'phong';
  14310. } else if ( material instanceof THREE.LineBasicMaterial ) {
  14311. shaderID = 'basic';
  14312. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14313. shaderID = 'dashed';
  14314. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14315. shaderID = 'particle_basic';
  14316. }
  14317. if ( shaderID ) {
  14318. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  14319. }
  14320. // heuristics to create shader parameters according to lights in the scene
  14321. // (not to blow over maxLights budget)
  14322. maxLightCount = allocateLights( lights );
  14323. maxShadows = allocateShadows( lights );
  14324. maxBones = allocateBones( object );
  14325. parameters = {
  14326. map: !!material.map,
  14327. envMap: !!material.envMap,
  14328. lightMap: !!material.lightMap,
  14329. bumpMap: !!material.bumpMap,
  14330. normalMap: !!material.normalMap,
  14331. specularMap: !!material.specularMap,
  14332. vertexColors: material.vertexColors,
  14333. fog: fog,
  14334. useFog: material.fog,
  14335. fogExp: fog instanceof THREE.FogExp2,
  14336. sizeAttenuation: material.sizeAttenuation,
  14337. skinning: material.skinning,
  14338. maxBones: maxBones,
  14339. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  14340. boneTextureWidth: object && object.boneTextureWidth,
  14341. boneTextureHeight: object && object.boneTextureHeight,
  14342. morphTargets: material.morphTargets,
  14343. morphNormals: material.morphNormals,
  14344. maxMorphTargets: this.maxMorphTargets,
  14345. maxMorphNormals: this.maxMorphNormals,
  14346. maxDirLights: maxLightCount.directional,
  14347. maxPointLights: maxLightCount.point,
  14348. maxSpotLights: maxLightCount.spot,
  14349. maxHemiLights: maxLightCount.hemi,
  14350. maxShadows: maxShadows,
  14351. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  14352. shadowMapType: this.shadowMapType,
  14353. shadowMapDebug: this.shadowMapDebug,
  14354. shadowMapCascade: this.shadowMapCascade,
  14355. alphaTest: material.alphaTest,
  14356. metal: material.metal,
  14357. perPixel: material.perPixel,
  14358. wrapAround: material.wrapAround,
  14359. doubleSided: material.side === THREE.DoubleSide,
  14360. flipSided: material.side === THREE.BackSide
  14361. };
  14362. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  14363. var attributes = material.program.attributes;
  14364. if ( material.morphTargets ) {
  14365. material.numSupportedMorphTargets = 0;
  14366. var id, base = "morphTarget";
  14367. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  14368. id = base + i;
  14369. if ( attributes[ id ] >= 0 ) {
  14370. material.numSupportedMorphTargets ++;
  14371. }
  14372. }
  14373. }
  14374. if ( material.morphNormals ) {
  14375. material.numSupportedMorphNormals = 0;
  14376. var id, base = "morphNormal";
  14377. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  14378. id = base + i;
  14379. if ( attributes[ id ] >= 0 ) {
  14380. material.numSupportedMorphNormals ++;
  14381. }
  14382. }
  14383. }
  14384. material.uniformsList = [];
  14385. for ( u in material.uniforms ) {
  14386. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  14387. }
  14388. };
  14389. function setMaterialShaders( material, shaders ) {
  14390. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  14391. material.vertexShader = shaders.vertexShader;
  14392. material.fragmentShader = shaders.fragmentShader;
  14393. };
  14394. function setProgram( camera, lights, fog, material, object ) {
  14395. _usedTextureUnits = 0;
  14396. if ( material.needsUpdate ) {
  14397. if ( material.program ) deallocateMaterial( material );
  14398. _this.initMaterial( material, lights, fog, object );
  14399. material.needsUpdate = false;
  14400. }
  14401. if ( material.morphTargets ) {
  14402. if ( ! object.__webglMorphTargetInfluences ) {
  14403. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  14404. }
  14405. }
  14406. var refreshMaterial = false;
  14407. var program = material.program,
  14408. p_uniforms = program.uniforms,
  14409. m_uniforms = material.uniforms;
  14410. if ( program !== _currentProgram ) {
  14411. _gl.useProgram( program );
  14412. _currentProgram = program;
  14413. refreshMaterial = true;
  14414. }
  14415. if ( material.id !== _currentMaterialId ) {
  14416. _currentMaterialId = material.id;
  14417. refreshMaterial = true;
  14418. }
  14419. if ( refreshMaterial || camera !== _currentCamera ) {
  14420. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  14421. if ( camera !== _currentCamera ) _currentCamera = camera;
  14422. }
  14423. // skinning uniforms must be set even if material didn't change
  14424. // auto-setting of texture unit for bone texture must go before other textures
  14425. // not sure why, but otherwise weird things happen
  14426. if ( material.skinning ) {
  14427. if ( _supportsBoneTextures && object.useVertexTexture ) {
  14428. if ( p_uniforms.boneTexture !== null ) {
  14429. var textureUnit = getTextureUnit();
  14430. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  14431. _this.setTexture( object.boneTexture, textureUnit );
  14432. }
  14433. } else {
  14434. if ( p_uniforms.boneGlobalMatrices !== null ) {
  14435. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  14436. }
  14437. }
  14438. }
  14439. if ( refreshMaterial ) {
  14440. // refresh uniforms common to several materials
  14441. if ( fog && material.fog ) {
  14442. refreshUniformsFog( m_uniforms, fog );
  14443. }
  14444. if ( material instanceof THREE.MeshPhongMaterial ||
  14445. material instanceof THREE.MeshLambertMaterial ||
  14446. material.lights ) {
  14447. if ( _lightsNeedUpdate ) {
  14448. setupLights( program, lights );
  14449. _lightsNeedUpdate = false;
  14450. }
  14451. refreshUniformsLights( m_uniforms, _lights );
  14452. }
  14453. if ( material instanceof THREE.MeshBasicMaterial ||
  14454. material instanceof THREE.MeshLambertMaterial ||
  14455. material instanceof THREE.MeshPhongMaterial ) {
  14456. refreshUniformsCommon( m_uniforms, material );
  14457. }
  14458. // refresh single material specific uniforms
  14459. if ( material instanceof THREE.LineBasicMaterial ) {
  14460. refreshUniformsLine( m_uniforms, material );
  14461. } else if ( material instanceof THREE.LineDashedMaterial ) {
  14462. refreshUniformsLine( m_uniforms, material );
  14463. refreshUniformsDash( m_uniforms, material );
  14464. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  14465. refreshUniformsParticle( m_uniforms, material );
  14466. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  14467. refreshUniformsPhong( m_uniforms, material );
  14468. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  14469. refreshUniformsLambert( m_uniforms, material );
  14470. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  14471. m_uniforms.mNear.value = camera.near;
  14472. m_uniforms.mFar.value = camera.far;
  14473. m_uniforms.opacity.value = material.opacity;
  14474. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  14475. m_uniforms.opacity.value = material.opacity;
  14476. }
  14477. if ( object.receiveShadow && ! material._shadowPass ) {
  14478. refreshUniformsShadow( m_uniforms, lights );
  14479. }
  14480. // load common uniforms
  14481. loadUniformsGeneric( program, material.uniformsList );
  14482. // load material specific uniforms
  14483. // (shader material also gets them for the sake of genericity)
  14484. if ( material instanceof THREE.ShaderMaterial ||
  14485. material instanceof THREE.MeshPhongMaterial ||
  14486. material.envMap ) {
  14487. if ( p_uniforms.cameraPosition !== null ) {
  14488. _vector3.getPositionFromMatrix( camera.matrixWorld );
  14489. _gl.uniform3f( p_uniforms.cameraPosition, _vector3.x, _vector3.y, _vector3.z );
  14490. }
  14491. }
  14492. if ( material instanceof THREE.MeshPhongMaterial ||
  14493. material instanceof THREE.MeshLambertMaterial ||
  14494. material instanceof THREE.ShaderMaterial ||
  14495. material.skinning ) {
  14496. if ( p_uniforms.viewMatrix !== null ) {
  14497. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  14498. }
  14499. }
  14500. }
  14501. loadUniformsMatrices( p_uniforms, object );
  14502. if ( p_uniforms.modelMatrix !== null ) {
  14503. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  14504. }
  14505. return program;
  14506. };
  14507. // Uniforms (refresh uniforms objects)
  14508. function refreshUniformsCommon ( uniforms, material ) {
  14509. uniforms.opacity.value = material.opacity;
  14510. if ( _this.gammaInput ) {
  14511. uniforms.diffuse.value.copyGammaToLinear( material.color );
  14512. } else {
  14513. uniforms.diffuse.value = material.color;
  14514. }
  14515. uniforms.map.value = material.map;
  14516. uniforms.lightMap.value = material.lightMap;
  14517. uniforms.specularMap.value = material.specularMap;
  14518. if ( material.bumpMap ) {
  14519. uniforms.bumpMap.value = material.bumpMap;
  14520. uniforms.bumpScale.value = material.bumpScale;
  14521. }
  14522. if ( material.normalMap ) {
  14523. uniforms.normalMap.value = material.normalMap;
  14524. uniforms.normalScale.value.copy( material.normalScale );
  14525. }
  14526. // uv repeat and offset setting priorities
  14527. // 1. color map
  14528. // 2. specular map
  14529. // 3. normal map
  14530. // 4. bump map
  14531. var uvScaleMap;
  14532. if ( material.map ) {
  14533. uvScaleMap = material.map;
  14534. } else if ( material.specularMap ) {
  14535. uvScaleMap = material.specularMap;
  14536. } else if ( material.normalMap ) {
  14537. uvScaleMap = material.normalMap;
  14538. } else if ( material.bumpMap ) {
  14539. uvScaleMap = material.bumpMap;
  14540. }
  14541. if ( uvScaleMap !== undefined ) {
  14542. var offset = uvScaleMap.offset;
  14543. var repeat = uvScaleMap.repeat;
  14544. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  14545. }
  14546. uniforms.envMap.value = material.envMap;
  14547. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  14548. if ( _this.gammaInput ) {
  14549. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  14550. uniforms.reflectivity.value = material.reflectivity;
  14551. } else {
  14552. uniforms.reflectivity.value = material.reflectivity;
  14553. }
  14554. uniforms.refractionRatio.value = material.refractionRatio;
  14555. uniforms.combine.value = material.combine;
  14556. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  14557. };
  14558. function refreshUniformsLine ( uniforms, material ) {
  14559. uniforms.diffuse.value = material.color;
  14560. uniforms.opacity.value = material.opacity;
  14561. };
  14562. function refreshUniformsDash ( uniforms, material ) {
  14563. uniforms.dashSize.value = material.dashSize;
  14564. uniforms.totalSize.value = material.dashSize + material.gapSize;
  14565. uniforms.scale.value = material.scale;
  14566. };
  14567. function refreshUniformsParticle ( uniforms, material ) {
  14568. uniforms.psColor.value = material.color;
  14569. uniforms.opacity.value = material.opacity;
  14570. uniforms.size.value = material.size;
  14571. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  14572. uniforms.map.value = material.map;
  14573. };
  14574. function refreshUniformsFog ( uniforms, fog ) {
  14575. uniforms.fogColor.value = fog.color;
  14576. if ( fog instanceof THREE.Fog ) {
  14577. uniforms.fogNear.value = fog.near;
  14578. uniforms.fogFar.value = fog.far;
  14579. } else if ( fog instanceof THREE.FogExp2 ) {
  14580. uniforms.fogDensity.value = fog.density;
  14581. }
  14582. };
  14583. function refreshUniformsPhong ( uniforms, material ) {
  14584. uniforms.shininess.value = material.shininess;
  14585. if ( _this.gammaInput ) {
  14586. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14587. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14588. uniforms.specular.value.copyGammaToLinear( material.specular );
  14589. } else {
  14590. uniforms.ambient.value = material.ambient;
  14591. uniforms.emissive.value = material.emissive;
  14592. uniforms.specular.value = material.specular;
  14593. }
  14594. if ( material.wrapAround ) {
  14595. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14596. }
  14597. };
  14598. function refreshUniformsLambert ( uniforms, material ) {
  14599. if ( _this.gammaInput ) {
  14600. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  14601. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  14602. } else {
  14603. uniforms.ambient.value = material.ambient;
  14604. uniforms.emissive.value = material.emissive;
  14605. }
  14606. if ( material.wrapAround ) {
  14607. uniforms.wrapRGB.value.copy( material.wrapRGB );
  14608. }
  14609. };
  14610. function refreshUniformsLights ( uniforms, lights ) {
  14611. uniforms.ambientLightColor.value = lights.ambient;
  14612. uniforms.directionalLightColor.value = lights.directional.colors;
  14613. uniforms.directionalLightDirection.value = lights.directional.positions;
  14614. uniforms.pointLightColor.value = lights.point.colors;
  14615. uniforms.pointLightPosition.value = lights.point.positions;
  14616. uniforms.pointLightDistance.value = lights.point.distances;
  14617. uniforms.spotLightColor.value = lights.spot.colors;
  14618. uniforms.spotLightPosition.value = lights.spot.positions;
  14619. uniforms.spotLightDistance.value = lights.spot.distances;
  14620. uniforms.spotLightDirection.value = lights.spot.directions;
  14621. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  14622. uniforms.spotLightExponent.value = lights.spot.exponents;
  14623. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  14624. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  14625. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  14626. };
  14627. function refreshUniformsShadow ( uniforms, lights ) {
  14628. if ( uniforms.shadowMatrix ) {
  14629. var j = 0;
  14630. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  14631. var light = lights[ i ];
  14632. if ( ! light.castShadow ) continue;
  14633. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  14634. uniforms.shadowMap.value[ j ] = light.shadowMap;
  14635. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  14636. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  14637. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  14638. uniforms.shadowBias.value[ j ] = light.shadowBias;
  14639. j ++;
  14640. }
  14641. }
  14642. }
  14643. };
  14644. // Uniforms (load to GPU)
  14645. function loadUniformsMatrices ( uniforms, object ) {
  14646. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  14647. if ( uniforms.normalMatrix ) {
  14648. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  14649. }
  14650. };
  14651. function getTextureUnit() {
  14652. var textureUnit = _usedTextureUnits;
  14653. if ( textureUnit >= _maxTextures ) {
  14654. console.warn( "WebGLRenderer: trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  14655. }
  14656. _usedTextureUnits += 1;
  14657. return textureUnit;
  14658. };
  14659. function loadUniformsGeneric ( program, uniforms ) {
  14660. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  14661. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  14662. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  14663. if ( !location ) continue;
  14664. uniform = uniforms[ j ][ 0 ];
  14665. type = uniform.type;
  14666. value = uniform.value;
  14667. if ( type === "i" ) { // single integer
  14668. _gl.uniform1i( location, value );
  14669. } else if ( type === "f" ) { // single float
  14670. _gl.uniform1f( location, value );
  14671. } else if ( type === "v2" ) { // single THREE.Vector2
  14672. _gl.uniform2f( location, value.x, value.y );
  14673. } else if ( type === "v3" ) { // single THREE.Vector3
  14674. _gl.uniform3f( location, value.x, value.y, value.z );
  14675. } else if ( type === "v4" ) { // single THREE.Vector4
  14676. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  14677. } else if ( type === "c" ) { // single THREE.Color
  14678. _gl.uniform3f( location, value.r, value.g, value.b );
  14679. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  14680. _gl.uniform1iv( location, value );
  14681. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  14682. _gl.uniform3iv( location, value );
  14683. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  14684. _gl.uniform1fv( location, value );
  14685. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  14686. _gl.uniform3fv( location, value );
  14687. } else if ( type === "v2v" ) { // array of THREE.Vector2
  14688. if ( uniform._array === undefined ) {
  14689. uniform._array = new Float32Array( 2 * value.length );
  14690. }
  14691. for ( i = 0, il = value.length; i < il; i ++ ) {
  14692. offset = i * 2;
  14693. uniform._array[ offset ] = value[ i ].x;
  14694. uniform._array[ offset + 1 ] = value[ i ].y;
  14695. }
  14696. _gl.uniform2fv( location, uniform._array );
  14697. } else if ( type === "v3v" ) { // array of THREE.Vector3
  14698. if ( uniform._array === undefined ) {
  14699. uniform._array = new Float32Array( 3 * value.length );
  14700. }
  14701. for ( i = 0, il = value.length; i < il; i ++ ) {
  14702. offset = i * 3;
  14703. uniform._array[ offset ] = value[ i ].x;
  14704. uniform._array[ offset + 1 ] = value[ i ].y;
  14705. uniform._array[ offset + 2 ] = value[ i ].z;
  14706. }
  14707. _gl.uniform3fv( location, uniform._array );
  14708. } else if ( type === "v4v" ) { // array of THREE.Vector4
  14709. if ( uniform._array === undefined ) {
  14710. uniform._array = new Float32Array( 4 * value.length );
  14711. }
  14712. for ( i = 0, il = value.length; i < il; i ++ ) {
  14713. offset = i * 4;
  14714. uniform._array[ offset ] = value[ i ].x;
  14715. uniform._array[ offset + 1 ] = value[ i ].y;
  14716. uniform._array[ offset + 2 ] = value[ i ].z;
  14717. uniform._array[ offset + 3 ] = value[ i ].w;
  14718. }
  14719. _gl.uniform4fv( location, uniform._array );
  14720. } else if ( type === "m4") { // single THREE.Matrix4
  14721. if ( uniform._array === undefined ) {
  14722. uniform._array = new Float32Array( 16 );
  14723. }
  14724. value.flattenToArray( uniform._array );
  14725. _gl.uniformMatrix4fv( location, false, uniform._array );
  14726. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  14727. if ( uniform._array === undefined ) {
  14728. uniform._array = new Float32Array( 16 * value.length );
  14729. }
  14730. for ( i = 0, il = value.length; i < il; i ++ ) {
  14731. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  14732. }
  14733. _gl.uniformMatrix4fv( location, false, uniform._array );
  14734. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  14735. texture = value;
  14736. textureUnit = getTextureUnit();
  14737. _gl.uniform1i( location, textureUnit );
  14738. if ( !texture ) continue;
  14739. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  14740. setCubeTexture( texture, textureUnit );
  14741. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  14742. setCubeTextureDynamic( texture, textureUnit );
  14743. } else {
  14744. _this.setTexture( texture, textureUnit );
  14745. }
  14746. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  14747. if ( uniform._array === undefined ) {
  14748. uniform._array = [];
  14749. }
  14750. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14751. uniform._array[ i ] = getTextureUnit();
  14752. }
  14753. _gl.uniform1iv( location, uniform._array );
  14754. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  14755. texture = uniform.value[ i ];
  14756. textureUnit = uniform._array[ i ];
  14757. if ( !texture ) continue;
  14758. _this.setTexture( texture, textureUnit );
  14759. }
  14760. }
  14761. }
  14762. };
  14763. function setupMatrices ( object, camera ) {
  14764. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  14765. object._normalMatrix.getNormalMatrix( object._modelViewMatrix );
  14766. };
  14767. //
  14768. function setColorGamma( array, offset, color, intensitySq ) {
  14769. array[ offset ] = color.r * color.r * intensitySq;
  14770. array[ offset + 1 ] = color.g * color.g * intensitySq;
  14771. array[ offset + 2 ] = color.b * color.b * intensitySq;
  14772. };
  14773. function setColorLinear( array, offset, color, intensity ) {
  14774. array[ offset ] = color.r * intensity;
  14775. array[ offset + 1 ] = color.g * intensity;
  14776. array[ offset + 2 ] = color.b * intensity;
  14777. };
  14778. function setupLights ( program, lights ) {
  14779. var l, ll, light, n,
  14780. r = 0, g = 0, b = 0,
  14781. color, skyColor, groundColor,
  14782. intensity, intensitySq,
  14783. position,
  14784. distance,
  14785. zlights = _lights,
  14786. dirColors = zlights.directional.colors,
  14787. dirPositions = zlights.directional.positions,
  14788. pointColors = zlights.point.colors,
  14789. pointPositions = zlights.point.positions,
  14790. pointDistances = zlights.point.distances,
  14791. spotColors = zlights.spot.colors,
  14792. spotPositions = zlights.spot.positions,
  14793. spotDistances = zlights.spot.distances,
  14794. spotDirections = zlights.spot.directions,
  14795. spotAnglesCos = zlights.spot.anglesCos,
  14796. spotExponents = zlights.spot.exponents,
  14797. hemiSkyColors = zlights.hemi.skyColors,
  14798. hemiGroundColors = zlights.hemi.groundColors,
  14799. hemiPositions = zlights.hemi.positions,
  14800. dirLength = 0,
  14801. pointLength = 0,
  14802. spotLength = 0,
  14803. hemiLength = 0,
  14804. dirCount = 0,
  14805. pointCount = 0,
  14806. spotCount = 0,
  14807. hemiCount = 0,
  14808. dirOffset = 0,
  14809. pointOffset = 0,
  14810. spotOffset = 0,
  14811. hemiOffset = 0;
  14812. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14813. light = lights[ l ];
  14814. if ( light.onlyShadow ) continue;
  14815. color = light.color;
  14816. intensity = light.intensity;
  14817. distance = light.distance;
  14818. if ( light instanceof THREE.AmbientLight ) {
  14819. if ( ! light.visible ) continue;
  14820. if ( _this.gammaInput ) {
  14821. r += color.r * color.r;
  14822. g += color.g * color.g;
  14823. b += color.b * color.b;
  14824. } else {
  14825. r += color.r;
  14826. g += color.g;
  14827. b += color.b;
  14828. }
  14829. } else if ( light instanceof THREE.DirectionalLight ) {
  14830. dirCount += 1;
  14831. if ( ! light.visible ) continue;
  14832. _direction.getPositionFromMatrix( light.matrixWorld );
  14833. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14834. _direction.sub( _vector3 );
  14835. _direction.normalize();
  14836. // skip lights with undefined direction
  14837. // these create troubles in OpenGL (making pixel black)
  14838. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14839. dirOffset = dirLength * 3;
  14840. dirPositions[ dirOffset ] = _direction.x;
  14841. dirPositions[ dirOffset + 1 ] = _direction.y;
  14842. dirPositions[ dirOffset + 2 ] = _direction.z;
  14843. if ( _this.gammaInput ) {
  14844. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  14845. } else {
  14846. setColorLinear( dirColors, dirOffset, color, intensity );
  14847. }
  14848. dirLength += 1;
  14849. } else if ( light instanceof THREE.PointLight ) {
  14850. pointCount += 1;
  14851. if ( ! light.visible ) continue;
  14852. pointOffset = pointLength * 3;
  14853. if ( _this.gammaInput ) {
  14854. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  14855. } else {
  14856. setColorLinear( pointColors, pointOffset, color, intensity );
  14857. }
  14858. _vector3.getPositionFromMatrix( light.matrixWorld );
  14859. pointPositions[ pointOffset ] = _vector3.x;
  14860. pointPositions[ pointOffset + 1 ] = _vector3.y;
  14861. pointPositions[ pointOffset + 2 ] = _vector3.z;
  14862. pointDistances[ pointLength ] = distance;
  14863. pointLength += 1;
  14864. } else if ( light instanceof THREE.SpotLight ) {
  14865. spotCount += 1;
  14866. if ( ! light.visible ) continue;
  14867. spotOffset = spotLength * 3;
  14868. if ( _this.gammaInput ) {
  14869. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  14870. } else {
  14871. setColorLinear( spotColors, spotOffset, color, intensity );
  14872. }
  14873. _vector3.getPositionFromMatrix( light.matrixWorld );
  14874. spotPositions[ spotOffset ] = _vector3.x;
  14875. spotPositions[ spotOffset + 1 ] = _vector3.y;
  14876. spotPositions[ spotOffset + 2 ] = _vector3.z;
  14877. spotDistances[ spotLength ] = distance;
  14878. _direction.copy( _vector3 );
  14879. _vector3.getPositionFromMatrix( light.target.matrixWorld );
  14880. _direction.sub( _vector3 );
  14881. _direction.normalize();
  14882. spotDirections[ spotOffset ] = _direction.x;
  14883. spotDirections[ spotOffset + 1 ] = _direction.y;
  14884. spotDirections[ spotOffset + 2 ] = _direction.z;
  14885. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  14886. spotExponents[ spotLength ] = light.exponent;
  14887. spotLength += 1;
  14888. } else if ( light instanceof THREE.HemisphereLight ) {
  14889. hemiCount += 1;
  14890. if ( ! light.visible ) continue;
  14891. _direction.getPositionFromMatrix( light.matrixWorld );
  14892. _direction.normalize();
  14893. // skip lights with undefined direction
  14894. // these create troubles in OpenGL (making pixel black)
  14895. if ( _direction.x === 0 && _direction.y === 0 && _direction.z === 0 ) continue;
  14896. hemiOffset = hemiLength * 3;
  14897. hemiPositions[ hemiOffset ] = _direction.x;
  14898. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  14899. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  14900. skyColor = light.color;
  14901. groundColor = light.groundColor;
  14902. if ( _this.gammaInput ) {
  14903. intensitySq = intensity * intensity;
  14904. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  14905. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  14906. } else {
  14907. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  14908. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  14909. }
  14910. hemiLength += 1;
  14911. }
  14912. }
  14913. // null eventual remains from removed lights
  14914. // (this is to avoid if in shader)
  14915. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  14916. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  14917. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  14918. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  14919. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  14920. zlights.directional.length = dirLength;
  14921. zlights.point.length = pointLength;
  14922. zlights.spot.length = spotLength;
  14923. zlights.hemi.length = hemiLength;
  14924. zlights.ambient[ 0 ] = r;
  14925. zlights.ambient[ 1 ] = g;
  14926. zlights.ambient[ 2 ] = b;
  14927. };
  14928. // GL state setting
  14929. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  14930. if ( cullFace === THREE.CullFaceNone ) {
  14931. _gl.disable( _gl.CULL_FACE );
  14932. } else {
  14933. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  14934. _gl.frontFace( _gl.CW );
  14935. } else {
  14936. _gl.frontFace( _gl.CCW );
  14937. }
  14938. if ( cullFace === THREE.CullFaceBack ) {
  14939. _gl.cullFace( _gl.BACK );
  14940. } else if ( cullFace === THREE.CullFaceFront ) {
  14941. _gl.cullFace( _gl.FRONT );
  14942. } else {
  14943. _gl.cullFace( _gl.FRONT_AND_BACK );
  14944. }
  14945. _gl.enable( _gl.CULL_FACE );
  14946. }
  14947. };
  14948. this.setMaterialFaces = function ( material ) {
  14949. var doubleSided = material.side === THREE.DoubleSide;
  14950. var flipSided = material.side === THREE.BackSide;
  14951. if ( _oldDoubleSided !== doubleSided ) {
  14952. if ( doubleSided ) {
  14953. _gl.disable( _gl.CULL_FACE );
  14954. } else {
  14955. _gl.enable( _gl.CULL_FACE );
  14956. }
  14957. _oldDoubleSided = doubleSided;
  14958. }
  14959. if ( _oldFlipSided !== flipSided ) {
  14960. if ( flipSided ) {
  14961. _gl.frontFace( _gl.CW );
  14962. } else {
  14963. _gl.frontFace( _gl.CCW );
  14964. }
  14965. _oldFlipSided = flipSided;
  14966. }
  14967. };
  14968. this.setDepthTest = function ( depthTest ) {
  14969. if ( _oldDepthTest !== depthTest ) {
  14970. if ( depthTest ) {
  14971. _gl.enable( _gl.DEPTH_TEST );
  14972. } else {
  14973. _gl.disable( _gl.DEPTH_TEST );
  14974. }
  14975. _oldDepthTest = depthTest;
  14976. }
  14977. };
  14978. this.setDepthWrite = function ( depthWrite ) {
  14979. if ( _oldDepthWrite !== depthWrite ) {
  14980. _gl.depthMask( depthWrite );
  14981. _oldDepthWrite = depthWrite;
  14982. }
  14983. };
  14984. function setLineWidth ( width ) {
  14985. if ( width !== _oldLineWidth ) {
  14986. _gl.lineWidth( width );
  14987. _oldLineWidth = width;
  14988. }
  14989. };
  14990. function setPolygonOffset ( polygonoffset, factor, units ) {
  14991. if ( _oldPolygonOffset !== polygonoffset ) {
  14992. if ( polygonoffset ) {
  14993. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  14994. } else {
  14995. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  14996. }
  14997. _oldPolygonOffset = polygonoffset;
  14998. }
  14999. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  15000. _gl.polygonOffset( factor, units );
  15001. _oldPolygonOffsetFactor = factor;
  15002. _oldPolygonOffsetUnits = units;
  15003. }
  15004. };
  15005. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  15006. if ( blending !== _oldBlending ) {
  15007. if ( blending === THREE.NoBlending ) {
  15008. _gl.disable( _gl.BLEND );
  15009. } else if ( blending === THREE.AdditiveBlending ) {
  15010. _gl.enable( _gl.BLEND );
  15011. _gl.blendEquation( _gl.FUNC_ADD );
  15012. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  15013. } else if ( blending === THREE.SubtractiveBlending ) {
  15014. // TODO: Find blendFuncSeparate() combination
  15015. _gl.enable( _gl.BLEND );
  15016. _gl.blendEquation( _gl.FUNC_ADD );
  15017. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  15018. } else if ( blending === THREE.MultiplyBlending ) {
  15019. // TODO: Find blendFuncSeparate() combination
  15020. _gl.enable( _gl.BLEND );
  15021. _gl.blendEquation( _gl.FUNC_ADD );
  15022. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  15023. } else if ( blending === THREE.CustomBlending ) {
  15024. _gl.enable( _gl.BLEND );
  15025. } else {
  15026. _gl.enable( _gl.BLEND );
  15027. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  15028. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  15029. }
  15030. _oldBlending = blending;
  15031. }
  15032. if ( blending === THREE.CustomBlending ) {
  15033. if ( blendEquation !== _oldBlendEquation ) {
  15034. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  15035. _oldBlendEquation = blendEquation;
  15036. }
  15037. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  15038. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  15039. _oldBlendSrc = blendSrc;
  15040. _oldBlendDst = blendDst;
  15041. }
  15042. } else {
  15043. _oldBlendEquation = null;
  15044. _oldBlendSrc = null;
  15045. _oldBlendDst = null;
  15046. }
  15047. };
  15048. // Defines
  15049. function generateDefines ( defines ) {
  15050. var value, chunk, chunks = [];
  15051. for ( var d in defines ) {
  15052. value = defines[ d ];
  15053. if ( value === false ) continue;
  15054. chunk = "#define " + d + " " + value;
  15055. chunks.push( chunk );
  15056. }
  15057. return chunks.join( "\n" );
  15058. };
  15059. // Shaders
  15060. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  15061. var p, pl, d, program, code;
  15062. var chunks = [];
  15063. // Generate code
  15064. if ( shaderID ) {
  15065. chunks.push( shaderID );
  15066. } else {
  15067. chunks.push( fragmentShader );
  15068. chunks.push( vertexShader );
  15069. }
  15070. for ( d in defines ) {
  15071. chunks.push( d );
  15072. chunks.push( defines[ d ] );
  15073. }
  15074. for ( p in parameters ) {
  15075. chunks.push( p );
  15076. chunks.push( parameters[ p ] );
  15077. }
  15078. code = chunks.join();
  15079. // Check if code has been already compiled
  15080. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  15081. var programInfo = _programs[ p ];
  15082. if ( programInfo.code === code ) {
  15083. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  15084. programInfo.usedTimes ++;
  15085. return programInfo.program;
  15086. }
  15087. }
  15088. var shadowMapTypeDefine = "SHADOWMAP_TYPE_BASIC";
  15089. if ( parameters.shadowMapType === THREE.PCFShadowMap ) {
  15090. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF";
  15091. } else if ( parameters.shadowMapType === THREE.PCFSoftShadowMap ) {
  15092. shadowMapTypeDefine = "SHADOWMAP_TYPE_PCF_SOFT";
  15093. }
  15094. // console.log( "building new program " );
  15095. //
  15096. var customDefines = generateDefines( defines );
  15097. //
  15098. program = _gl.createProgram();
  15099. var prefix_vertex = [
  15100. "precision " + _precision + " float;",
  15101. customDefines,
  15102. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  15103. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15104. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15105. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15106. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15107. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15108. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15109. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15110. "#define MAX_SHADOWS " + parameters.maxShadows,
  15111. "#define MAX_BONES " + parameters.maxBones,
  15112. parameters.map ? "#define USE_MAP" : "",
  15113. parameters.envMap ? "#define USE_ENVMAP" : "",
  15114. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15115. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15116. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15117. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15118. parameters.vertexColors ? "#define USE_COLOR" : "",
  15119. parameters.skinning ? "#define USE_SKINNING" : "",
  15120. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  15121. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  15122. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  15123. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  15124. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  15125. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15126. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15127. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15128. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15129. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15130. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15131. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15132. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15133. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  15134. "uniform mat4 modelMatrix;",
  15135. "uniform mat4 modelViewMatrix;",
  15136. "uniform mat4 projectionMatrix;",
  15137. "uniform mat4 viewMatrix;",
  15138. "uniform mat3 normalMatrix;",
  15139. "uniform vec3 cameraPosition;",
  15140. "attribute vec3 position;",
  15141. "attribute vec3 normal;",
  15142. "attribute vec2 uv;",
  15143. "attribute vec2 uv2;",
  15144. "#ifdef USE_COLOR",
  15145. "attribute vec3 color;",
  15146. "#endif",
  15147. "#ifdef USE_MORPHTARGETS",
  15148. "attribute vec3 morphTarget0;",
  15149. "attribute vec3 morphTarget1;",
  15150. "attribute vec3 morphTarget2;",
  15151. "attribute vec3 morphTarget3;",
  15152. "#ifdef USE_MORPHNORMALS",
  15153. "attribute vec3 morphNormal0;",
  15154. "attribute vec3 morphNormal1;",
  15155. "attribute vec3 morphNormal2;",
  15156. "attribute vec3 morphNormal3;",
  15157. "#else",
  15158. "attribute vec3 morphTarget4;",
  15159. "attribute vec3 morphTarget5;",
  15160. "attribute vec3 morphTarget6;",
  15161. "attribute vec3 morphTarget7;",
  15162. "#endif",
  15163. "#endif",
  15164. "#ifdef USE_SKINNING",
  15165. "attribute vec4 skinIndex;",
  15166. "attribute vec4 skinWeight;",
  15167. "#endif",
  15168. ""
  15169. ].join("\n");
  15170. var prefix_fragment = [
  15171. "precision " + _precision + " float;",
  15172. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  15173. customDefines,
  15174. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  15175. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  15176. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  15177. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  15178. "#define MAX_SHADOWS " + parameters.maxShadows,
  15179. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  15180. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  15181. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  15182. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  15183. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  15184. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  15185. parameters.map ? "#define USE_MAP" : "",
  15186. parameters.envMap ? "#define USE_ENVMAP" : "",
  15187. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  15188. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  15189. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  15190. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  15191. parameters.vertexColors ? "#define USE_COLOR" : "",
  15192. parameters.metal ? "#define METAL" : "",
  15193. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  15194. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  15195. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  15196. parameters.flipSided ? "#define FLIP_SIDED" : "",
  15197. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  15198. parameters.shadowMapEnabled ? "#define " + shadowMapTypeDefine : "",
  15199. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  15200. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  15201. "uniform mat4 viewMatrix;",
  15202. "uniform vec3 cameraPosition;",
  15203. ""
  15204. ].join("\n");
  15205. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  15206. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  15207. _gl.attachShader( program, glVertexShader );
  15208. _gl.attachShader( program, glFragmentShader );
  15209. _gl.linkProgram( program );
  15210. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  15211. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  15212. }
  15213. // clean up
  15214. _gl.deleteShader( glFragmentShader );
  15215. _gl.deleteShader( glVertexShader );
  15216. // console.log( prefix_fragment + fragmentShader );
  15217. // console.log( prefix_vertex + vertexShader );
  15218. program.uniforms = {};
  15219. program.attributes = {};
  15220. var identifiers, u, a, i;
  15221. // cache uniform locations
  15222. identifiers = [
  15223. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  15224. 'morphTargetInfluences'
  15225. ];
  15226. if ( parameters.useVertexTexture ) {
  15227. identifiers.push( 'boneTexture' );
  15228. } else {
  15229. identifiers.push( 'boneGlobalMatrices' );
  15230. }
  15231. for ( u in uniforms ) {
  15232. identifiers.push( u );
  15233. }
  15234. cacheUniformLocations( program, identifiers );
  15235. // cache attributes locations
  15236. identifiers = [
  15237. "position", "normal", "uv", "uv2", "tangent", "color",
  15238. "skinIndex", "skinWeight", "lineDistance"
  15239. ];
  15240. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  15241. identifiers.push( "morphTarget" + i );
  15242. }
  15243. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  15244. identifiers.push( "morphNormal" + i );
  15245. }
  15246. for ( a in attributes ) {
  15247. identifiers.push( a );
  15248. }
  15249. cacheAttributeLocations( program, identifiers );
  15250. program.id = _programs_counter ++;
  15251. _programs.push( { program: program, code: code, usedTimes: 1 } );
  15252. _this.info.memory.programs = _programs.length;
  15253. return program;
  15254. };
  15255. // Shader parameters cache
  15256. function cacheUniformLocations ( program, identifiers ) {
  15257. var i, l, id;
  15258. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15259. id = identifiers[ i ];
  15260. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  15261. }
  15262. };
  15263. function cacheAttributeLocations ( program, identifiers ) {
  15264. var i, l, id;
  15265. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  15266. id = identifiers[ i ];
  15267. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  15268. }
  15269. };
  15270. function addLineNumbers ( string ) {
  15271. var chunks = string.split( "\n" );
  15272. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  15273. // Chrome reports shader errors on lines
  15274. // starting counting from 1
  15275. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  15276. }
  15277. return chunks.join( "\n" );
  15278. };
  15279. function getShader ( type, string ) {
  15280. var shader;
  15281. if ( type === "fragment" ) {
  15282. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  15283. } else if ( type === "vertex" ) {
  15284. shader = _gl.createShader( _gl.VERTEX_SHADER );
  15285. }
  15286. _gl.shaderSource( shader, string );
  15287. _gl.compileShader( shader );
  15288. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  15289. console.error( _gl.getShaderInfoLog( shader ) );
  15290. console.error( addLineNumbers( string ) );
  15291. return null;
  15292. }
  15293. return shader;
  15294. };
  15295. // Textures
  15296. function isPowerOfTwo ( value ) {
  15297. return ( value & ( value - 1 ) ) === 0;
  15298. };
  15299. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  15300. if ( isImagePowerOfTwo ) {
  15301. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  15302. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  15303. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  15304. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  15305. } else {
  15306. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  15307. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  15308. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  15309. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  15310. }
  15311. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  15312. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  15313. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  15314. texture.__oldAnisotropy = texture.anisotropy;
  15315. }
  15316. }
  15317. };
  15318. this.setTexture = function ( texture, slot ) {
  15319. if ( texture.needsUpdate ) {
  15320. if ( ! texture.__webglInit ) {
  15321. texture.__webglInit = true;
  15322. texture.addEventListener( 'dispose', onTextureDispose );
  15323. texture.__webglTexture = _gl.createTexture();
  15324. _this.info.memory.textures ++;
  15325. }
  15326. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15327. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15328. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15329. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  15330. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  15331. var image = texture.image,
  15332. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15333. glFormat = paramThreeToGL( texture.format ),
  15334. glType = paramThreeToGL( texture.type );
  15335. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  15336. var mipmap, mipmaps = texture.mipmaps;
  15337. if ( texture instanceof THREE.DataTexture ) {
  15338. // use manually created mipmaps if available
  15339. // if there are no manual mipmaps
  15340. // set 0 level mipmap and then use GL to generate other mipmap levels
  15341. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15342. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15343. mipmap = mipmaps[ i ];
  15344. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  15345. }
  15346. texture.generateMipmaps = false;
  15347. } else {
  15348. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  15349. }
  15350. } else if ( texture instanceof THREE.CompressedTexture ) {
  15351. // compressed textures can only use manually created mipmaps
  15352. // WebGL can't generate mipmaps for DDS textures
  15353. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15354. mipmap = mipmaps[ i ];
  15355. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15356. }
  15357. } else { // regular Texture (image, video, canvas)
  15358. // use manually created mipmaps if available
  15359. // if there are no manual mipmaps
  15360. // set 0 level mipmap and then use GL to generate other mipmap levels
  15361. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  15362. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  15363. mipmap = mipmaps[ i ];
  15364. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  15365. }
  15366. texture.generateMipmaps = false;
  15367. } else {
  15368. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  15369. }
  15370. }
  15371. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15372. texture.needsUpdate = false;
  15373. if ( texture.onUpdate ) texture.onUpdate();
  15374. } else {
  15375. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15376. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  15377. }
  15378. };
  15379. function clampToMaxSize ( image, maxSize ) {
  15380. if ( image.width <= maxSize && image.height <= maxSize ) {
  15381. return image;
  15382. }
  15383. // Warning: Scaling through the canvas will only work with images that use
  15384. // premultiplied alpha.
  15385. var maxDimension = Math.max( image.width, image.height );
  15386. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  15387. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  15388. var canvas = document.createElement( 'canvas' );
  15389. canvas.width = newWidth;
  15390. canvas.height = newHeight;
  15391. var ctx = canvas.getContext( "2d" );
  15392. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  15393. return canvas;
  15394. }
  15395. function setCubeTexture ( texture, slot ) {
  15396. if ( texture.image.length === 6 ) {
  15397. if ( texture.needsUpdate ) {
  15398. if ( ! texture.image.__webglTextureCube ) {
  15399. texture.addEventListener( 'dispose', onTextureDispose );
  15400. texture.image.__webglTextureCube = _gl.createTexture();
  15401. _this.info.memory.textures ++;
  15402. }
  15403. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15404. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15405. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  15406. var isCompressed = texture instanceof THREE.CompressedTexture;
  15407. var cubeImage = [];
  15408. for ( var i = 0; i < 6; i ++ ) {
  15409. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  15410. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  15411. } else {
  15412. cubeImage[ i ] = texture.image[ i ];
  15413. }
  15414. }
  15415. var image = cubeImage[ 0 ],
  15416. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  15417. glFormat = paramThreeToGL( texture.format ),
  15418. glType = paramThreeToGL( texture.type );
  15419. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  15420. for ( var i = 0; i < 6; i ++ ) {
  15421. if ( isCompressed ) {
  15422. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  15423. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  15424. mipmap = mipmaps[ j ];
  15425. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  15426. }
  15427. } else {
  15428. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  15429. }
  15430. }
  15431. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  15432. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15433. }
  15434. texture.needsUpdate = false;
  15435. if ( texture.onUpdate ) texture.onUpdate();
  15436. } else {
  15437. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15438. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  15439. }
  15440. }
  15441. };
  15442. function setCubeTextureDynamic ( texture, slot ) {
  15443. _gl.activeTexture( _gl.TEXTURE0 + slot );
  15444. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  15445. };
  15446. // Render targets
  15447. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  15448. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15449. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  15450. };
  15451. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  15452. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  15453. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15454. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  15455. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15456. /* For some reason this is not working. Defaulting to RGBA4.
  15457. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15458. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  15459. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15460. */
  15461. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15462. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  15463. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  15464. } else {
  15465. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  15466. }
  15467. };
  15468. this.setRenderTarget = function ( renderTarget ) {
  15469. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  15470. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  15471. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  15472. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  15473. renderTarget.addEventListener( 'dispose', onRenderTargetDispose );
  15474. renderTarget.__webglTexture = _gl.createTexture();
  15475. _this.info.memory.textures ++;
  15476. // Setup texture, create render and frame buffers
  15477. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  15478. glFormat = paramThreeToGL( renderTarget.format ),
  15479. glType = paramThreeToGL( renderTarget.type );
  15480. if ( isCube ) {
  15481. renderTarget.__webglFramebuffer = [];
  15482. renderTarget.__webglRenderbuffer = [];
  15483. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15484. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  15485. for ( var i = 0; i < 6; i ++ ) {
  15486. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  15487. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  15488. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15489. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  15490. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  15491. }
  15492. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15493. } else {
  15494. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  15495. if ( renderTarget.shareDepthFrom ) {
  15496. renderTarget.__webglRenderbuffer = renderTarget.shareDepthFrom.__webglRenderbuffer;
  15497. } else {
  15498. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  15499. }
  15500. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15501. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  15502. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  15503. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  15504. if ( renderTarget.shareDepthFrom ) {
  15505. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  15506. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15507. } else if ( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  15508. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderTarget.__webglRenderbuffer );
  15509. }
  15510. } else {
  15511. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  15512. }
  15513. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  15514. }
  15515. // Release everything
  15516. if ( isCube ) {
  15517. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15518. } else {
  15519. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15520. }
  15521. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  15522. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  15523. }
  15524. var framebuffer, width, height, vx, vy;
  15525. if ( renderTarget ) {
  15526. if ( isCube ) {
  15527. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  15528. } else {
  15529. framebuffer = renderTarget.__webglFramebuffer;
  15530. }
  15531. width = renderTarget.width;
  15532. height = renderTarget.height;
  15533. vx = 0;
  15534. vy = 0;
  15535. } else {
  15536. framebuffer = null;
  15537. width = _viewportWidth;
  15538. height = _viewportHeight;
  15539. vx = _viewportX;
  15540. vy = _viewportY;
  15541. }
  15542. if ( framebuffer !== _currentFramebuffer ) {
  15543. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  15544. _gl.viewport( vx, vy, width, height );
  15545. _currentFramebuffer = framebuffer;
  15546. }
  15547. _currentWidth = width;
  15548. _currentHeight = height;
  15549. };
  15550. function updateRenderTargetMipmap ( renderTarget ) {
  15551. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  15552. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  15553. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  15554. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  15555. } else {
  15556. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  15557. _gl.generateMipmap( _gl.TEXTURE_2D );
  15558. _gl.bindTexture( _gl.TEXTURE_2D, null );
  15559. }
  15560. };
  15561. // Fallback filters for non-power-of-2 textures
  15562. function filterFallback ( f ) {
  15563. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  15564. return _gl.NEAREST;
  15565. }
  15566. return _gl.LINEAR;
  15567. };
  15568. // Map three.js constants to WebGL constants
  15569. function paramThreeToGL ( p ) {
  15570. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  15571. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  15572. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  15573. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  15574. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  15575. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  15576. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  15577. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  15578. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  15579. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  15580. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  15581. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  15582. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  15583. if ( p === THREE.ByteType ) return _gl.BYTE;
  15584. if ( p === THREE.ShortType ) return _gl.SHORT;
  15585. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  15586. if ( p === THREE.IntType ) return _gl.INT;
  15587. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  15588. if ( p === THREE.FloatType ) return _gl.FLOAT;
  15589. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  15590. if ( p === THREE.RGBFormat ) return _gl.RGB;
  15591. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  15592. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  15593. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  15594. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  15595. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  15596. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  15597. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  15598. if ( p === THREE.OneFactor ) return _gl.ONE;
  15599. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  15600. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  15601. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  15602. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  15603. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  15604. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  15605. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  15606. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  15607. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  15608. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  15609. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  15610. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  15611. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  15612. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  15613. }
  15614. return 0;
  15615. };
  15616. // Allocations
  15617. function allocateBones ( object ) {
  15618. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  15619. return 1024;
  15620. } else {
  15621. // default for when object is not specified
  15622. // ( for example when prebuilding shader
  15623. // to be used with multiple objects )
  15624. //
  15625. // - leave some extra space for other uniforms
  15626. // - limit here is ANGLE's 254 max uniform vectors
  15627. // (up to 54 should be safe)
  15628. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  15629. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  15630. var maxBones = nVertexMatrices;
  15631. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  15632. maxBones = Math.min( object.bones.length, maxBones );
  15633. if ( maxBones < object.bones.length ) {
  15634. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  15635. }
  15636. }
  15637. return maxBones;
  15638. }
  15639. };
  15640. function allocateLights( lights ) {
  15641. var dirLights = 0;
  15642. var pointLights = 0;
  15643. var spotLights = 0;
  15644. var hemiLights = 0;
  15645. for ( var l = 0, ll = lights.length; l < ll; l ++ ) {
  15646. var light = lights[ l ];
  15647. if ( light.onlyShadow ) continue;
  15648. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  15649. if ( light instanceof THREE.PointLight ) pointLights ++;
  15650. if ( light instanceof THREE.SpotLight ) spotLights ++;
  15651. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  15652. }
  15653. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  15654. };
  15655. function allocateShadows( lights ) {
  15656. var maxShadows = 0;
  15657. for ( var l = 0, ll = lights.length; l < ll; l++ ) {
  15658. var light = lights[ l ];
  15659. if ( ! light.castShadow ) continue;
  15660. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  15661. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  15662. }
  15663. return maxShadows;
  15664. };
  15665. // Initialization
  15666. function initGL() {
  15667. try {
  15668. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  15669. throw 'Error creating WebGL context.';
  15670. }
  15671. } catch ( error ) {
  15672. console.error( error );
  15673. }
  15674. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  15675. _glExtensionTextureFloatLinear = _gl.getExtension( 'OES_texture_float_linear' );
  15676. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  15677. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) || _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  15678. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) || _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  15679. if ( ! _glExtensionTextureFloat ) {
  15680. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  15681. }
  15682. if ( ! _glExtensionStandardDerivatives ) {
  15683. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  15684. }
  15685. if ( ! _glExtensionTextureFilterAnisotropic ) {
  15686. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  15687. }
  15688. if ( ! _glExtensionCompressedTextureS3TC ) {
  15689. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  15690. }
  15691. if ( _gl.getShaderPrecisionFormat === undefined ) {
  15692. _gl.getShaderPrecisionFormat = function() {
  15693. return {
  15694. "rangeMin" : 1,
  15695. "rangeMax" : 1,
  15696. "precision" : 1
  15697. };
  15698. }
  15699. }
  15700. };
  15701. function setDefaultGLState () {
  15702. _gl.clearColor( 0, 0, 0, 1 );
  15703. _gl.clearDepth( 1 );
  15704. _gl.clearStencil( 0 );
  15705. _gl.enable( _gl.DEPTH_TEST );
  15706. _gl.depthFunc( _gl.LEQUAL );
  15707. _gl.frontFace( _gl.CCW );
  15708. _gl.cullFace( _gl.BACK );
  15709. _gl.enable( _gl.CULL_FACE );
  15710. _gl.enable( _gl.BLEND );
  15711. _gl.blendEquation( _gl.FUNC_ADD );
  15712. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  15713. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  15714. };
  15715. // default plugins (order is important)
  15716. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  15717. this.addPrePlugin( this.shadowMapPlugin );
  15718. this.addPostPlugin( new THREE.SpritePlugin() );
  15719. this.addPostPlugin( new THREE.LensFlarePlugin() );
  15720. };
  15721. /**
  15722. * @author szimek / https://github.com/szimek/
  15723. * @author alteredq / http://alteredqualia.com/
  15724. */
  15725. THREE.WebGLRenderTarget = function ( width, height, options ) {
  15726. this.width = width;
  15727. this.height = height;
  15728. options = options || {};
  15729. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  15730. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  15731. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  15732. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  15733. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  15734. this.offset = new THREE.Vector2( 0, 0 );
  15735. this.repeat = new THREE.Vector2( 1, 1 );
  15736. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  15737. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  15738. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  15739. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  15740. this.generateMipmaps = true;
  15741. this.shareDepthFrom = null;
  15742. };
  15743. THREE.WebGLRenderTarget.prototype = {
  15744. constructor: THREE.WebGLRenderTarget,
  15745. addEventListener: THREE.EventDispatcher.prototype.addEventListener,
  15746. hasEventListener: THREE.EventDispatcher.prototype.hasEventListener,
  15747. removeEventListener: THREE.EventDispatcher.prototype.removeEventListener,
  15748. dispatchEvent: THREE.EventDispatcher.prototype.dispatchEvent,
  15749. clone: function () {
  15750. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  15751. tmp.wrapS = this.wrapS;
  15752. tmp.wrapT = this.wrapT;
  15753. tmp.magFilter = this.magFilter;
  15754. tmp.minFilter = this.minFilter;
  15755. tmp.anisotropy = this.anisotropy;
  15756. tmp.offset.copy( this.offset );
  15757. tmp.repeat.copy( this.repeat );
  15758. tmp.format = this.format;
  15759. tmp.type = this.type;
  15760. tmp.depthBuffer = this.depthBuffer;
  15761. tmp.stencilBuffer = this.stencilBuffer;
  15762. tmp.generateMipmaps = this.generateMipmaps;
  15763. tmp.shareDepthFrom = this.shareDepthFrom;
  15764. return tmp;
  15765. },
  15766. dispose: function () {
  15767. this.dispatchEvent( { type: 'dispose' } );
  15768. }
  15769. };
  15770. /**
  15771. * @author alteredq / http://alteredqualia.com
  15772. */
  15773. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  15774. THREE.WebGLRenderTarget.call( this, width, height, options );
  15775. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  15776. };
  15777. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  15778. /**
  15779. * @author mrdoob / http://mrdoob.com/
  15780. */
  15781. THREE.RenderableVertex = function () {
  15782. this.positionWorld = new THREE.Vector3();
  15783. this.positionScreen = new THREE.Vector4();
  15784. this.visible = true;
  15785. };
  15786. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  15787. this.positionWorld.copy( vertex.positionWorld );
  15788. this.positionScreen.copy( vertex.positionScreen );
  15789. };
  15790. /**
  15791. * @author mrdoob / http://mrdoob.com/
  15792. */
  15793. THREE.RenderableFace3 = function () {
  15794. this.v1 = new THREE.RenderableVertex();
  15795. this.v2 = new THREE.RenderableVertex();
  15796. this.v3 = new THREE.RenderableVertex();
  15797. this.centroidModel = new THREE.Vector3();
  15798. this.normalModel = new THREE.Vector3();
  15799. this.normalModelView = new THREE.Vector3();
  15800. this.vertexNormalsLength = 0;
  15801. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15802. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15803. this.color = null;
  15804. this.material = null;
  15805. this.uvs = [[]];
  15806. this.z = null;
  15807. };
  15808. /**
  15809. * @author mrdoob / http://mrdoob.com/
  15810. */
  15811. THREE.RenderableFace4 = function () {
  15812. this.v1 = new THREE.RenderableVertex();
  15813. this.v2 = new THREE.RenderableVertex();
  15814. this.v3 = new THREE.RenderableVertex();
  15815. this.v4 = new THREE.RenderableVertex();
  15816. this.centroidModel = new THREE.Vector3();
  15817. this.normalModel = new THREE.Vector3();
  15818. this.normalModelView = new THREE.Vector3();
  15819. this.vertexNormalsLength = 0;
  15820. this.vertexNormalsModel = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15821. this.vertexNormalsModelView = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  15822. this.color = null;
  15823. this.material = null;
  15824. this.uvs = [[]];
  15825. this.z = null;
  15826. };
  15827. /**
  15828. * @author mrdoob / http://mrdoob.com/
  15829. */
  15830. THREE.RenderableObject = function () {
  15831. this.object = null;
  15832. this.z = null;
  15833. };
  15834. /**
  15835. * @author mrdoob / http://mrdoob.com/
  15836. */
  15837. THREE.RenderableParticle = function () {
  15838. this.object = null;
  15839. this.x = null;
  15840. this.y = null;
  15841. this.z = null;
  15842. this.rotation = null;
  15843. this.scale = new THREE.Vector2();
  15844. this.material = null;
  15845. };
  15846. /**
  15847. * @author mrdoob / http://mrdoob.com/
  15848. */
  15849. THREE.RenderableLine = function () {
  15850. this.z = null;
  15851. this.v1 = new THREE.RenderableVertex();
  15852. this.v2 = new THREE.RenderableVertex();
  15853. this.vertexColors = [ new THREE.Color(), new THREE.Color() ];
  15854. this.material = null;
  15855. };
  15856. /**
  15857. * @author mrdoob / http://mrdoob.com/
  15858. * @author alteredq / http://alteredqualia.com/
  15859. */
  15860. THREE.GeometryUtils = {
  15861. // Merge two geometries or geometry and geometry from object (using object's transform)
  15862. merge: function ( geometry1, object2 /* mesh | geometry */, materialIndexOffset ) {
  15863. var matrix, normalMatrix,
  15864. vertexOffset = geometry1.vertices.length,
  15865. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  15866. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  15867. vertices1 = geometry1.vertices,
  15868. vertices2 = geometry2.vertices,
  15869. faces1 = geometry1.faces,
  15870. faces2 = geometry2.faces,
  15871. uvs1 = geometry1.faceVertexUvs[ 0 ],
  15872. uvs2 = geometry2.faceVertexUvs[ 0 ];
  15873. if ( materialIndexOffset === undefined ) materialIndexOffset = 0;
  15874. if ( object2 instanceof THREE.Mesh ) {
  15875. object2.matrixAutoUpdate && object2.updateMatrix();
  15876. matrix = object2.matrix;
  15877. normalMatrix = new THREE.Matrix3().getNormalMatrix( matrix );
  15878. }
  15879. // vertices
  15880. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  15881. var vertex = vertices2[ i ];
  15882. var vertexCopy = vertex.clone();
  15883. if ( matrix ) vertexCopy.applyMatrix4( matrix );
  15884. vertices1.push( vertexCopy );
  15885. }
  15886. // faces
  15887. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  15888. var face = faces2[ i ], faceCopy, normal, color,
  15889. faceVertexNormals = face.vertexNormals,
  15890. faceVertexColors = face.vertexColors;
  15891. if ( face instanceof THREE.Face3 ) {
  15892. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  15893. } else if ( face instanceof THREE.Face4 ) {
  15894. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  15895. }
  15896. faceCopy.normal.copy( face.normal );
  15897. if ( normalMatrix ) {
  15898. faceCopy.normal.applyMatrix3( normalMatrix ).normalize();
  15899. }
  15900. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  15901. normal = faceVertexNormals[ j ].clone();
  15902. if ( normalMatrix ) {
  15903. normal.applyMatrix3( normalMatrix ).normalize();
  15904. }
  15905. faceCopy.vertexNormals.push( normal );
  15906. }
  15907. faceCopy.color.copy( face.color );
  15908. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  15909. color = faceVertexColors[ j ];
  15910. faceCopy.vertexColors.push( color.clone() );
  15911. }
  15912. faceCopy.materialIndex = face.materialIndex + materialIndexOffset;
  15913. faceCopy.centroid.copy( face.centroid );
  15914. if ( matrix ) {
  15915. faceCopy.centroid.applyMatrix4( matrix );
  15916. }
  15917. faces1.push( faceCopy );
  15918. }
  15919. // uvs
  15920. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  15921. var uv = uvs2[ i ], uvCopy = [];
  15922. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  15923. uvCopy.push( new THREE.Vector2( uv[ j ].x, uv[ j ].y ) );
  15924. }
  15925. uvs1.push( uvCopy );
  15926. }
  15927. },
  15928. removeMaterials: function ( geometry, materialIndexArray ) {
  15929. var materialIndexMap = {};
  15930. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  15931. materialIndexMap[ materialIndexArray[i] ] = true;
  15932. }
  15933. var face, newFaces = [];
  15934. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  15935. face = geometry.faces[ i ];
  15936. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  15937. }
  15938. geometry.faces = newFaces;
  15939. },
  15940. // Get random point in triangle (via barycentric coordinates)
  15941. // (uniform distribution)
  15942. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  15943. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  15944. var a, b, c,
  15945. point = new THREE.Vector3(),
  15946. tmp = THREE.GeometryUtils.__v1;
  15947. a = THREE.GeometryUtils.random();
  15948. b = THREE.GeometryUtils.random();
  15949. if ( ( a + b ) > 1 ) {
  15950. a = 1 - a;
  15951. b = 1 - b;
  15952. }
  15953. c = 1 - a - b;
  15954. point.copy( vectorA );
  15955. point.multiplyScalar( a );
  15956. tmp.copy( vectorB );
  15957. tmp.multiplyScalar( b );
  15958. point.add( tmp );
  15959. tmp.copy( vectorC );
  15960. tmp.multiplyScalar( c );
  15961. point.add( tmp );
  15962. return point;
  15963. },
  15964. // Get random point in face (triangle / quad)
  15965. // (uniform distribution)
  15966. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  15967. var vA, vB, vC, vD;
  15968. if ( face instanceof THREE.Face3 ) {
  15969. vA = geometry.vertices[ face.a ];
  15970. vB = geometry.vertices[ face.b ];
  15971. vC = geometry.vertices[ face.c ];
  15972. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  15973. } else if ( face instanceof THREE.Face4 ) {
  15974. vA = geometry.vertices[ face.a ];
  15975. vB = geometry.vertices[ face.b ];
  15976. vC = geometry.vertices[ face.c ];
  15977. vD = geometry.vertices[ face.d ];
  15978. var area1, area2;
  15979. if ( useCachedAreas ) {
  15980. if ( face._area1 && face._area2 ) {
  15981. area1 = face._area1;
  15982. area2 = face._area2;
  15983. } else {
  15984. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  15985. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15986. face._area1 = area1;
  15987. face._area2 = area2;
  15988. }
  15989. } else {
  15990. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  15991. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  15992. }
  15993. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  15994. if ( r < area1 ) {
  15995. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  15996. } else {
  15997. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  15998. }
  15999. }
  16000. },
  16001. // Get uniformly distributed random points in mesh
  16002. // - create array with cumulative sums of face areas
  16003. // - pick random number from 0 to total area
  16004. // - find corresponding place in area array by binary search
  16005. // - get random point in face
  16006. randomPointsInGeometry: function ( geometry, n ) {
  16007. var face, i,
  16008. faces = geometry.faces,
  16009. vertices = geometry.vertices,
  16010. il = faces.length,
  16011. totalArea = 0,
  16012. cumulativeAreas = [],
  16013. vA, vB, vC, vD;
  16014. // precompute face areas
  16015. for ( i = 0; i < il; i ++ ) {
  16016. face = faces[ i ];
  16017. if ( face instanceof THREE.Face3 ) {
  16018. vA = vertices[ face.a ];
  16019. vB = vertices[ face.b ];
  16020. vC = vertices[ face.c ];
  16021. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  16022. } else if ( face instanceof THREE.Face4 ) {
  16023. vA = vertices[ face.a ];
  16024. vB = vertices[ face.b ];
  16025. vC = vertices[ face.c ];
  16026. vD = vertices[ face.d ];
  16027. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  16028. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  16029. face._area = face._area1 + face._area2;
  16030. }
  16031. totalArea += face._area;
  16032. cumulativeAreas[ i ] = totalArea;
  16033. }
  16034. // binary search cumulative areas array
  16035. function binarySearchIndices( value ) {
  16036. function binarySearch( start, end ) {
  16037. // return closest larger index
  16038. // if exact number is not found
  16039. if ( end < start )
  16040. return start;
  16041. var mid = start + Math.floor( ( end - start ) / 2 );
  16042. if ( cumulativeAreas[ mid ] > value ) {
  16043. return binarySearch( start, mid - 1 );
  16044. } else if ( cumulativeAreas[ mid ] < value ) {
  16045. return binarySearch( mid + 1, end );
  16046. } else {
  16047. return mid;
  16048. }
  16049. }
  16050. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  16051. return result;
  16052. }
  16053. // pick random face weighted by face area
  16054. var r, index,
  16055. result = [];
  16056. var stats = {};
  16057. for ( i = 0; i < n; i ++ ) {
  16058. r = THREE.GeometryUtils.random() * totalArea;
  16059. index = binarySearchIndices( r );
  16060. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  16061. if ( ! stats[ index ] ) {
  16062. stats[ index ] = 1;
  16063. } else {
  16064. stats[ index ] += 1;
  16065. }
  16066. }
  16067. return result;
  16068. },
  16069. // Get triangle area (half of parallelogram)
  16070. // http://mathworld.wolfram.com/TriangleArea.html
  16071. triangleArea: function ( vectorA, vectorB, vectorC ) {
  16072. var tmp1 = THREE.GeometryUtils.__v1,
  16073. tmp2 = THREE.GeometryUtils.__v2;
  16074. tmp1.subVectors( vectorB, vectorA );
  16075. tmp2.subVectors( vectorC, vectorA );
  16076. tmp1.cross( tmp2 );
  16077. return 0.5 * tmp1.length();
  16078. },
  16079. // Center geometry so that 0,0,0 is in center of bounding box
  16080. center: function ( geometry ) {
  16081. geometry.computeBoundingBox();
  16082. var bb = geometry.boundingBox;
  16083. var offset = new THREE.Vector3();
  16084. offset.addVectors( bb.min, bb.max );
  16085. offset.multiplyScalar( -0.5 );
  16086. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  16087. geometry.computeBoundingBox();
  16088. return offset;
  16089. },
  16090. // Normalize UVs to be from <0,1>
  16091. // (for now just the first set of UVs)
  16092. normalizeUVs: function ( geometry ) {
  16093. var uvSet = geometry.faceVertexUvs[ 0 ];
  16094. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  16095. var uvs = uvSet[ i ];
  16096. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  16097. // texture repeat
  16098. if( uvs[ j ].x !== 1.0 ) uvs[ j ].x = uvs[ j ].x - Math.floor( uvs[ j ].x );
  16099. if( uvs[ j ].y !== 1.0 ) uvs[ j ].y = uvs[ j ].y - Math.floor( uvs[ j ].y );
  16100. }
  16101. }
  16102. },
  16103. triangulateQuads: function ( geometry ) {
  16104. var i, il, j, jl;
  16105. var faces = [];
  16106. var faceUvs = [];
  16107. var faceVertexUvs = [];
  16108. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  16109. faceUvs[ i ] = [];
  16110. }
  16111. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  16112. faceVertexUvs[ i ] = [];
  16113. }
  16114. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16115. var face = geometry.faces[ i ];
  16116. if ( face instanceof THREE.Face4 ) {
  16117. var a = face.a;
  16118. var b = face.b;
  16119. var c = face.c;
  16120. var d = face.d;
  16121. var triA = new THREE.Face3();
  16122. var triB = new THREE.Face3();
  16123. triA.color.copy( face.color );
  16124. triB.color.copy( face.color );
  16125. triA.materialIndex = face.materialIndex;
  16126. triB.materialIndex = face.materialIndex;
  16127. triA.a = a;
  16128. triA.b = b;
  16129. triA.c = d;
  16130. triB.a = b;
  16131. triB.b = c;
  16132. triB.c = d;
  16133. if ( face.vertexColors.length === 4 ) {
  16134. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  16135. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  16136. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16137. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  16138. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  16139. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  16140. }
  16141. faces.push( triA, triB );
  16142. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16143. if ( geometry.faceVertexUvs[ j ].length ) {
  16144. var uvs = geometry.faceVertexUvs[ j ][ i ];
  16145. var uvA = uvs[ 0 ];
  16146. var uvB = uvs[ 1 ];
  16147. var uvC = uvs[ 2 ];
  16148. var uvD = uvs[ 3 ];
  16149. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  16150. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  16151. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  16152. }
  16153. }
  16154. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16155. if ( geometry.faceUvs[ j ].length ) {
  16156. var faceUv = geometry.faceUvs[ j ][ i ];
  16157. faceUvs[ j ].push( faceUv, faceUv );
  16158. }
  16159. }
  16160. } else {
  16161. faces.push( face );
  16162. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  16163. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  16164. }
  16165. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  16166. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  16167. }
  16168. }
  16169. }
  16170. geometry.faces = faces;
  16171. geometry.faceUvs = faceUvs;
  16172. geometry.faceVertexUvs = faceVertexUvs;
  16173. geometry.computeCentroids();
  16174. geometry.computeFaceNormals();
  16175. geometry.computeVertexNormals();
  16176. if ( geometry.hasTangents ) geometry.computeTangents();
  16177. },
  16178. setMaterialIndex: function ( geometry, index, startFace, endFace ){
  16179. var faces = geometry.faces;
  16180. var start = startFace || 0;
  16181. var end = endFace || faces.length - 1;
  16182. for ( var i = start; i <= end; i ++ ) {
  16183. faces[i].materialIndex = index;
  16184. }
  16185. }
  16186. };
  16187. THREE.GeometryUtils.random = THREE.Math.random16;
  16188. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  16189. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  16190. /**
  16191. * @author alteredq / http://alteredqualia.com/
  16192. * @author mrdoob / http://mrdoob.com/
  16193. */
  16194. THREE.ImageUtils = {
  16195. crossOrigin: 'anonymous',
  16196. loadTexture: function ( url, mapping, onLoad, onError ) {
  16197. var image = new Image();
  16198. var texture = new THREE.Texture( image, mapping );
  16199. var loader = new THREE.ImageLoader();
  16200. loader.crossOrigin = this.crossOrigin;
  16201. loader.load( url, function ( image ) {
  16202. texture.image = image;
  16203. texture.needsUpdate = true;
  16204. if ( onLoad ) onLoad( texture );
  16205. } );
  16206. texture.sourceFile = url;
  16207. return texture;
  16208. },
  16209. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  16210. var texture = new THREE.CompressedTexture();
  16211. texture.mapping = mapping;
  16212. var request = new XMLHttpRequest();
  16213. request.onload = function () {
  16214. var buffer = request.response;
  16215. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16216. texture.format = dds.format;
  16217. texture.mipmaps = dds.mipmaps;
  16218. texture.image.width = dds.width;
  16219. texture.image.height = dds.height;
  16220. // gl.generateMipmap fails for compressed textures
  16221. // mipmaps must be embedded in the DDS file
  16222. // or texture filters must not use mipmapping
  16223. texture.generateMipmaps = false;
  16224. texture.needsUpdate = true;
  16225. if ( onLoad ) onLoad( texture );
  16226. }
  16227. request.onerror = onError;
  16228. request.open( 'GET', url, true );
  16229. request.responseType = "arraybuffer";
  16230. request.send( null );
  16231. return texture;
  16232. },
  16233. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  16234. var images = [];
  16235. images.loadCount = 0;
  16236. var texture = new THREE.Texture();
  16237. texture.image = images;
  16238. if ( mapping !== undefined ) texture.mapping = mapping;
  16239. // no flipping needed for cube textures
  16240. texture.flipY = false;
  16241. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16242. var cubeImage = new Image();
  16243. images[ i ] = cubeImage;
  16244. cubeImage.onload = function () {
  16245. images.loadCount += 1;
  16246. if ( images.loadCount === 6 ) {
  16247. texture.needsUpdate = true;
  16248. if ( onLoad ) onLoad( texture );
  16249. }
  16250. };
  16251. cubeImage.onerror = onError;
  16252. cubeImage.crossOrigin = this.crossOrigin;
  16253. cubeImage.src = array[ i ];
  16254. }
  16255. return texture;
  16256. },
  16257. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  16258. var images = [];
  16259. images.loadCount = 0;
  16260. var texture = new THREE.CompressedTexture();
  16261. texture.image = images;
  16262. if ( mapping !== undefined ) texture.mapping = mapping;
  16263. // no flipping for cube textures
  16264. // (also flipping doesn't work for compressed textures )
  16265. texture.flipY = false;
  16266. // can't generate mipmaps for compressed textures
  16267. // mips must be embedded in DDS files
  16268. texture.generateMipmaps = false;
  16269. var generateCubeFaceCallback = function ( rq, img ) {
  16270. return function () {
  16271. var buffer = rq.response;
  16272. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16273. img.format = dds.format;
  16274. img.mipmaps = dds.mipmaps;
  16275. img.width = dds.width;
  16276. img.height = dds.height;
  16277. images.loadCount += 1;
  16278. if ( images.loadCount === 6 ) {
  16279. texture.format = dds.format;
  16280. texture.needsUpdate = true;
  16281. if ( onLoad ) onLoad( texture );
  16282. }
  16283. }
  16284. }
  16285. // compressed cubemap textures as 6 separate DDS files
  16286. if ( array instanceof Array ) {
  16287. for ( var i = 0, il = array.length; i < il; ++ i ) {
  16288. var cubeImage = {};
  16289. images[ i ] = cubeImage;
  16290. var request = new XMLHttpRequest();
  16291. request.onload = generateCubeFaceCallback( request, cubeImage );
  16292. request.onerror = onError;
  16293. var url = array[ i ];
  16294. request.open( 'GET', url, true );
  16295. request.responseType = "arraybuffer";
  16296. request.send( null );
  16297. }
  16298. // compressed cubemap texture stored in a single DDS file
  16299. } else {
  16300. var url = array;
  16301. var request = new XMLHttpRequest();
  16302. request.onload = function( ) {
  16303. var buffer = request.response;
  16304. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  16305. if ( dds.isCubemap ) {
  16306. var faces = dds.mipmaps.length / dds.mipmapCount;
  16307. for ( var f = 0; f < faces; f ++ ) {
  16308. images[ f ] = { mipmaps : [] };
  16309. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16310. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  16311. images[ f ].format = dds.format;
  16312. images[ f ].width = dds.width;
  16313. images[ f ].height = dds.height;
  16314. }
  16315. }
  16316. texture.format = dds.format;
  16317. texture.needsUpdate = true;
  16318. if ( onLoad ) onLoad( texture );
  16319. }
  16320. }
  16321. request.onerror = onError;
  16322. request.open( 'GET', url, true );
  16323. request.responseType = "arraybuffer";
  16324. request.send( null );
  16325. }
  16326. return texture;
  16327. },
  16328. parseDDS: function ( buffer, loadMipmaps ) {
  16329. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  16330. // Adapted from @toji's DDS utils
  16331. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  16332. // All values and structures referenced from:
  16333. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  16334. var DDS_MAGIC = 0x20534444;
  16335. var DDSD_CAPS = 0x1,
  16336. DDSD_HEIGHT = 0x2,
  16337. DDSD_WIDTH = 0x4,
  16338. DDSD_PITCH = 0x8,
  16339. DDSD_PIXELFORMAT = 0x1000,
  16340. DDSD_MIPMAPCOUNT = 0x20000,
  16341. DDSD_LINEARSIZE = 0x80000,
  16342. DDSD_DEPTH = 0x800000;
  16343. var DDSCAPS_COMPLEX = 0x8,
  16344. DDSCAPS_MIPMAP = 0x400000,
  16345. DDSCAPS_TEXTURE = 0x1000;
  16346. var DDSCAPS2_CUBEMAP = 0x200,
  16347. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  16348. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  16349. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  16350. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  16351. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  16352. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  16353. DDSCAPS2_VOLUME = 0x200000;
  16354. var DDPF_ALPHAPIXELS = 0x1,
  16355. DDPF_ALPHA = 0x2,
  16356. DDPF_FOURCC = 0x4,
  16357. DDPF_RGB = 0x40,
  16358. DDPF_YUV = 0x200,
  16359. DDPF_LUMINANCE = 0x20000;
  16360. function fourCCToInt32( value ) {
  16361. return value.charCodeAt(0) +
  16362. (value.charCodeAt(1) << 8) +
  16363. (value.charCodeAt(2) << 16) +
  16364. (value.charCodeAt(3) << 24);
  16365. }
  16366. function int32ToFourCC( value ) {
  16367. return String.fromCharCode(
  16368. value & 0xff,
  16369. (value >> 8) & 0xff,
  16370. (value >> 16) & 0xff,
  16371. (value >> 24) & 0xff
  16372. );
  16373. }
  16374. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  16375. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  16376. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  16377. var headerLengthInt = 31; // The header length in 32 bit ints
  16378. // Offsets into the header array
  16379. var off_magic = 0;
  16380. var off_size = 1;
  16381. var off_flags = 2;
  16382. var off_height = 3;
  16383. var off_width = 4;
  16384. var off_mipmapCount = 7;
  16385. var off_pfFlags = 20;
  16386. var off_pfFourCC = 21;
  16387. var off_caps = 27;
  16388. var off_caps2 = 28;
  16389. var off_caps3 = 29;
  16390. var off_caps4 = 30;
  16391. // Parse header
  16392. var header = new Int32Array( buffer, 0, headerLengthInt );
  16393. if ( header[ off_magic ] !== DDS_MAGIC ) {
  16394. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  16395. return dds;
  16396. }
  16397. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  16398. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  16399. return dds;
  16400. }
  16401. var blockBytes;
  16402. var fourCC = header[ off_pfFourCC ];
  16403. switch ( fourCC ) {
  16404. case FOURCC_DXT1:
  16405. blockBytes = 8;
  16406. dds.format = THREE.RGB_S3TC_DXT1_Format;
  16407. break;
  16408. case FOURCC_DXT3:
  16409. blockBytes = 16;
  16410. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  16411. break;
  16412. case FOURCC_DXT5:
  16413. blockBytes = 16;
  16414. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  16415. break;
  16416. default:
  16417. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  16418. return dds;
  16419. }
  16420. dds.mipmapCount = 1;
  16421. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  16422. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  16423. }
  16424. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  16425. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  16426. dds.width = header[ off_width ];
  16427. dds.height = header[ off_height ];
  16428. var dataOffset = header[ off_size ] + 4;
  16429. // Extract mipmaps buffers
  16430. var width = dds.width;
  16431. var height = dds.height;
  16432. var faces = dds.isCubemap ? 6 : 1;
  16433. for ( var face = 0; face < faces; face ++ ) {
  16434. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  16435. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  16436. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  16437. var mipmap = { "data": byteArray, "width": width, "height": height };
  16438. dds.mipmaps.push( mipmap );
  16439. dataOffset += dataLength;
  16440. width = Math.max( width * 0.5, 1 );
  16441. height = Math.max( height * 0.5, 1 );
  16442. }
  16443. width = dds.width;
  16444. height = dds.height;
  16445. }
  16446. return dds;
  16447. },
  16448. getNormalMap: function ( image, depth ) {
  16449. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  16450. var cross = function ( a, b ) {
  16451. 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 ] ];
  16452. }
  16453. var subtract = function ( a, b ) {
  16454. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  16455. }
  16456. var normalize = function ( a ) {
  16457. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  16458. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  16459. }
  16460. depth = depth | 1;
  16461. var width = image.width;
  16462. var height = image.height;
  16463. var canvas = document.createElement( 'canvas' );
  16464. canvas.width = width;
  16465. canvas.height = height;
  16466. var context = canvas.getContext( '2d' );
  16467. context.drawImage( image, 0, 0 );
  16468. var data = context.getImageData( 0, 0, width, height ).data;
  16469. var imageData = context.createImageData( width, height );
  16470. var output = imageData.data;
  16471. for ( var x = 0; x < width; x ++ ) {
  16472. for ( var y = 0; y < height; y ++ ) {
  16473. var ly = y - 1 < 0 ? 0 : y - 1;
  16474. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  16475. var lx = x - 1 < 0 ? 0 : x - 1;
  16476. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  16477. var points = [];
  16478. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  16479. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  16480. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  16481. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  16482. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  16483. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  16484. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  16485. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  16486. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  16487. var normals = [];
  16488. var num_points = points.length;
  16489. for ( var i = 0; i < num_points; i ++ ) {
  16490. var v1 = points[ i ];
  16491. var v2 = points[ ( i + 1 ) % num_points ];
  16492. v1 = subtract( v1, origin );
  16493. v2 = subtract( v2, origin );
  16494. normals.push( normalize( cross( v1, v2 ) ) );
  16495. }
  16496. var normal = [ 0, 0, 0 ];
  16497. for ( var i = 0; i < normals.length; i ++ ) {
  16498. normal[ 0 ] += normals[ i ][ 0 ];
  16499. normal[ 1 ] += normals[ i ][ 1 ];
  16500. normal[ 2 ] += normals[ i ][ 2 ];
  16501. }
  16502. normal[ 0 ] /= normals.length;
  16503. normal[ 1 ] /= normals.length;
  16504. normal[ 2 ] /= normals.length;
  16505. var idx = ( y * width + x ) * 4;
  16506. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16507. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  16508. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  16509. output[ idx + 3 ] = 255;
  16510. }
  16511. }
  16512. context.putImageData( imageData, 0, 0 );
  16513. return canvas;
  16514. },
  16515. generateDataTexture: function ( width, height, color ) {
  16516. var size = width * height;
  16517. var data = new Uint8Array( 3 * size );
  16518. var r = Math.floor( color.r * 255 );
  16519. var g = Math.floor( color.g * 255 );
  16520. var b = Math.floor( color.b * 255 );
  16521. for ( var i = 0; i < size; i ++ ) {
  16522. data[ i * 3 ] = r;
  16523. data[ i * 3 + 1 ] = g;
  16524. data[ i * 3 + 2 ] = b;
  16525. }
  16526. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  16527. texture.needsUpdate = true;
  16528. return texture;
  16529. }
  16530. };
  16531. /**
  16532. * @author alteredq / http://alteredqualia.com/
  16533. */
  16534. THREE.SceneUtils = {
  16535. createMultiMaterialObject: function ( geometry, materials ) {
  16536. var group = new THREE.Object3D();
  16537. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  16538. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  16539. }
  16540. return group;
  16541. },
  16542. detach : function ( child, parent, scene ) {
  16543. child.applyMatrix( parent.matrixWorld );
  16544. parent.remove( child );
  16545. scene.add( child );
  16546. },
  16547. attach: function ( child, scene, parent ) {
  16548. var matrixWorldInverse = new THREE.Matrix4();
  16549. matrixWorldInverse.getInverse( parent.matrixWorld );
  16550. child.applyMatrix( matrixWorldInverse );
  16551. scene.remove( child );
  16552. parent.add( child );
  16553. }
  16554. };
  16555. /**
  16556. * @author zz85 / http://www.lab4games.net/zz85/blog
  16557. * @author alteredq / http://alteredqualia.com/
  16558. *
  16559. * For Text operations in three.js (See TextGeometry)
  16560. *
  16561. * It uses techniques used in:
  16562. *
  16563. * typeface.js and canvastext
  16564. * For converting fonts and rendering with javascript
  16565. * http://typeface.neocracy.org
  16566. *
  16567. * Triangulation ported from AS3
  16568. * Simple Polygon Triangulation
  16569. * http://actionsnippet.com/?p=1462
  16570. *
  16571. * A Method to triangulate shapes with holes
  16572. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  16573. *
  16574. */
  16575. THREE.FontUtils = {
  16576. faces : {},
  16577. // Just for now. face[weight][style]
  16578. face : "helvetiker",
  16579. weight: "normal",
  16580. style : "normal",
  16581. size : 150,
  16582. divisions : 10,
  16583. getFace : function() {
  16584. return this.faces[ this.face ][ this.weight ][ this.style ];
  16585. },
  16586. loadFace : function( data ) {
  16587. var family = data.familyName.toLowerCase();
  16588. var ThreeFont = this;
  16589. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  16590. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  16591. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16592. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  16593. return data;
  16594. },
  16595. drawText : function( text ) {
  16596. var characterPts = [], allPts = [];
  16597. // RenderText
  16598. var i, p,
  16599. face = this.getFace(),
  16600. scale = this.size / face.resolution,
  16601. offset = 0,
  16602. chars = String( text ).split( '' ),
  16603. length = chars.length;
  16604. var fontPaths = [];
  16605. for ( i = 0; i < length; i ++ ) {
  16606. var path = new THREE.Path();
  16607. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  16608. offset += ret.offset;
  16609. fontPaths.push( ret.path );
  16610. }
  16611. // get the width
  16612. var width = offset / 2;
  16613. //
  16614. // for ( p = 0; p < allPts.length; p++ ) {
  16615. //
  16616. // allPts[ p ].x -= width;
  16617. //
  16618. // }
  16619. //var extract = this.extractPoints( allPts, characterPts );
  16620. //extract.contour = allPts;
  16621. //extract.paths = fontPaths;
  16622. //extract.offset = width;
  16623. return { paths : fontPaths, offset : width };
  16624. },
  16625. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16626. var pts = [];
  16627. var i, i2, divisions,
  16628. outline, action, length,
  16629. scaleX, scaleY,
  16630. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16631. laste,
  16632. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16633. if ( !glyph ) return;
  16634. if ( glyph.o ) {
  16635. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16636. length = outline.length;
  16637. scaleX = scale;
  16638. scaleY = scale;
  16639. for ( i = 0; i < length; ) {
  16640. action = outline[ i ++ ];
  16641. //console.log( action );
  16642. switch( action ) {
  16643. case 'm':
  16644. // Move To
  16645. x = outline[ i++ ] * scaleX + offset;
  16646. y = outline[ i++ ] * scaleY;
  16647. path.moveTo( x, y );
  16648. break;
  16649. case 'l':
  16650. // Line To
  16651. x = outline[ i++ ] * scaleX + offset;
  16652. y = outline[ i++ ] * scaleY;
  16653. path.lineTo(x,y);
  16654. break;
  16655. case 'q':
  16656. // QuadraticCurveTo
  16657. cpx = outline[ i++ ] * scaleX + offset;
  16658. cpy = outline[ i++ ] * scaleY;
  16659. cpx1 = outline[ i++ ] * scaleX + offset;
  16660. cpy1 = outline[ i++ ] * scaleY;
  16661. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16662. laste = pts[ pts.length - 1 ];
  16663. if ( laste ) {
  16664. cpx0 = laste.x;
  16665. cpy0 = laste.y;
  16666. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16667. var t = i2 / divisions;
  16668. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16669. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16670. }
  16671. }
  16672. break;
  16673. case 'b':
  16674. // Cubic Bezier Curve
  16675. cpx = outline[ i++ ] * scaleX + offset;
  16676. cpy = outline[ i++ ] * scaleY;
  16677. cpx1 = outline[ i++ ] * scaleX + offset;
  16678. cpy1 = outline[ i++ ] * -scaleY;
  16679. cpx2 = outline[ i++ ] * scaleX + offset;
  16680. cpy2 = outline[ i++ ] * -scaleY;
  16681. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16682. laste = pts[ pts.length - 1 ];
  16683. if ( laste ) {
  16684. cpx0 = laste.x;
  16685. cpy0 = laste.y;
  16686. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16687. var t = i2 / divisions;
  16688. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16689. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16690. }
  16691. }
  16692. break;
  16693. }
  16694. }
  16695. }
  16696. return { offset: glyph.ha*scale, path:path};
  16697. }
  16698. };
  16699. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16700. // Parameters
  16701. parameters = parameters || {};
  16702. var size = parameters.size !== undefined ? parameters.size : 100;
  16703. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16704. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16705. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16706. var style = parameters.style !== undefined ? parameters.style : "normal";
  16707. THREE.FontUtils.size = size;
  16708. THREE.FontUtils.divisions = curveSegments;
  16709. THREE.FontUtils.face = font;
  16710. THREE.FontUtils.weight = weight;
  16711. THREE.FontUtils.style = style;
  16712. // Get a Font data json object
  16713. var data = THREE.FontUtils.drawText( text );
  16714. var paths = data.paths;
  16715. var shapes = [];
  16716. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16717. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16718. }
  16719. return shapes;
  16720. };
  16721. /**
  16722. * This code is a quick port of code written in C++ which was submitted to
  16723. * flipcode.com by John W. Ratcliff // July 22, 2000
  16724. * See original code and more information here:
  16725. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16726. *
  16727. * ported to actionscript by Zevan Rosser
  16728. * www.actionsnippet.com
  16729. *
  16730. * ported to javascript by Joshua Koo
  16731. * http://www.lab4games.net/zz85/blog
  16732. *
  16733. */
  16734. ( function( namespace ) {
  16735. var EPSILON = 0.0000000001;
  16736. // takes in an contour array and returns
  16737. var process = function( contour, indices ) {
  16738. var n = contour.length;
  16739. if ( n < 3 ) return null;
  16740. var result = [],
  16741. verts = [],
  16742. vertIndices = [];
  16743. /* we want a counter-clockwise polygon in verts */
  16744. var u, v, w;
  16745. if ( area( contour ) > 0.0 ) {
  16746. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16747. } else {
  16748. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16749. }
  16750. var nv = n;
  16751. /* remove nv - 2 vertices, creating 1 triangle every time */
  16752. var count = 2 * nv; /* error detection */
  16753. for( v = nv - 1; nv > 2; ) {
  16754. /* if we loop, it is probably a non-simple polygon */
  16755. if ( ( count-- ) <= 0 ) {
  16756. //** Triangulate: ERROR - probable bad polygon!
  16757. //throw ( "Warning, unable to triangulate polygon!" );
  16758. //return null;
  16759. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16760. console.log( "Warning, unable to triangulate polygon!" );
  16761. if ( indices ) return vertIndices;
  16762. return result;
  16763. }
  16764. /* three consecutive vertices in current polygon, <u,v,w> */
  16765. u = v; if ( nv <= u ) u = 0; /* previous */
  16766. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16767. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16768. if ( snip( contour, u, v, w, nv, verts ) ) {
  16769. var a, b, c, s, t;
  16770. /* true names of the vertices */
  16771. a = verts[ u ];
  16772. b = verts[ v ];
  16773. c = verts[ w ];
  16774. /* output Triangle */
  16775. result.push( [ contour[ a ],
  16776. contour[ b ],
  16777. contour[ c ] ] );
  16778. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16779. /* remove v from the remaining polygon */
  16780. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16781. verts[ s ] = verts[ t ];
  16782. }
  16783. nv--;
  16784. /* reset error detection counter */
  16785. count = 2 * nv;
  16786. }
  16787. }
  16788. if ( indices ) return vertIndices;
  16789. return result;
  16790. };
  16791. // calculate area of the contour polygon
  16792. var area = function ( contour ) {
  16793. var n = contour.length;
  16794. var a = 0.0;
  16795. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16796. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16797. }
  16798. return a * 0.5;
  16799. };
  16800. var snip = function ( contour, u, v, w, n, verts ) {
  16801. var p;
  16802. var ax, ay, bx, by;
  16803. var cx, cy, px, py;
  16804. ax = contour[ verts[ u ] ].x;
  16805. ay = contour[ verts[ u ] ].y;
  16806. bx = contour[ verts[ v ] ].x;
  16807. by = contour[ verts[ v ] ].y;
  16808. cx = contour[ verts[ w ] ].x;
  16809. cy = contour[ verts[ w ] ].y;
  16810. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16811. var aX, aY, bX, bY, cX, cY;
  16812. var apx, apy, bpx, bpy, cpx, cpy;
  16813. var cCROSSap, bCROSScp, aCROSSbp;
  16814. aX = cx - bx; aY = cy - by;
  16815. bX = ax - cx; bY = ay - cy;
  16816. cX = bx - ax; cY = by - ay;
  16817. for ( p = 0; p < n; p++ ) {
  16818. if( (p === u) || (p === v) || (p === w) ) continue;
  16819. px = contour[ verts[ p ] ].x
  16820. py = contour[ verts[ p ] ].y
  16821. apx = px - ax; apy = py - ay;
  16822. bpx = px - bx; bpy = py - by;
  16823. cpx = px - cx; cpy = py - cy;
  16824. // see if p is inside triangle abc
  16825. aCROSSbp = aX*bpy - aY*bpx;
  16826. cCROSSap = cX*apy - cY*apx;
  16827. bCROSScp = bX*cpy - bY*cpx;
  16828. if ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) ) return false;
  16829. }
  16830. return true;
  16831. };
  16832. namespace.Triangulate = process;
  16833. namespace.Triangulate.area = area;
  16834. return namespace;
  16835. })(THREE.FontUtils);
  16836. // To use the typeface.js face files, hook up the API
  16837. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  16838. THREE.typeface_js = self._typeface_js;
  16839. /**
  16840. * @author zz85 / http://www.lab4games.net/zz85/blog
  16841. * Extensible curve object
  16842. *
  16843. * Some common of Curve methods
  16844. * .getPoint(t), getTangent(t)
  16845. * .getPointAt(u), getTagentAt(u)
  16846. * .getPoints(), .getSpacedPoints()
  16847. * .getLength()
  16848. * .updateArcLengths()
  16849. *
  16850. * This following classes subclasses THREE.Curve:
  16851. *
  16852. * -- 2d classes --
  16853. * THREE.LineCurve
  16854. * THREE.QuadraticBezierCurve
  16855. * THREE.CubicBezierCurve
  16856. * THREE.SplineCurve
  16857. * THREE.ArcCurve
  16858. * THREE.EllipseCurve
  16859. *
  16860. * -- 3d classes --
  16861. * THREE.LineCurve3
  16862. * THREE.QuadraticBezierCurve3
  16863. * THREE.CubicBezierCurve3
  16864. * THREE.SplineCurve3
  16865. * THREE.ClosedSplineCurve3
  16866. *
  16867. * A series of curves can be represented as a THREE.CurvePath
  16868. *
  16869. **/
  16870. /**************************************************************
  16871. * Abstract Curve base class
  16872. **************************************************************/
  16873. THREE.Curve = function () {
  16874. };
  16875. // Virtual base class method to overwrite and implement in subclasses
  16876. // - t [0 .. 1]
  16877. THREE.Curve.prototype.getPoint = function ( t ) {
  16878. console.log( "Warning, getPoint() not implemented!" );
  16879. return null;
  16880. };
  16881. // Get point at relative position in curve according to arc length
  16882. // - u [0 .. 1]
  16883. THREE.Curve.prototype.getPointAt = function ( u ) {
  16884. var t = this.getUtoTmapping( u );
  16885. return this.getPoint( t );
  16886. };
  16887. // Get sequence of points using getPoint( t )
  16888. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16889. if ( !divisions ) divisions = 5;
  16890. var d, pts = [];
  16891. for ( d = 0; d <= divisions; d ++ ) {
  16892. pts.push( this.getPoint( d / divisions ) );
  16893. }
  16894. return pts;
  16895. };
  16896. // Get sequence of points using getPointAt( u )
  16897. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16898. if ( !divisions ) divisions = 5;
  16899. var d, pts = [];
  16900. for ( d = 0; d <= divisions; d ++ ) {
  16901. pts.push( this.getPointAt( d / divisions ) );
  16902. }
  16903. return pts;
  16904. };
  16905. // Get total curve arc length
  16906. THREE.Curve.prototype.getLength = function () {
  16907. var lengths = this.getLengths();
  16908. return lengths[ lengths.length - 1 ];
  16909. };
  16910. // Get list of cumulative segment lengths
  16911. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16912. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16913. if ( this.cacheArcLengths
  16914. && ( this.cacheArcLengths.length == divisions + 1 )
  16915. && !this.needsUpdate) {
  16916. //console.log( "cached", this.cacheArcLengths );
  16917. return this.cacheArcLengths;
  16918. }
  16919. this.needsUpdate = false;
  16920. var cache = [];
  16921. var current, last = this.getPoint( 0 );
  16922. var p, sum = 0;
  16923. cache.push( 0 );
  16924. for ( p = 1; p <= divisions; p ++ ) {
  16925. current = this.getPoint ( p / divisions );
  16926. sum += current.distanceTo( last );
  16927. cache.push( sum );
  16928. last = current;
  16929. }
  16930. this.cacheArcLengths = cache;
  16931. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16932. };
  16933. THREE.Curve.prototype.updateArcLengths = function() {
  16934. this.needsUpdate = true;
  16935. this.getLengths();
  16936. };
  16937. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16938. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16939. var arcLengths = this.getLengths();
  16940. var i = 0, il = arcLengths.length;
  16941. var targetArcLength; // The targeted u distance value to get
  16942. if ( distance ) {
  16943. targetArcLength = distance;
  16944. } else {
  16945. targetArcLength = u * arcLengths[ il - 1 ];
  16946. }
  16947. //var time = Date.now();
  16948. // binary search for the index with largest value smaller than target u distance
  16949. var low = 0, high = il - 1, comparison;
  16950. while ( low <= high ) {
  16951. 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
  16952. comparison = arcLengths[ i ] - targetArcLength;
  16953. if ( comparison < 0 ) {
  16954. low = i + 1;
  16955. continue;
  16956. } else if ( comparison > 0 ) {
  16957. high = i - 1;
  16958. continue;
  16959. } else {
  16960. high = i;
  16961. break;
  16962. // DONE
  16963. }
  16964. }
  16965. i = high;
  16966. //console.log('b' , i, low, high, Date.now()- time);
  16967. if ( arcLengths[ i ] == targetArcLength ) {
  16968. var t = i / ( il - 1 );
  16969. return t;
  16970. }
  16971. // we could get finer grain at lengths, or use simple interpolatation between two points
  16972. var lengthBefore = arcLengths[ i ];
  16973. var lengthAfter = arcLengths[ i + 1 ];
  16974. var segmentLength = lengthAfter - lengthBefore;
  16975. // determine where we are between the 'before' and 'after' points
  16976. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16977. // add that fractional amount to t
  16978. var t = ( i + segmentFraction ) / ( il -1 );
  16979. return t;
  16980. };
  16981. // Returns a unit vector tangent at t
  16982. // In case any sub curve does not implement its tangent derivation,
  16983. // 2 points a small delta apart will be used to find its gradient
  16984. // which seems to give a reasonable approximation
  16985. THREE.Curve.prototype.getTangent = function( t ) {
  16986. var delta = 0.0001;
  16987. var t1 = t - delta;
  16988. var t2 = t + delta;
  16989. // Capping in case of danger
  16990. if ( t1 < 0 ) t1 = 0;
  16991. if ( t2 > 1 ) t2 = 1;
  16992. var pt1 = this.getPoint( t1 );
  16993. var pt2 = this.getPoint( t2 );
  16994. var vec = pt2.clone().sub(pt1);
  16995. return vec.normalize();
  16996. };
  16997. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16998. var t = this.getUtoTmapping( u );
  16999. return this.getTangent( t );
  17000. };
  17001. /**************************************************************
  17002. * Utils
  17003. **************************************************************/
  17004. THREE.Curve.Utils = {
  17005. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  17006. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  17007. },
  17008. // Puay Bing, thanks for helping with this derivative!
  17009. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  17010. return -3 * p0 * (1 - t) * (1 - t) +
  17011. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  17012. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  17013. 3 * t * t * p3;
  17014. },
  17015. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  17016. // To check if my formulas are correct
  17017. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  17018. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  17019. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  17020. var h11 = 3 * t * t - 2 * t; // t3 − t2
  17021. return h00 + h10 + h01 + h11;
  17022. },
  17023. // Catmull-Rom
  17024. interpolate: function( p0, p1, p2, p3, t ) {
  17025. var v0 = ( p2 - p0 ) * 0.5;
  17026. var v1 = ( p3 - p1 ) * 0.5;
  17027. var t2 = t * t;
  17028. var t3 = t * t2;
  17029. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17030. }
  17031. };
  17032. // TODO: Transformation for Curves?
  17033. /**************************************************************
  17034. * 3D Curves
  17035. **************************************************************/
  17036. // A Factory method for creating new curve subclasses
  17037. THREE.Curve.create = function ( constructor, getPointFunc ) {
  17038. constructor.prototype = Object.create( THREE.Curve.prototype );
  17039. constructor.prototype.getPoint = getPointFunc;
  17040. return constructor;
  17041. };
  17042. /**
  17043. * @author zz85 / http://www.lab4games.net/zz85/blog
  17044. *
  17045. **/
  17046. /**************************************************************
  17047. * Curved Path - a curve path is simply a array of connected
  17048. * curves, but retains the api of a curve
  17049. **************************************************************/
  17050. THREE.CurvePath = function () {
  17051. this.curves = [];
  17052. this.bends = [];
  17053. this.autoClose = false; // Automatically closes the path
  17054. };
  17055. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  17056. THREE.CurvePath.prototype.add = function ( curve ) {
  17057. this.curves.push( curve );
  17058. };
  17059. THREE.CurvePath.prototype.checkConnection = function() {
  17060. // TODO
  17061. // If the ending of curve is not connected to the starting
  17062. // or the next curve, then, this is not a real path
  17063. };
  17064. THREE.CurvePath.prototype.closePath = function() {
  17065. // TODO Test
  17066. // and verify for vector3 (needs to implement equals)
  17067. // Add a line curve if start and end of lines are not connected
  17068. var startPoint = this.curves[0].getPoint(0);
  17069. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  17070. if (!startPoint.equals(endPoint)) {
  17071. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  17072. }
  17073. };
  17074. // To get accurate point with reference to
  17075. // entire path distance at time t,
  17076. // following has to be done:
  17077. // 1. Length of each sub path have to be known
  17078. // 2. Locate and identify type of curve
  17079. // 3. Get t for the curve
  17080. // 4. Return curve.getPointAt(t')
  17081. THREE.CurvePath.prototype.getPoint = function( t ) {
  17082. var d = t * this.getLength();
  17083. var curveLengths = this.getCurveLengths();
  17084. var i = 0, diff, curve;
  17085. // To think about boundaries points.
  17086. while ( i < curveLengths.length ) {
  17087. if ( curveLengths[ i ] >= d ) {
  17088. diff = curveLengths[ i ] - d;
  17089. curve = this.curves[ i ];
  17090. var u = 1 - diff / curve.getLength();
  17091. return curve.getPointAt( u );
  17092. break;
  17093. }
  17094. i ++;
  17095. }
  17096. return null;
  17097. // loop where sum != 0, sum > d , sum+1 <d
  17098. };
  17099. /*
  17100. THREE.CurvePath.prototype.getTangent = function( t ) {
  17101. };*/
  17102. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  17103. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  17104. // getPoint() depends on getLength
  17105. THREE.CurvePath.prototype.getLength = function() {
  17106. var lens = this.getCurveLengths();
  17107. return lens[ lens.length - 1 ];
  17108. };
  17109. // Compute lengths and cache them
  17110. // We cannot overwrite getLengths() because UtoT mapping uses it.
  17111. THREE.CurvePath.prototype.getCurveLengths = function() {
  17112. // We use cache values if curves and cache array are same length
  17113. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  17114. return this.cacheLengths;
  17115. };
  17116. // Get length of subsurve
  17117. // Push sums into cached array
  17118. var lengths = [], sums = 0;
  17119. var i, il = this.curves.length;
  17120. for ( i = 0; i < il; i ++ ) {
  17121. sums += this.curves[ i ].getLength();
  17122. lengths.push( sums );
  17123. }
  17124. this.cacheLengths = lengths;
  17125. return lengths;
  17126. };
  17127. // Returns min and max coordinates, as well as centroid
  17128. THREE.CurvePath.prototype.getBoundingBox = function () {
  17129. var points = this.getPoints();
  17130. var maxX, maxY, maxZ;
  17131. var minX, minY, minZ;
  17132. maxX = maxY = Number.NEGATIVE_INFINITY;
  17133. minX = minY = Number.POSITIVE_INFINITY;
  17134. var p, i, il, sum;
  17135. var v3 = points[0] instanceof THREE.Vector3;
  17136. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  17137. for ( i = 0, il = points.length; i < il; i ++ ) {
  17138. p = points[ i ];
  17139. if ( p.x > maxX ) maxX = p.x;
  17140. else if ( p.x < minX ) minX = p.x;
  17141. if ( p.y > maxY ) maxY = p.y;
  17142. else if ( p.y < minY ) minY = p.y;
  17143. if ( v3 ) {
  17144. if ( p.z > maxZ ) maxZ = p.z;
  17145. else if ( p.z < minZ ) minZ = p.z;
  17146. }
  17147. sum.add( p );
  17148. }
  17149. var ret = {
  17150. minX: minX,
  17151. minY: minY,
  17152. maxX: maxX,
  17153. maxY: maxY,
  17154. centroid: sum.divideScalar( il )
  17155. };
  17156. if ( v3 ) {
  17157. ret.maxZ = maxZ;
  17158. ret.minZ = minZ;
  17159. }
  17160. return ret;
  17161. };
  17162. /**************************************************************
  17163. * Create Geometries Helpers
  17164. **************************************************************/
  17165. /// Generate geometry from path points (for Line or ParticleSystem objects)
  17166. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  17167. var pts = this.getPoints( divisions, true );
  17168. return this.createGeometry( pts );
  17169. };
  17170. // Generate geometry from equidistance sampling along the path
  17171. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  17172. var pts = this.getSpacedPoints( divisions, true );
  17173. return this.createGeometry( pts );
  17174. };
  17175. THREE.CurvePath.prototype.createGeometry = function( points ) {
  17176. var geometry = new THREE.Geometry();
  17177. for ( var i = 0; i < points.length; i ++ ) {
  17178. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  17179. }
  17180. return geometry;
  17181. };
  17182. /**************************************************************
  17183. * Bend / Wrap Helper Methods
  17184. **************************************************************/
  17185. // Wrap path / Bend modifiers?
  17186. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  17187. this.bends.push( bendpath );
  17188. };
  17189. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  17190. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  17191. var i, il;
  17192. if ( !bends ) {
  17193. bends = this.bends;
  17194. }
  17195. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17196. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17197. }
  17198. return oldPts;
  17199. };
  17200. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  17201. var oldPts = this.getSpacedPoints( segments );
  17202. var i, il;
  17203. if ( !bends ) {
  17204. bends = this.bends;
  17205. }
  17206. for ( i = 0, il = bends.length; i < il; i ++ ) {
  17207. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  17208. }
  17209. return oldPts;
  17210. };
  17211. // This returns getPoints() bend/wrapped around the contour of a path.
  17212. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  17213. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  17214. var bounds = this.getBoundingBox();
  17215. var i, il, p, oldX, oldY, xNorm;
  17216. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  17217. p = oldPts[ i ];
  17218. oldX = p.x;
  17219. oldY = p.y;
  17220. xNorm = oldX / bounds.maxX;
  17221. // If using actual distance, for length > path, requires line extrusions
  17222. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  17223. xNorm = path.getUtoTmapping( xNorm, oldX );
  17224. // check for out of bounds?
  17225. var pathPt = path.getPoint( xNorm );
  17226. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  17227. p.x = pathPt.x + normal.x;
  17228. p.y = pathPt.y + normal.y;
  17229. }
  17230. return oldPts;
  17231. };
  17232. /**
  17233. * @author alteredq / http://alteredqualia.com/
  17234. */
  17235. THREE.Gyroscope = function () {
  17236. THREE.Object3D.call( this );
  17237. };
  17238. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  17239. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  17240. this.matrixAutoUpdate && this.updateMatrix();
  17241. // update matrixWorld
  17242. if ( this.matrixWorldNeedsUpdate || force ) {
  17243. if ( this.parent ) {
  17244. this.matrixWorld.multiplyMatrices( this.parent.matrixWorld, this.matrix );
  17245. this.matrixWorld.decompose( this.translationWorld, this.quaternionWorld, this.scaleWorld );
  17246. this.matrix.decompose( this.translationObject, this.quaternionObject, this.scaleObject );
  17247. this.matrixWorld.compose( this.translationWorld, this.quaternionObject, this.scaleWorld );
  17248. } else {
  17249. this.matrixWorld.copy( this.matrix );
  17250. }
  17251. this.matrixWorldNeedsUpdate = false;
  17252. force = true;
  17253. }
  17254. // update children
  17255. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  17256. this.children[ i ].updateMatrixWorld( force );
  17257. }
  17258. };
  17259. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  17260. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  17261. THREE.Gyroscope.prototype.quaternionWorld = new THREE.Quaternion();
  17262. THREE.Gyroscope.prototype.quaternionObject = new THREE.Quaternion();
  17263. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  17264. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  17265. /**
  17266. * @author zz85 / http://www.lab4games.net/zz85/blog
  17267. * Creates free form 2d path using series of points, lines or curves.
  17268. *
  17269. **/
  17270. THREE.Path = function ( points ) {
  17271. THREE.CurvePath.call(this);
  17272. this.actions = [];
  17273. if ( points ) {
  17274. this.fromPoints( points );
  17275. }
  17276. };
  17277. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  17278. THREE.PathActions = {
  17279. MOVE_TO: 'moveTo',
  17280. LINE_TO: 'lineTo',
  17281. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  17282. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  17283. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  17284. ARC: 'arc', // Circle
  17285. ELLIPSE: 'ellipse'
  17286. };
  17287. // TODO Clean up PATH API
  17288. // Create path using straight lines to connect all points
  17289. // - vectors: array of Vector2
  17290. THREE.Path.prototype.fromPoints = function ( vectors ) {
  17291. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  17292. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  17293. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  17294. };
  17295. };
  17296. // startPath() endPath()?
  17297. THREE.Path.prototype.moveTo = function ( x, y ) {
  17298. var args = Array.prototype.slice.call( arguments );
  17299. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  17300. };
  17301. THREE.Path.prototype.lineTo = function ( x, y ) {
  17302. var args = Array.prototype.slice.call( arguments );
  17303. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17304. var x0 = lastargs[ lastargs.length - 2 ];
  17305. var y0 = lastargs[ lastargs.length - 1 ];
  17306. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  17307. this.curves.push( curve );
  17308. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  17309. };
  17310. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  17311. var args = Array.prototype.slice.call( arguments );
  17312. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17313. var x0 = lastargs[ lastargs.length - 2 ];
  17314. var y0 = lastargs[ lastargs.length - 1 ];
  17315. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  17316. new THREE.Vector2( aCPx, aCPy ),
  17317. new THREE.Vector2( aX, aY ) );
  17318. this.curves.push( curve );
  17319. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  17320. };
  17321. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  17322. aCP2x, aCP2y,
  17323. aX, aY ) {
  17324. var args = Array.prototype.slice.call( arguments );
  17325. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17326. var x0 = lastargs[ lastargs.length - 2 ];
  17327. var y0 = lastargs[ lastargs.length - 1 ];
  17328. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  17329. new THREE.Vector2( aCP1x, aCP1y ),
  17330. new THREE.Vector2( aCP2x, aCP2y ),
  17331. new THREE.Vector2( aX, aY ) );
  17332. this.curves.push( curve );
  17333. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  17334. };
  17335. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  17336. var args = Array.prototype.slice.call( arguments );
  17337. var lastargs = this.actions[ this.actions.length - 1 ].args;
  17338. var x0 = lastargs[ lastargs.length - 2 ];
  17339. var y0 = lastargs[ lastargs.length - 1 ];
  17340. //---
  17341. var npts = [ new THREE.Vector2( x0, y0 ) ];
  17342. Array.prototype.push.apply( npts, pts );
  17343. var curve = new THREE.SplineCurve( npts );
  17344. this.curves.push( curve );
  17345. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17346. };
  17347. // FUTURE: Change the API or follow canvas API?
  17348. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17349. aStartAngle, aEndAngle, aClockwise ) {
  17350. var lastargs = this.actions[ this.actions.length - 1].args;
  17351. var x0 = lastargs[ lastargs.length - 2 ];
  17352. var y0 = lastargs[ lastargs.length - 1 ];
  17353. this.absarc(aX + x0, aY + y0, aRadius,
  17354. aStartAngle, aEndAngle, aClockwise );
  17355. };
  17356. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17357. aStartAngle, aEndAngle, aClockwise ) {
  17358. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17359. };
  17360. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17361. aStartAngle, aEndAngle, aClockwise ) {
  17362. var lastargs = this.actions[ this.actions.length - 1].args;
  17363. var x0 = lastargs[ lastargs.length - 2 ];
  17364. var y0 = lastargs[ lastargs.length - 1 ];
  17365. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17366. aStartAngle, aEndAngle, aClockwise );
  17367. };
  17368. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17369. aStartAngle, aEndAngle, aClockwise ) {
  17370. var args = Array.prototype.slice.call( arguments );
  17371. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17372. aStartAngle, aEndAngle, aClockwise );
  17373. this.curves.push( curve );
  17374. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17375. args.push(lastPoint.x);
  17376. args.push(lastPoint.y);
  17377. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17378. };
  17379. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17380. if ( ! divisions ) divisions = 40;
  17381. var points = [];
  17382. for ( var i = 0; i < divisions; i ++ ) {
  17383. points.push( this.getPoint( i / divisions ) );
  17384. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17385. }
  17386. // if ( closedPath ) {
  17387. //
  17388. // points.push( points[ 0 ] );
  17389. //
  17390. // }
  17391. return points;
  17392. };
  17393. /* Return an array of vectors based on contour of the path */
  17394. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17395. if (this.useSpacedPoints) {
  17396. console.log('tata');
  17397. return this.getSpacedPoints( divisions, closedPath );
  17398. }
  17399. divisions = divisions || 12;
  17400. var points = [];
  17401. var i, il, item, action, args;
  17402. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17403. laste, j,
  17404. t, tx, ty;
  17405. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17406. item = this.actions[ i ];
  17407. action = item.action;
  17408. args = item.args;
  17409. switch( action ) {
  17410. case THREE.PathActions.MOVE_TO:
  17411. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17412. break;
  17413. case THREE.PathActions.LINE_TO:
  17414. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17415. break;
  17416. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17417. cpx = args[ 2 ];
  17418. cpy = args[ 3 ];
  17419. cpx1 = args[ 0 ];
  17420. cpy1 = args[ 1 ];
  17421. if ( points.length > 0 ) {
  17422. laste = points[ points.length - 1 ];
  17423. cpx0 = laste.x;
  17424. cpy0 = laste.y;
  17425. } else {
  17426. laste = this.actions[ i - 1 ].args;
  17427. cpx0 = laste[ laste.length - 2 ];
  17428. cpy0 = laste[ laste.length - 1 ];
  17429. }
  17430. for ( j = 1; j <= divisions; j ++ ) {
  17431. t = j / divisions;
  17432. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17433. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17434. points.push( new THREE.Vector2( tx, ty ) );
  17435. }
  17436. break;
  17437. case THREE.PathActions.BEZIER_CURVE_TO:
  17438. cpx = args[ 4 ];
  17439. cpy = args[ 5 ];
  17440. cpx1 = args[ 0 ];
  17441. cpy1 = args[ 1 ];
  17442. cpx2 = args[ 2 ];
  17443. cpy2 = args[ 3 ];
  17444. if ( points.length > 0 ) {
  17445. laste = points[ points.length - 1 ];
  17446. cpx0 = laste.x;
  17447. cpy0 = laste.y;
  17448. } else {
  17449. laste = this.actions[ i - 1 ].args;
  17450. cpx0 = laste[ laste.length - 2 ];
  17451. cpy0 = laste[ laste.length - 1 ];
  17452. }
  17453. for ( j = 1; j <= divisions; j ++ ) {
  17454. t = j / divisions;
  17455. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17456. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17457. points.push( new THREE.Vector2( tx, ty ) );
  17458. }
  17459. break;
  17460. case THREE.PathActions.CSPLINE_THRU:
  17461. laste = this.actions[ i - 1 ].args;
  17462. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17463. var spts = [ last ];
  17464. var n = divisions * args[ 0 ].length;
  17465. spts = spts.concat( args[ 0 ] );
  17466. var spline = new THREE.SplineCurve( spts );
  17467. for ( j = 1; j <= n; j ++ ) {
  17468. points.push( spline.getPointAt( j / n ) ) ;
  17469. }
  17470. break;
  17471. case THREE.PathActions.ARC:
  17472. var aX = args[ 0 ], aY = args[ 1 ],
  17473. aRadius = args[ 2 ],
  17474. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17475. aClockwise = !!args[ 5 ];
  17476. var deltaAngle = aEndAngle - aStartAngle;
  17477. var angle;
  17478. var tdivisions = divisions * 2;
  17479. for ( j = 1; j <= tdivisions; j ++ ) {
  17480. t = j / tdivisions;
  17481. if ( ! aClockwise ) {
  17482. t = 1 - t;
  17483. }
  17484. angle = aStartAngle + t * deltaAngle;
  17485. tx = aX + aRadius * Math.cos( angle );
  17486. ty = aY + aRadius * Math.sin( angle );
  17487. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17488. points.push( new THREE.Vector2( tx, ty ) );
  17489. }
  17490. //console.log(points);
  17491. break;
  17492. case THREE.PathActions.ELLIPSE:
  17493. var aX = args[ 0 ], aY = args[ 1 ],
  17494. xRadius = args[ 2 ],
  17495. yRadius = args[ 3 ],
  17496. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17497. aClockwise = !!args[ 6 ];
  17498. var deltaAngle = aEndAngle - aStartAngle;
  17499. var angle;
  17500. var tdivisions = divisions * 2;
  17501. for ( j = 1; j <= tdivisions; j ++ ) {
  17502. t = j / tdivisions;
  17503. if ( ! aClockwise ) {
  17504. t = 1 - t;
  17505. }
  17506. angle = aStartAngle + t * deltaAngle;
  17507. tx = aX + xRadius * Math.cos( angle );
  17508. ty = aY + yRadius * Math.sin( angle );
  17509. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17510. points.push( new THREE.Vector2( tx, ty ) );
  17511. }
  17512. //console.log(points);
  17513. break;
  17514. } // end switch
  17515. }
  17516. // Normalize to remove the closing point by default.
  17517. var lastPoint = points[ points.length - 1];
  17518. var EPSILON = 0.0000000001;
  17519. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17520. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17521. points.splice( points.length - 1, 1);
  17522. if ( closedPath ) {
  17523. points.push( points[ 0 ] );
  17524. }
  17525. return points;
  17526. };
  17527. // Breaks path into shapes
  17528. THREE.Path.prototype.toShapes = function( isCCW ) {
  17529. var i, il, item, action, args;
  17530. var subPaths = [], lastPath = new THREE.Path();
  17531. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17532. item = this.actions[ i ];
  17533. args = item.args;
  17534. action = item.action;
  17535. if ( action == THREE.PathActions.MOVE_TO ) {
  17536. if ( lastPath.actions.length != 0 ) {
  17537. subPaths.push( lastPath );
  17538. lastPath = new THREE.Path();
  17539. }
  17540. }
  17541. lastPath[ action ].apply( lastPath, args );
  17542. }
  17543. if ( lastPath.actions.length != 0 ) {
  17544. subPaths.push( lastPath );
  17545. }
  17546. // console.log(subPaths);
  17547. if ( subPaths.length == 0 ) return [];
  17548. var solid, tmpPath, tmpShape, shapes = [];
  17549. if ( subPaths.length == 1) {
  17550. tmpPath = subPaths[0];
  17551. tmpShape = new THREE.Shape();
  17552. tmpShape.actions = tmpPath.actions;
  17553. tmpShape.curves = tmpPath.curves;
  17554. shapes.push( tmpShape );
  17555. return shapes;
  17556. }
  17557. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17558. holesFirst = isCCW ? !holesFirst : holesFirst;
  17559. // console.log("Holes first", holesFirst);
  17560. if ( holesFirst ) {
  17561. tmpShape = new THREE.Shape();
  17562. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17563. tmpPath = subPaths[ i ];
  17564. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17565. solid = isCCW ? !solid : solid;
  17566. if ( solid ) {
  17567. tmpShape.actions = tmpPath.actions;
  17568. tmpShape.curves = tmpPath.curves;
  17569. shapes.push( tmpShape );
  17570. tmpShape = new THREE.Shape();
  17571. //console.log('cw', i);
  17572. } else {
  17573. tmpShape.holes.push( tmpPath );
  17574. //console.log('ccw', i);
  17575. }
  17576. }
  17577. } else {
  17578. // Shapes first
  17579. tmpShape = undefined;
  17580. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17581. tmpPath = subPaths[ i ];
  17582. solid = THREE.Shape.Utils.isClockWise( tmpPath.getPoints() );
  17583. solid = isCCW ? !solid : solid;
  17584. if ( solid ) {
  17585. if ( tmpShape ) shapes.push( tmpShape );
  17586. tmpShape = new THREE.Shape();
  17587. tmpShape.actions = tmpPath.actions;
  17588. tmpShape.curves = tmpPath.curves;
  17589. } else {
  17590. tmpShape.holes.push( tmpPath );
  17591. }
  17592. }
  17593. shapes.push( tmpShape );
  17594. }
  17595. //console.log("shape", shapes);
  17596. return shapes;
  17597. };
  17598. /**
  17599. * @author zz85 / http://www.lab4games.net/zz85/blog
  17600. * Defines a 2d shape plane using paths.
  17601. **/
  17602. // STEP 1 Create a path.
  17603. // STEP 2 Turn path into shape.
  17604. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17605. // STEP 3a - Extract points from each shape, turn to vertices
  17606. // STEP 3b - Triangulate each shape, add faces.
  17607. THREE.Shape = function () {
  17608. THREE.Path.apply( this, arguments );
  17609. this.holes = [];
  17610. };
  17611. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17612. // Convenience method to return ExtrudeGeometry
  17613. THREE.Shape.prototype.extrude = function ( options ) {
  17614. var extruded = new THREE.ExtrudeGeometry( this, options );
  17615. return extruded;
  17616. };
  17617. // Convenience method to return ShapeGeometry
  17618. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17619. var geometry = new THREE.ShapeGeometry( this, options );
  17620. return geometry;
  17621. };
  17622. // Get points of holes
  17623. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17624. var i, il = this.holes.length, holesPts = [];
  17625. for ( i = 0; i < il; i ++ ) {
  17626. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17627. }
  17628. return holesPts;
  17629. };
  17630. // Get points of holes (spaced by regular distance)
  17631. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17632. var i, il = this.holes.length, holesPts = [];
  17633. for ( i = 0; i < il; i ++ ) {
  17634. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17635. }
  17636. return holesPts;
  17637. };
  17638. // Get points of shape and holes (keypoints based on segments parameter)
  17639. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17640. return {
  17641. shape: this.getTransformedPoints( divisions ),
  17642. holes: this.getPointsHoles( divisions )
  17643. };
  17644. };
  17645. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17646. if (this.useSpacedPoints) {
  17647. return this.extractAllSpacedPoints(divisions);
  17648. }
  17649. return this.extractAllPoints(divisions);
  17650. };
  17651. //
  17652. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17653. //
  17654. // return {
  17655. //
  17656. // shape: this.transform( bend, divisions ),
  17657. // holes: this.getPointsHoles( divisions, bend )
  17658. //
  17659. // };
  17660. //
  17661. // };
  17662. // Get points of shape and holes (spaced by regular distance)
  17663. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17664. return {
  17665. shape: this.getTransformedSpacedPoints( divisions ),
  17666. holes: this.getSpacedPointsHoles( divisions )
  17667. };
  17668. };
  17669. /**************************************************************
  17670. * Utils
  17671. **************************************************************/
  17672. THREE.Shape.Utils = {
  17673. /*
  17674. contour - array of vector2 for contour
  17675. holes - array of array of vector2
  17676. */
  17677. removeHoles: function ( contour, holes ) {
  17678. var shape = contour.concat(); // work on this shape
  17679. var allpoints = shape.concat();
  17680. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17681. var prevShapeVert, nextShapeVert,
  17682. prevHoleVert, nextHoleVert,
  17683. holeIndex, shapeIndex,
  17684. shapeId, shapeGroup,
  17685. h, h2,
  17686. hole, shortest, d,
  17687. p, pts1, pts2,
  17688. tmpShape1, tmpShape2,
  17689. tmpHole1, tmpHole2,
  17690. verts = [];
  17691. for ( h = 0; h < holes.length; h ++ ) {
  17692. hole = holes[ h ];
  17693. /*
  17694. shapeholes[ h ].concat(); // preserves original
  17695. holes.push( hole );
  17696. */
  17697. Array.prototype.push.apply( allpoints, hole );
  17698. shortest = Number.POSITIVE_INFINITY;
  17699. // Find the shortest pair of pts between shape and hole
  17700. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17701. // Using distanceToSquared() intead of distanceTo() should speed a little
  17702. // since running square roots operations are reduced.
  17703. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17704. pts1 = hole[ h2 ];
  17705. var dist = [];
  17706. for ( p = 0; p < shape.length; p++ ) {
  17707. pts2 = shape[ p ];
  17708. d = pts1.distanceToSquared( pts2 );
  17709. dist.push( d );
  17710. if ( d < shortest ) {
  17711. shortest = d;
  17712. holeIndex = h2;
  17713. shapeIndex = p;
  17714. }
  17715. }
  17716. }
  17717. //console.log("shortest", shortest, dist);
  17718. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17719. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17720. var areaapts = [
  17721. hole[ holeIndex ],
  17722. shape[ shapeIndex ],
  17723. shape[ prevShapeVert ]
  17724. ];
  17725. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17726. var areabpts = [
  17727. hole[ holeIndex ],
  17728. hole[ prevHoleVert ],
  17729. shape[ shapeIndex ]
  17730. ];
  17731. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17732. var shapeOffset = 1;
  17733. var holeOffset = -1;
  17734. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17735. shapeIndex += shapeOffset;
  17736. holeIndex += holeOffset;
  17737. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17738. shapeIndex %= shape.length;
  17739. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17740. holeIndex %= hole.length;
  17741. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17742. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17743. areaapts = [
  17744. hole[ holeIndex ],
  17745. shape[ shapeIndex ],
  17746. shape[ prevShapeVert ]
  17747. ];
  17748. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17749. areabpts = [
  17750. hole[ holeIndex ],
  17751. hole[ prevHoleVert ],
  17752. shape[ shapeIndex ]
  17753. ];
  17754. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17755. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17756. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17757. // In case areas are not correct.
  17758. //console.log("USE THIS");
  17759. shapeIndex = oldShapeIndex;
  17760. holeIndex = oldHoleIndex ;
  17761. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17762. shapeIndex %= shape.length;
  17763. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17764. holeIndex %= hole.length;
  17765. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17766. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17767. } else {
  17768. //console.log("USE THAT ")
  17769. }
  17770. tmpShape1 = shape.slice( 0, shapeIndex );
  17771. tmpShape2 = shape.slice( shapeIndex );
  17772. tmpHole1 = hole.slice( holeIndex );
  17773. tmpHole2 = hole.slice( 0, holeIndex );
  17774. // Should check orders here again?
  17775. var trianglea = [
  17776. hole[ holeIndex ],
  17777. shape[ shapeIndex ],
  17778. shape[ prevShapeVert ]
  17779. ];
  17780. var triangleb = [
  17781. hole[ holeIndex ] ,
  17782. hole[ prevHoleVert ],
  17783. shape[ shapeIndex ]
  17784. ];
  17785. verts.push( trianglea );
  17786. verts.push( triangleb );
  17787. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17788. }
  17789. return {
  17790. shape:shape, /* shape with no holes */
  17791. isolatedPts: verts, /* isolated faces */
  17792. allpoints: allpoints
  17793. }
  17794. },
  17795. triangulateShape: function ( contour, holes ) {
  17796. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17797. var shape = shapeWithoutHoles.shape,
  17798. allpoints = shapeWithoutHoles.allpoints,
  17799. isolatedPts = shapeWithoutHoles.isolatedPts;
  17800. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17801. // 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.
  17802. //console.log( "triangles",triangles, triangles.length );
  17803. //console.log( "allpoints",allpoints, allpoints.length );
  17804. var i, il, f, face,
  17805. key, index,
  17806. allPointsMap = {},
  17807. isolatedPointsMap = {};
  17808. // prepare all points map
  17809. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17810. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17811. if ( allPointsMap[ key ] !== undefined ) {
  17812. console.log( "Duplicate point", key );
  17813. }
  17814. allPointsMap[ key ] = i;
  17815. }
  17816. // check all face vertices against all points map
  17817. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17818. face = triangles[ i ];
  17819. for ( f = 0; f < 3; f ++ ) {
  17820. key = face[ f ].x + ":" + face[ f ].y;
  17821. index = allPointsMap[ key ];
  17822. if ( index !== undefined ) {
  17823. face[ f ] = index;
  17824. }
  17825. }
  17826. }
  17827. // check isolated points vertices against all points map
  17828. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17829. face = isolatedPts[ i ];
  17830. for ( f = 0; f < 3; f ++ ) {
  17831. key = face[ f ].x + ":" + face[ f ].y;
  17832. index = allPointsMap[ key ];
  17833. if ( index !== undefined ) {
  17834. face[ f ] = index;
  17835. }
  17836. }
  17837. }
  17838. return triangles.concat( isolatedPts );
  17839. }, // end triangulate shapes
  17840. /*
  17841. triangulate2 : function( pts, holes ) {
  17842. // For use with Poly2Tri.js
  17843. var allpts = pts.concat();
  17844. var shape = [];
  17845. for (var p in pts) {
  17846. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17847. }
  17848. var swctx = new js.poly2tri.SweepContext(shape);
  17849. for (var h in holes) {
  17850. var aHole = holes[h];
  17851. var newHole = []
  17852. for (i in aHole) {
  17853. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17854. allpts.push(aHole[i]);
  17855. }
  17856. swctx.AddHole(newHole);
  17857. }
  17858. var find;
  17859. var findIndexForPt = function (pt) {
  17860. find = new THREE.Vector2(pt.x, pt.y);
  17861. var p;
  17862. for (p=0, pl = allpts.length; p<pl; p++) {
  17863. if (allpts[p].equals(find)) return p;
  17864. }
  17865. return -1;
  17866. };
  17867. // triangulate
  17868. js.poly2tri.sweep.Triangulate(swctx);
  17869. var triangles = swctx.GetTriangles();
  17870. var tr ;
  17871. var facesPts = [];
  17872. for (var t in triangles) {
  17873. tr = triangles[t];
  17874. facesPts.push([
  17875. findIndexForPt(tr.GetPoint(0)),
  17876. findIndexForPt(tr.GetPoint(1)),
  17877. findIndexForPt(tr.GetPoint(2))
  17878. ]);
  17879. }
  17880. // console.log(facesPts);
  17881. // console.log("triangles", triangles.length, triangles);
  17882. // Returns array of faces with 3 element each
  17883. return facesPts;
  17884. },
  17885. */
  17886. isClockWise: function ( pts ) {
  17887. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17888. },
  17889. // Bezier Curves formulas obtained from
  17890. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17891. // Quad Bezier Functions
  17892. b2p0: function ( t, p ) {
  17893. var k = 1 - t;
  17894. return k * k * p;
  17895. },
  17896. b2p1: function ( t, p ) {
  17897. return 2 * ( 1 - t ) * t * p;
  17898. },
  17899. b2p2: function ( t, p ) {
  17900. return t * t * p;
  17901. },
  17902. b2: function ( t, p0, p1, p2 ) {
  17903. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17904. },
  17905. // Cubic Bezier Functions
  17906. b3p0: function ( t, p ) {
  17907. var k = 1 - t;
  17908. return k * k * k * p;
  17909. },
  17910. b3p1: function ( t, p ) {
  17911. var k = 1 - t;
  17912. return 3 * k * k * t * p;
  17913. },
  17914. b3p2: function ( t, p ) {
  17915. var k = 1 - t;
  17916. return 3 * k * t * t * p;
  17917. },
  17918. b3p3: function ( t, p ) {
  17919. return t * t * t * p;
  17920. },
  17921. b3: function ( t, p0, p1, p2, p3 ) {
  17922. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17923. }
  17924. };
  17925. /**************************************************************
  17926. * Line
  17927. **************************************************************/
  17928. THREE.LineCurve = function ( v1, v2 ) {
  17929. this.v1 = v1;
  17930. this.v2 = v2;
  17931. };
  17932. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  17933. THREE.LineCurve.prototype.getPoint = function ( t ) {
  17934. var point = this.v2.clone().sub(this.v1);
  17935. point.multiplyScalar( t ).add( this.v1 );
  17936. return point;
  17937. };
  17938. // Line curve is linear, so we can overwrite default getPointAt
  17939. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  17940. return this.getPoint( u );
  17941. };
  17942. THREE.LineCurve.prototype.getTangent = function( t ) {
  17943. var tangent = this.v2.clone().sub(this.v1);
  17944. return tangent.normalize();
  17945. };
  17946. /**************************************************************
  17947. * Quadratic Bezier curve
  17948. **************************************************************/
  17949. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  17950. this.v0 = v0;
  17951. this.v1 = v1;
  17952. this.v2 = v2;
  17953. };
  17954. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17955. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  17956. var tx, ty;
  17957. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  17958. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  17959. return new THREE.Vector2( tx, ty );
  17960. };
  17961. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  17962. var tx, ty;
  17963. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  17964. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  17965. // returns unit vector
  17966. var tangent = new THREE.Vector2( tx, ty );
  17967. tangent.normalize();
  17968. return tangent;
  17969. };
  17970. /**************************************************************
  17971. * Cubic Bezier curve
  17972. **************************************************************/
  17973. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  17974. this.v0 = v0;
  17975. this.v1 = v1;
  17976. this.v2 = v2;
  17977. this.v3 = v3;
  17978. };
  17979. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  17980. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  17981. var tx, ty;
  17982. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17983. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17984. return new THREE.Vector2( tx, ty );
  17985. };
  17986. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  17987. var tx, ty;
  17988. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  17989. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  17990. var tangent = new THREE.Vector2( tx, ty );
  17991. tangent.normalize();
  17992. return tangent;
  17993. };
  17994. /**************************************************************
  17995. * Spline curve
  17996. **************************************************************/
  17997. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  17998. this.points = (points == undefined) ? [] : points;
  17999. };
  18000. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  18001. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  18002. var v = new THREE.Vector2();
  18003. var c = [];
  18004. var points = this.points, point, intPoint, weight;
  18005. point = ( points.length - 1 ) * t;
  18006. intPoint = Math.floor( point );
  18007. weight = point - intPoint;
  18008. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18009. c[ 1 ] = intPoint;
  18010. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  18011. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  18012. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18013. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18014. return v;
  18015. };
  18016. /**************************************************************
  18017. * Ellipse curve
  18018. **************************************************************/
  18019. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  18020. aStartAngle, aEndAngle,
  18021. aClockwise ) {
  18022. this.aX = aX;
  18023. this.aY = aY;
  18024. this.xRadius = xRadius;
  18025. this.yRadius = yRadius;
  18026. this.aStartAngle = aStartAngle;
  18027. this.aEndAngle = aEndAngle;
  18028. this.aClockwise = aClockwise;
  18029. };
  18030. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  18031. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  18032. var deltaAngle = this.aEndAngle - this.aStartAngle;
  18033. if ( !this.aClockwise ) {
  18034. t = 1 - t;
  18035. }
  18036. var angle = this.aStartAngle + t * deltaAngle;
  18037. var tx = this.aX + this.xRadius * Math.cos( angle );
  18038. var ty = this.aY + this.yRadius * Math.sin( angle );
  18039. return new THREE.Vector2( tx, ty );
  18040. };
  18041. /**************************************************************
  18042. * Arc curve
  18043. **************************************************************/
  18044. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  18045. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  18046. };
  18047. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  18048. /**************************************************************
  18049. * Line3D
  18050. **************************************************************/
  18051. THREE.LineCurve3 = THREE.Curve.create(
  18052. function ( v1, v2 ) {
  18053. this.v1 = v1;
  18054. this.v2 = v2;
  18055. },
  18056. function ( t ) {
  18057. var r = new THREE.Vector3();
  18058. r.subVectors( this.v2, this.v1 ); // diff
  18059. r.multiplyScalar( t );
  18060. r.add( this.v1 );
  18061. return r;
  18062. }
  18063. );
  18064. /**************************************************************
  18065. * Quadratic Bezier 3D curve
  18066. **************************************************************/
  18067. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  18068. function ( v0, v1, v2 ) {
  18069. this.v0 = v0;
  18070. this.v1 = v1;
  18071. this.v2 = v2;
  18072. },
  18073. function ( t ) {
  18074. var tx, ty, tz;
  18075. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  18076. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  18077. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  18078. return new THREE.Vector3( tx, ty, tz );
  18079. }
  18080. );
  18081. /**************************************************************
  18082. * Cubic Bezier 3D curve
  18083. **************************************************************/
  18084. THREE.CubicBezierCurve3 = THREE.Curve.create(
  18085. function ( v0, v1, v2, v3 ) {
  18086. this.v0 = v0;
  18087. this.v1 = v1;
  18088. this.v2 = v2;
  18089. this.v3 = v3;
  18090. },
  18091. function ( t ) {
  18092. var tx, ty, tz;
  18093. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  18094. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  18095. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  18096. return new THREE.Vector3( tx, ty, tz );
  18097. }
  18098. );
  18099. /**************************************************************
  18100. * Spline 3D curve
  18101. **************************************************************/
  18102. THREE.SplineCurve3 = THREE.Curve.create(
  18103. function ( points /* array of Vector3 */) {
  18104. this.points = (points == undefined) ? [] : points;
  18105. },
  18106. function ( t ) {
  18107. var v = new THREE.Vector3();
  18108. var c = [];
  18109. var points = this.points, point, intPoint, weight;
  18110. point = ( points.length - 1 ) * t;
  18111. intPoint = Math.floor( point );
  18112. weight = point - intPoint;
  18113. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18114. c[ 1 ] = intPoint;
  18115. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18116. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18117. var pt0 = points[ c[0] ],
  18118. pt1 = points[ c[1] ],
  18119. pt2 = points[ c[2] ],
  18120. pt3 = points[ c[3] ];
  18121. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  18122. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  18123. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  18124. return v;
  18125. }
  18126. );
  18127. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  18128. // var v = new THREE.Vector3();
  18129. // var c = [];
  18130. // var points = this.points, point, intPoint, weight;
  18131. // point = ( points.length - 1 ) * t;
  18132. // intPoint = Math.floor( point );
  18133. // weight = point - intPoint;
  18134. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  18135. // c[ 1 ] = intPoint;
  18136. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  18137. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  18138. // var pt0 = points[ c[0] ],
  18139. // pt1 = points[ c[1] ],
  18140. // pt2 = points[ c[2] ],
  18141. // pt3 = points[ c[3] ];
  18142. // // t = weight;
  18143. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  18144. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  18145. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  18146. // return v;
  18147. // }
  18148. /**************************************************************
  18149. * Closed Spline 3D curve
  18150. **************************************************************/
  18151. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  18152. function ( points /* array of Vector3 */) {
  18153. this.points = (points == undefined) ? [] : points;
  18154. },
  18155. function ( t ) {
  18156. var v = new THREE.Vector3();
  18157. var c = [];
  18158. var points = this.points, point, intPoint, weight;
  18159. point = ( points.length - 0 ) * t;
  18160. // This needs to be from 0-length +1
  18161. intPoint = Math.floor( point );
  18162. weight = point - intPoint;
  18163. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  18164. c[ 0 ] = ( intPoint - 1 ) % points.length;
  18165. c[ 1 ] = ( intPoint ) % points.length;
  18166. c[ 2 ] = ( intPoint + 1 ) % points.length;
  18167. c[ 3 ] = ( intPoint + 2 ) % points.length;
  18168. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  18169. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  18170. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  18171. return v;
  18172. }
  18173. );
  18174. /**
  18175. * @author mikael emtinger / http://gomo.se/
  18176. */
  18177. THREE.AnimationHandler = (function() {
  18178. var playing = [];
  18179. var library = {};
  18180. var that = {};
  18181. //--- update ---
  18182. that.update = function( deltaTimeMS ) {
  18183. for( var i = 0; i < playing.length; i ++ )
  18184. playing[ i ].update( deltaTimeMS );
  18185. };
  18186. //--- add ---
  18187. that.addToUpdate = function( animation ) {
  18188. if ( playing.indexOf( animation ) === -1 )
  18189. playing.push( animation );
  18190. };
  18191. //--- remove ---
  18192. that.removeFromUpdate = function( animation ) {
  18193. var index = playing.indexOf( animation );
  18194. if( index !== -1 )
  18195. playing.splice( index, 1 );
  18196. };
  18197. //--- add ---
  18198. that.add = function( data ) {
  18199. if ( library[ data.name ] !== undefined )
  18200. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  18201. library[ data.name ] = data;
  18202. initData( data );
  18203. };
  18204. //--- get ---
  18205. that.get = function( name ) {
  18206. if ( typeof name === "string" ) {
  18207. if ( library[ name ] ) {
  18208. return library[ name ];
  18209. } else {
  18210. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  18211. return null;
  18212. }
  18213. } else {
  18214. // todo: add simple tween library
  18215. }
  18216. };
  18217. //--- parse ---
  18218. that.parse = function( root ) {
  18219. // setup hierarchy
  18220. var hierarchy = [];
  18221. if ( root instanceof THREE.SkinnedMesh ) {
  18222. for( var b = 0; b < root.bones.length; b++ ) {
  18223. hierarchy.push( root.bones[ b ] );
  18224. }
  18225. } else {
  18226. parseRecurseHierarchy( root, hierarchy );
  18227. }
  18228. return hierarchy;
  18229. };
  18230. var parseRecurseHierarchy = function( root, hierarchy ) {
  18231. hierarchy.push( root );
  18232. for( var c = 0; c < root.children.length; c++ )
  18233. parseRecurseHierarchy( root.children[ c ], hierarchy );
  18234. }
  18235. //--- init data ---
  18236. var initData = function( data ) {
  18237. if( data.initialized === true )
  18238. return;
  18239. // loop through all keys
  18240. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  18241. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18242. // remove minus times
  18243. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  18244. data.hierarchy[ h ].keys[ k ].time = 0;
  18245. // create quaternions
  18246. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  18247. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  18248. var quat = data.hierarchy[ h ].keys[ k ].rot;
  18249. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  18250. }
  18251. }
  18252. // prepare morph target keys
  18253. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  18254. // get all used
  18255. var usedMorphTargets = {};
  18256. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18257. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18258. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  18259. usedMorphTargets[ morphTargetName ] = -1;
  18260. }
  18261. }
  18262. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  18263. // set all used on all frames
  18264. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18265. var influences = {};
  18266. for ( var morphTargetName in usedMorphTargets ) {
  18267. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  18268. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  18269. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  18270. break;
  18271. }
  18272. }
  18273. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  18274. influences[ morphTargetName ] = 0;
  18275. }
  18276. }
  18277. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  18278. }
  18279. }
  18280. // remove all keys that are on the same time
  18281. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18282. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  18283. data.hierarchy[ h ].keys.splice( k, 1 );
  18284. k --;
  18285. }
  18286. }
  18287. // set index
  18288. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  18289. data.hierarchy[ h ].keys[ k ].index = k;
  18290. }
  18291. }
  18292. // JIT
  18293. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  18294. data.JIT = {};
  18295. data.JIT.hierarchy = [];
  18296. for( var h = 0; h < data.hierarchy.length; h ++ )
  18297. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  18298. // done
  18299. data.initialized = true;
  18300. };
  18301. // interpolation types
  18302. that.LINEAR = 0;
  18303. that.CATMULLROM = 1;
  18304. that.CATMULLROM_FORWARD = 2;
  18305. return that;
  18306. }());
  18307. /**
  18308. * @author mikael emtinger / http://gomo.se/
  18309. * @author mrdoob / http://mrdoob.com/
  18310. * @author alteredq / http://alteredqualia.com/
  18311. */
  18312. THREE.Animation = function ( root, name, interpolationType ) {
  18313. this.root = root;
  18314. this.data = THREE.AnimationHandler.get( name );
  18315. this.hierarchy = THREE.AnimationHandler.parse( root );
  18316. this.currentTime = 0;
  18317. this.timeScale = 1;
  18318. this.isPlaying = false;
  18319. this.isPaused = true;
  18320. this.loop = true;
  18321. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  18322. this.points = [];
  18323. this.target = new THREE.Vector3();
  18324. };
  18325. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  18326. if ( this.isPlaying === false ) {
  18327. this.isPlaying = true;
  18328. this.loop = loop !== undefined ? loop : true;
  18329. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18330. // reset key cache
  18331. var h, hl = this.hierarchy.length,
  18332. object;
  18333. for ( h = 0; h < hl; h ++ ) {
  18334. object = this.hierarchy[ h ];
  18335. object.matrixAutoUpdate = true;
  18336. if ( object.animationCache === undefined ) {
  18337. object.animationCache = {};
  18338. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  18339. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  18340. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18341. }
  18342. var prevKey = object.animationCache.prevKey;
  18343. var nextKey = object.animationCache.nextKey;
  18344. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  18345. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  18346. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  18347. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  18348. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  18349. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  18350. }
  18351. this.update( 0 );
  18352. }
  18353. this.isPaused = false;
  18354. THREE.AnimationHandler.addToUpdate( this );
  18355. };
  18356. THREE.Animation.prototype.pause = function() {
  18357. if ( this.isPaused === true ) {
  18358. THREE.AnimationHandler.addToUpdate( this );
  18359. } else {
  18360. THREE.AnimationHandler.removeFromUpdate( this );
  18361. }
  18362. this.isPaused = !this.isPaused;
  18363. };
  18364. THREE.Animation.prototype.stop = function() {
  18365. this.isPlaying = false;
  18366. this.isPaused = false;
  18367. THREE.AnimationHandler.removeFromUpdate( this );
  18368. };
  18369. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  18370. // early out
  18371. if ( this.isPlaying === false ) return;
  18372. // vars
  18373. var types = [ "pos", "rot", "scl" ];
  18374. var type;
  18375. var scale;
  18376. var vector;
  18377. var prevXYZ, nextXYZ;
  18378. var prevKey, nextKey;
  18379. var object;
  18380. var animationCache;
  18381. var frame;
  18382. var JIThierarchy = this.data.JIT.hierarchy;
  18383. var currentTime, unloopedCurrentTime;
  18384. var currentPoint, forwardPoint, angle;
  18385. this.currentTime += deltaTimeMS * this.timeScale;
  18386. unloopedCurrentTime = this.currentTime;
  18387. currentTime = this.currentTime = this.currentTime % this.data.length;
  18388. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18389. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  18390. object = this.hierarchy[ h ];
  18391. animationCache = object.animationCache;
  18392. // loop through pos/rot/scl
  18393. for ( var t = 0; t < 3; t ++ ) {
  18394. // get keys
  18395. type = types[ t ];
  18396. prevKey = animationCache.prevKey[ type ];
  18397. nextKey = animationCache.nextKey[ type ];
  18398. // switch keys?
  18399. if ( nextKey.time <= unloopedCurrentTime ) {
  18400. // did we loop?
  18401. if ( currentTime < unloopedCurrentTime ) {
  18402. if ( this.loop ) {
  18403. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  18404. nextKey = this.getNextKeyWith( type, h, 1 );
  18405. while( nextKey.time < currentTime ) {
  18406. prevKey = nextKey;
  18407. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18408. }
  18409. } else {
  18410. this.stop();
  18411. return;
  18412. }
  18413. } else {
  18414. do {
  18415. prevKey = nextKey;
  18416. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  18417. } while( nextKey.time < currentTime )
  18418. }
  18419. animationCache.prevKey[ type ] = prevKey;
  18420. animationCache.nextKey[ type ] = nextKey;
  18421. }
  18422. object.matrixAutoUpdate = true;
  18423. object.matrixWorldNeedsUpdate = true;
  18424. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  18425. prevXYZ = prevKey[ type ];
  18426. nextXYZ = nextKey[ type ];
  18427. // check scale error
  18428. if ( scale < 0 || scale > 1 ) {
  18429. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  18430. scale = scale < 0 ? 0 : 1;
  18431. }
  18432. // interpolate
  18433. if ( type === "pos" ) {
  18434. vector = object.position;
  18435. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  18436. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18437. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18438. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18439. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18440. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18441. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  18442. this.points[ 1 ] = prevXYZ;
  18443. this.points[ 2 ] = nextXYZ;
  18444. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  18445. scale = scale * 0.33 + 0.33;
  18446. currentPoint = this.interpolateCatmullRom( this.points, scale );
  18447. vector.x = currentPoint[ 0 ];
  18448. vector.y = currentPoint[ 1 ];
  18449. vector.z = currentPoint[ 2 ];
  18450. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18451. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  18452. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  18453. this.target.sub( vector );
  18454. this.target.y = 0;
  18455. this.target.normalize();
  18456. angle = Math.atan2( this.target.x, this.target.z );
  18457. object.rotation.set( 0, angle, 0 );
  18458. }
  18459. }
  18460. } else if ( type === "rot" ) {
  18461. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  18462. } else if ( type === "scl" ) {
  18463. vector = object.scale;
  18464. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  18465. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  18466. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  18467. }
  18468. }
  18469. }
  18470. };
  18471. // Catmull-Rom spline
  18472. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  18473. var c = [], v3 = [],
  18474. point, intPoint, weight, w2, w3,
  18475. pa, pb, pc, pd;
  18476. point = ( points.length - 1 ) * scale;
  18477. intPoint = Math.floor( point );
  18478. weight = point - intPoint;
  18479. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  18480. c[ 1 ] = intPoint;
  18481. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  18482. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  18483. pa = points[ c[ 0 ] ];
  18484. pb = points[ c[ 1 ] ];
  18485. pc = points[ c[ 2 ] ];
  18486. pd = points[ c[ 3 ] ];
  18487. w2 = weight * weight;
  18488. w3 = weight * w2;
  18489. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  18490. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  18491. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  18492. return v3;
  18493. };
  18494. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  18495. var v0 = ( p2 - p0 ) * 0.5,
  18496. v1 = ( p3 - p1 ) * 0.5;
  18497. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  18498. };
  18499. // Get next key with
  18500. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  18501. var keys = this.data.hierarchy[ h ].keys;
  18502. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18503. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18504. key = key < keys.length - 1 ? key : keys.length - 1;
  18505. } else {
  18506. key = key % keys.length;
  18507. }
  18508. for ( ; key < keys.length; key++ ) {
  18509. if ( keys[ key ][ type ] !== undefined ) {
  18510. return keys[ key ];
  18511. }
  18512. }
  18513. return this.data.hierarchy[ h ].keys[ 0 ];
  18514. };
  18515. // Get previous key with
  18516. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  18517. var keys = this.data.hierarchy[ h ].keys;
  18518. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  18519. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  18520. key = key > 0 ? key : 0;
  18521. } else {
  18522. key = key >= 0 ? key : key + keys.length;
  18523. }
  18524. for ( ; key >= 0; key -- ) {
  18525. if ( keys[ key ][ type ] !== undefined ) {
  18526. return keys[ key ];
  18527. }
  18528. }
  18529. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  18530. };
  18531. /**
  18532. * @author mikael emtinger / http://gomo.se/
  18533. * @author mrdoob / http://mrdoob.com/
  18534. * @author alteredq / http://alteredqualia.com/
  18535. * @author khang duong
  18536. * @author erik kitson
  18537. */
  18538. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  18539. this.root = root;
  18540. this.data = THREE.AnimationHandler.get( data );
  18541. this.hierarchy = THREE.AnimationHandler.parse( root );
  18542. this.currentTime = 0;
  18543. this.timeScale = 0.001;
  18544. this.isPlaying = false;
  18545. this.isPaused = true;
  18546. this.loop = true;
  18547. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  18548. // initialize to first keyframes
  18549. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18550. var keys = this.data.hierarchy[h].keys,
  18551. sids = this.data.hierarchy[h].sids,
  18552. obj = this.hierarchy[h];
  18553. if ( keys.length && sids ) {
  18554. for ( var s = 0; s < sids.length; s++ ) {
  18555. var sid = sids[ s ],
  18556. next = this.getNextKeyWith( sid, h, 0 );
  18557. if ( next ) {
  18558. next.apply( sid );
  18559. }
  18560. }
  18561. obj.matrixAutoUpdate = false;
  18562. this.data.hierarchy[h].node.updateMatrix();
  18563. obj.matrixWorldNeedsUpdate = true;
  18564. }
  18565. }
  18566. };
  18567. // Play
  18568. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  18569. if( !this.isPlaying ) {
  18570. this.isPlaying = true;
  18571. this.loop = loop !== undefined ? loop : true;
  18572. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  18573. this.startTimeMs = startTimeMS;
  18574. this.startTime = 10000000;
  18575. this.endTime = -this.startTime;
  18576. // reset key cache
  18577. var h, hl = this.hierarchy.length,
  18578. object,
  18579. node;
  18580. for ( h = 0; h < hl; h++ ) {
  18581. object = this.hierarchy[ h ];
  18582. node = this.data.hierarchy[ h ];
  18583. if ( node.animationCache === undefined ) {
  18584. node.animationCache = {};
  18585. node.animationCache.prevKey = null;
  18586. node.animationCache.nextKey = null;
  18587. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  18588. }
  18589. var keys = this.data.hierarchy[h].keys;
  18590. if (keys.length) {
  18591. node.animationCache.prevKey = keys[ 0 ];
  18592. node.animationCache.nextKey = keys[ 1 ];
  18593. this.startTime = Math.min( keys[0].time, this.startTime );
  18594. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18595. }
  18596. }
  18597. this.update( 0 );
  18598. }
  18599. this.isPaused = false;
  18600. THREE.AnimationHandler.addToUpdate( this );
  18601. };
  18602. // Pause
  18603. THREE.KeyFrameAnimation.prototype.pause = function() {
  18604. if( this.isPaused ) {
  18605. THREE.AnimationHandler.addToUpdate( this );
  18606. } else {
  18607. THREE.AnimationHandler.removeFromUpdate( this );
  18608. }
  18609. this.isPaused = !this.isPaused;
  18610. };
  18611. // Stop
  18612. THREE.KeyFrameAnimation.prototype.stop = function() {
  18613. this.isPlaying = false;
  18614. this.isPaused = false;
  18615. THREE.AnimationHandler.removeFromUpdate( this );
  18616. // reset JIT matrix and remove cache
  18617. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18618. var obj = this.hierarchy[ h ];
  18619. var node = this.data.hierarchy[ h ];
  18620. if ( node.animationCache !== undefined ) {
  18621. var original = node.animationCache.originalMatrix;
  18622. if( obj instanceof THREE.Bone ) {
  18623. original.copy( obj.skinMatrix );
  18624. obj.skinMatrix = original;
  18625. } else {
  18626. original.copy( obj.matrix );
  18627. obj.matrix = original;
  18628. }
  18629. delete node.animationCache;
  18630. }
  18631. }
  18632. };
  18633. // Update
  18634. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18635. // early out
  18636. if( !this.isPlaying ) return;
  18637. // vars
  18638. var prevKey, nextKey;
  18639. var object;
  18640. var node;
  18641. var frame;
  18642. var JIThierarchy = this.data.JIT.hierarchy;
  18643. var currentTime, unloopedCurrentTime;
  18644. var looped;
  18645. // update
  18646. this.currentTime += deltaTimeMS * this.timeScale;
  18647. unloopedCurrentTime = this.currentTime;
  18648. currentTime = this.currentTime = this.currentTime % this.data.length;
  18649. // if looped around, the current time should be based on the startTime
  18650. if ( currentTime < this.startTimeMs ) {
  18651. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18652. }
  18653. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18654. looped = currentTime < unloopedCurrentTime;
  18655. if ( looped && !this.loop ) {
  18656. // Set the animation to the last keyframes and stop
  18657. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18658. var keys = this.data.hierarchy[h].keys,
  18659. sids = this.data.hierarchy[h].sids,
  18660. end = keys.length-1,
  18661. obj = this.hierarchy[h];
  18662. if ( keys.length ) {
  18663. for ( var s = 0; s < sids.length; s++ ) {
  18664. var sid = sids[ s ],
  18665. prev = this.getPrevKeyWith( sid, h, end );
  18666. if ( prev ) {
  18667. prev.apply( sid );
  18668. }
  18669. }
  18670. this.data.hierarchy[h].node.updateMatrix();
  18671. obj.matrixWorldNeedsUpdate = true;
  18672. }
  18673. }
  18674. this.stop();
  18675. return;
  18676. }
  18677. // check pre-infinity
  18678. if ( currentTime < this.startTime ) {
  18679. return;
  18680. }
  18681. // update
  18682. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18683. object = this.hierarchy[ h ];
  18684. node = this.data.hierarchy[ h ];
  18685. var keys = node.keys,
  18686. animationCache = node.animationCache;
  18687. // use JIT?
  18688. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18689. if( object instanceof THREE.Bone ) {
  18690. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18691. object.matrixWorldNeedsUpdate = false;
  18692. } else {
  18693. object.matrix = JIThierarchy[ h ][ frame ];
  18694. object.matrixWorldNeedsUpdate = true;
  18695. }
  18696. // use interpolation
  18697. } else if ( keys.length ) {
  18698. // make sure so original matrix and not JIT matrix is set
  18699. if ( this.JITCompile && animationCache ) {
  18700. if( object instanceof THREE.Bone ) {
  18701. object.skinMatrix = animationCache.originalMatrix;
  18702. } else {
  18703. object.matrix = animationCache.originalMatrix;
  18704. }
  18705. }
  18706. prevKey = animationCache.prevKey;
  18707. nextKey = animationCache.nextKey;
  18708. if ( prevKey && nextKey ) {
  18709. // switch keys?
  18710. if ( nextKey.time <= unloopedCurrentTime ) {
  18711. // did we loop?
  18712. if ( looped && this.loop ) {
  18713. prevKey = keys[ 0 ];
  18714. nextKey = keys[ 1 ];
  18715. while ( nextKey.time < currentTime ) {
  18716. prevKey = nextKey;
  18717. nextKey = keys[ prevKey.index + 1 ];
  18718. }
  18719. } else if ( !looped ) {
  18720. var lastIndex = keys.length - 1;
  18721. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18722. prevKey = nextKey;
  18723. nextKey = keys[ prevKey.index + 1 ];
  18724. }
  18725. }
  18726. animationCache.prevKey = prevKey;
  18727. animationCache.nextKey = nextKey;
  18728. }
  18729. if(nextKey.time >= currentTime)
  18730. prevKey.interpolate( nextKey, currentTime );
  18731. else
  18732. prevKey.interpolate( nextKey, nextKey.time);
  18733. }
  18734. this.data.hierarchy[h].node.updateMatrix();
  18735. object.matrixWorldNeedsUpdate = true;
  18736. }
  18737. }
  18738. // update JIT?
  18739. if ( this.JITCompile ) {
  18740. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18741. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18742. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18743. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18744. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18745. } else {
  18746. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18747. }
  18748. }
  18749. }
  18750. }
  18751. };
  18752. // Get next key with
  18753. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18754. var keys = this.data.hierarchy[ h ].keys;
  18755. key = key % keys.length;
  18756. for ( ; key < keys.length; key++ ) {
  18757. if ( keys[ key ].hasTarget( sid ) ) {
  18758. return keys[ key ];
  18759. }
  18760. }
  18761. return keys[ 0 ];
  18762. };
  18763. // Get previous key with
  18764. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18765. var keys = this.data.hierarchy[ h ].keys;
  18766. key = key >= 0 ? key : key + keys.length;
  18767. for ( ; key >= 0; key-- ) {
  18768. if ( keys[ key ].hasTarget( sid ) ) {
  18769. return keys[ key ];
  18770. }
  18771. }
  18772. return keys[ keys.length - 1 ];
  18773. };
  18774. /**
  18775. * Camera for rendering cube maps
  18776. * - renders scene into axis-aligned cube
  18777. *
  18778. * @author alteredq / http://alteredqualia.com/
  18779. */
  18780. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18781. THREE.Object3D.call( this );
  18782. var fov = 90, aspect = 1;
  18783. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18784. cameraPX.up.set( 0, -1, 0 );
  18785. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18786. this.add( cameraPX );
  18787. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18788. cameraNX.up.set( 0, -1, 0 );
  18789. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18790. this.add( cameraNX );
  18791. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18792. cameraPY.up.set( 0, 0, 1 );
  18793. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18794. this.add( cameraPY );
  18795. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18796. cameraNY.up.set( 0, 0, -1 );
  18797. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18798. this.add( cameraNY );
  18799. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18800. cameraPZ.up.set( 0, -1, 0 );
  18801. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18802. this.add( cameraPZ );
  18803. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18804. cameraNZ.up.set( 0, -1, 0 );
  18805. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18806. this.add( cameraNZ );
  18807. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18808. this.updateCubeMap = function ( renderer, scene ) {
  18809. var renderTarget = this.renderTarget;
  18810. var generateMipmaps = renderTarget.generateMipmaps;
  18811. renderTarget.generateMipmaps = false;
  18812. renderTarget.activeCubeFace = 0;
  18813. renderer.render( scene, cameraPX, renderTarget );
  18814. renderTarget.activeCubeFace = 1;
  18815. renderer.render( scene, cameraNX, renderTarget );
  18816. renderTarget.activeCubeFace = 2;
  18817. renderer.render( scene, cameraPY, renderTarget );
  18818. renderTarget.activeCubeFace = 3;
  18819. renderer.render( scene, cameraNY, renderTarget );
  18820. renderTarget.activeCubeFace = 4;
  18821. renderer.render( scene, cameraPZ, renderTarget );
  18822. renderTarget.generateMipmaps = generateMipmaps;
  18823. renderTarget.activeCubeFace = 5;
  18824. renderer.render( scene, cameraNZ, renderTarget );
  18825. };
  18826. };
  18827. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18828. /*
  18829. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18830. *
  18831. * A general perpose camera, for setting FOV, Lens Focal Length,
  18832. * and switching between perspective and orthographic views easily.
  18833. * Use this only if you do not wish to manage
  18834. * both a Orthographic and Perspective Camera
  18835. *
  18836. */
  18837. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18838. THREE.Camera.call( this );
  18839. this.fov = fov;
  18840. this.left = -width / 2;
  18841. this.right = width / 2
  18842. this.top = height / 2;
  18843. this.bottom = -height / 2;
  18844. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18845. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18846. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18847. this.zoom = 1;
  18848. this.toPerspective();
  18849. var aspect = width/height;
  18850. };
  18851. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18852. THREE.CombinedCamera.prototype.toPerspective = function () {
  18853. // Switches to the Perspective Camera
  18854. this.near = this.cameraP.near;
  18855. this.far = this.cameraP.far;
  18856. this.cameraP.fov = this.fov / this.zoom ;
  18857. this.cameraP.updateProjectionMatrix();
  18858. this.projectionMatrix = this.cameraP.projectionMatrix;
  18859. this.inPerspectiveMode = true;
  18860. this.inOrthographicMode = false;
  18861. };
  18862. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18863. // Switches to the Orthographic camera estimating viewport from Perspective
  18864. var fov = this.fov;
  18865. var aspect = this.cameraP.aspect;
  18866. var near = this.cameraP.near;
  18867. var far = this.cameraP.far;
  18868. // The size that we set is the mid plane of the viewing frustum
  18869. var hyperfocus = ( near + far ) / 2;
  18870. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18871. var planeHeight = 2 * halfHeight;
  18872. var planeWidth = planeHeight * aspect;
  18873. var halfWidth = planeWidth / 2;
  18874. halfHeight /= this.zoom;
  18875. halfWidth /= this.zoom;
  18876. this.cameraO.left = -halfWidth;
  18877. this.cameraO.right = halfWidth;
  18878. this.cameraO.top = halfHeight;
  18879. this.cameraO.bottom = -halfHeight;
  18880. // this.cameraO.left = -farHalfWidth;
  18881. // this.cameraO.right = farHalfWidth;
  18882. // this.cameraO.top = farHalfHeight;
  18883. // this.cameraO.bottom = -farHalfHeight;
  18884. // this.cameraO.left = this.left / this.zoom;
  18885. // this.cameraO.right = this.right / this.zoom;
  18886. // this.cameraO.top = this.top / this.zoom;
  18887. // this.cameraO.bottom = this.bottom / this.zoom;
  18888. this.cameraO.updateProjectionMatrix();
  18889. this.near = this.cameraO.near;
  18890. this.far = this.cameraO.far;
  18891. this.projectionMatrix = this.cameraO.projectionMatrix;
  18892. this.inPerspectiveMode = false;
  18893. this.inOrthographicMode = true;
  18894. };
  18895. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18896. this.cameraP.aspect = width / height;
  18897. this.left = -width / 2;
  18898. this.right = width / 2
  18899. this.top = height / 2;
  18900. this.bottom = -height / 2;
  18901. };
  18902. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18903. this.fov = fov;
  18904. if ( this.inPerspectiveMode ) {
  18905. this.toPerspective();
  18906. } else {
  18907. this.toOrthographic();
  18908. }
  18909. };
  18910. // For mantaining similar API with PerspectiveCamera
  18911. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18912. if ( this.inPerspectiveMode ) {
  18913. this.toPerspective();
  18914. } else {
  18915. this.toPerspective();
  18916. this.toOrthographic();
  18917. }
  18918. };
  18919. /*
  18920. * Uses Focal Length (in mm) to estimate and set FOV
  18921. * 35mm (fullframe) camera is used if frame size is not specified;
  18922. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18923. */
  18924. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18925. if ( frameHeight === undefined ) frameHeight = 24;
  18926. var fov = 2 * THREE.Math.radToDeg( Math.atan( frameHeight / ( focalLength * 2 ) ) );
  18927. this.setFov( fov );
  18928. return fov;
  18929. };
  18930. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18931. this.zoom = zoom;
  18932. if ( this.inPerspectiveMode ) {
  18933. this.toPerspective();
  18934. } else {
  18935. this.toOrthographic();
  18936. }
  18937. };
  18938. THREE.CombinedCamera.prototype.toFrontView = function() {
  18939. this.rotation.x = 0;
  18940. this.rotation.y = 0;
  18941. this.rotation.z = 0;
  18942. // should we be modifing the matrix instead?
  18943. this.rotationAutoUpdate = false;
  18944. };
  18945. THREE.CombinedCamera.prototype.toBackView = function() {
  18946. this.rotation.x = 0;
  18947. this.rotation.y = Math.PI;
  18948. this.rotation.z = 0;
  18949. this.rotationAutoUpdate = false;
  18950. };
  18951. THREE.CombinedCamera.prototype.toLeftView = function() {
  18952. this.rotation.x = 0;
  18953. this.rotation.y = - Math.PI / 2;
  18954. this.rotation.z = 0;
  18955. this.rotationAutoUpdate = false;
  18956. };
  18957. THREE.CombinedCamera.prototype.toRightView = function() {
  18958. this.rotation.x = 0;
  18959. this.rotation.y = Math.PI / 2;
  18960. this.rotation.z = 0;
  18961. this.rotationAutoUpdate = false;
  18962. };
  18963. THREE.CombinedCamera.prototype.toTopView = function() {
  18964. this.rotation.x = - Math.PI / 2;
  18965. this.rotation.y = 0;
  18966. this.rotation.z = 0;
  18967. this.rotationAutoUpdate = false;
  18968. };
  18969. THREE.CombinedCamera.prototype.toBottomView = function() {
  18970. this.rotation.x = Math.PI / 2;
  18971. this.rotation.y = 0;
  18972. this.rotation.z = 0;
  18973. this.rotationAutoUpdate = false;
  18974. };
  18975. /**
  18976. * @author hughes
  18977. */
  18978. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18979. THREE.Geometry.call( this );
  18980. radius = radius || 50;
  18981. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18982. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18983. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18984. var i, uvs = [],
  18985. center = new THREE.Vector3(), centerUV = new THREE.Vector2( 0.5, 0.5 );
  18986. this.vertices.push(center);
  18987. uvs.push( centerUV );
  18988. for ( i = 0; i <= segments; i ++ ) {
  18989. var vertex = new THREE.Vector3();
  18990. var segment = thetaStart + i / segments * thetaLength;
  18991. vertex.x = radius * Math.cos( segment );
  18992. vertex.y = radius * Math.sin( segment );
  18993. this.vertices.push( vertex );
  18994. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, ( vertex.y / radius + 1 ) / 2 ) );
  18995. }
  18996. var n = new THREE.Vector3( 0, 0, 1 );
  18997. for ( i = 1; i <= segments; i ++ ) {
  18998. var v1 = i;
  18999. var v2 = i + 1 ;
  19000. var v3 = 0;
  19001. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19002. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  19003. }
  19004. this.computeCentroids();
  19005. this.computeFaceNormals();
  19006. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19007. };
  19008. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19009. /**
  19010. * @author mrdoob / http://mrdoob.com/
  19011. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  19012. */
  19013. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  19014. THREE.Geometry.call( this );
  19015. var scope = this;
  19016. this.width = width;
  19017. this.height = height;
  19018. this.depth = depth;
  19019. this.widthSegments = widthSegments || 1;
  19020. this.heightSegments = heightSegments || 1;
  19021. this.depthSegments = depthSegments || 1;
  19022. var width_half = this.width / 2;
  19023. var height_half = this.height / 2;
  19024. var depth_half = this.depth / 2;
  19025. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  19026. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  19027. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  19028. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  19029. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  19030. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  19031. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  19032. var w, ix, iy,
  19033. gridX = scope.widthSegments,
  19034. gridY = scope.heightSegments,
  19035. width_half = width / 2,
  19036. height_half = height / 2,
  19037. offset = scope.vertices.length;
  19038. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  19039. w = 'z';
  19040. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  19041. w = 'y';
  19042. gridY = scope.depthSegments;
  19043. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  19044. w = 'x';
  19045. gridX = scope.depthSegments;
  19046. }
  19047. var gridX1 = gridX + 1,
  19048. gridY1 = gridY + 1,
  19049. segment_width = width / gridX,
  19050. segment_height = height / gridY,
  19051. normal = new THREE.Vector3();
  19052. normal[ w ] = depth > 0 ? 1 : - 1;
  19053. for ( iy = 0; iy < gridY1; iy ++ ) {
  19054. for ( ix = 0; ix < gridX1; ix ++ ) {
  19055. var vector = new THREE.Vector3();
  19056. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  19057. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  19058. vector[ w ] = depth;
  19059. scope.vertices.push( vector );
  19060. }
  19061. }
  19062. for ( iy = 0; iy < gridY; iy++ ) {
  19063. for ( ix = 0; ix < gridX; ix++ ) {
  19064. var a = ix + gridX1 * iy;
  19065. var b = ix + gridX1 * ( iy + 1 );
  19066. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  19067. var d = ( ix + 1 ) + gridX1 * iy;
  19068. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  19069. face.normal.copy( normal );
  19070. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19071. face.materialIndex = materialIndex;
  19072. scope.faces.push( face );
  19073. scope.faceVertexUvs[ 0 ].push( [
  19074. new THREE.Vector2( ix / gridX, 1 - iy / gridY ),
  19075. new THREE.Vector2( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  19076. new THREE.Vector2( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  19077. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iy / gridY )
  19078. ] );
  19079. }
  19080. }
  19081. }
  19082. this.computeCentroids();
  19083. this.mergeVertices();
  19084. };
  19085. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19086. /**
  19087. * @author mrdoob / http://mrdoob.com/
  19088. */
  19089. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radialSegments, heightSegments, openEnded ) {
  19090. THREE.Geometry.call( this );
  19091. this.radiusTop = radiusTop = radiusTop !== undefined ? radiusTop : 20;
  19092. this.radiusBottom = radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  19093. this.height = height = height !== undefined ? height : 100;
  19094. this.radialSegments = radialSegments = radialSegments || 8;
  19095. this.heightSegments = heightSegments = heightSegments || 1;
  19096. this.openEnded = openEnded = openEnded !== undefined ? openEnded : false;
  19097. var heightHalf = height / 2;
  19098. var x, y, vertices = [], uvs = [];
  19099. for ( y = 0; y <= heightSegments; y ++ ) {
  19100. var verticesRow = [];
  19101. var uvsRow = [];
  19102. var v = y / heightSegments;
  19103. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  19104. for ( x = 0; x <= radialSegments; x ++ ) {
  19105. var u = x / radialSegments;
  19106. var vertex = new THREE.Vector3();
  19107. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  19108. vertex.y = - v * height + heightHalf;
  19109. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  19110. this.vertices.push( vertex );
  19111. verticesRow.push( this.vertices.length - 1 );
  19112. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19113. }
  19114. vertices.push( verticesRow );
  19115. uvs.push( uvsRow );
  19116. }
  19117. var tanTheta = ( radiusBottom - radiusTop ) / height;
  19118. var na, nb;
  19119. for ( x = 0; x < radialSegments; x ++ ) {
  19120. if ( radiusTop !== 0 ) {
  19121. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  19122. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  19123. } else {
  19124. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  19125. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  19126. }
  19127. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  19128. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  19129. for ( y = 0; y < heightSegments; y ++ ) {
  19130. var v1 = vertices[ y ][ x ];
  19131. var v2 = vertices[ y + 1 ][ x ];
  19132. var v3 = vertices[ y + 1 ][ x + 1 ];
  19133. var v4 = vertices[ y ][ x + 1 ];
  19134. var n1 = na.clone();
  19135. var n2 = na.clone();
  19136. var n3 = nb.clone();
  19137. var n4 = nb.clone();
  19138. var uv1 = uvs[ y ][ x ].clone();
  19139. var uv2 = uvs[ y + 1 ][ x ].clone();
  19140. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  19141. var uv4 = uvs[ y ][ x + 1 ].clone();
  19142. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19143. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19144. }
  19145. }
  19146. // top cap
  19147. if ( openEnded === false && radiusTop > 0 ) {
  19148. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  19149. for ( x = 0; x < radialSegments; x ++ ) {
  19150. var v1 = vertices[ 0 ][ x ];
  19151. var v2 = vertices[ 0 ][ x + 1 ];
  19152. var v3 = this.vertices.length - 1;
  19153. var n1 = new THREE.Vector3( 0, 1, 0 );
  19154. var n2 = new THREE.Vector3( 0, 1, 0 );
  19155. var n3 = new THREE.Vector3( 0, 1, 0 );
  19156. var uv1 = uvs[ 0 ][ x ].clone();
  19157. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  19158. var uv3 = new THREE.Vector2( uv2.u, 0 );
  19159. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19160. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19161. }
  19162. }
  19163. // bottom cap
  19164. if ( openEnded === false && radiusBottom > 0 ) {
  19165. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  19166. for ( x = 0; x < radialSegments; x ++ ) {
  19167. var v1 = vertices[ y ][ x + 1 ];
  19168. var v2 = vertices[ y ][ x ];
  19169. var v3 = this.vertices.length - 1;
  19170. var n1 = new THREE.Vector3( 0, - 1, 0 );
  19171. var n2 = new THREE.Vector3( 0, - 1, 0 );
  19172. var n3 = new THREE.Vector3( 0, - 1, 0 );
  19173. var uv1 = uvs[ y ][ x + 1 ].clone();
  19174. var uv2 = uvs[ y ][ x ].clone();
  19175. var uv3 = new THREE.Vector2( uv2.u, 1 );
  19176. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19177. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19178. }
  19179. }
  19180. this.computeCentroids();
  19181. this.computeFaceNormals();
  19182. }
  19183. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19184. /**
  19185. * @author zz85 / http://www.lab4games.net/zz85/blog
  19186. *
  19187. * Creates extruded geometry from a path shape.
  19188. *
  19189. * parameters = {
  19190. *
  19191. * size: <float>, // size of the text
  19192. * height: <float>, // thickness to extrude text
  19193. * curveSegments: <int>, // number of points on the curves
  19194. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  19195. * amount: <int>, // Amount
  19196. *
  19197. * bevelEnabled: <bool>, // turn on bevel
  19198. * bevelThickness: <float>, // how deep into text bevel goes
  19199. * bevelSize: <float>, // how far from text outline is bevel
  19200. * bevelSegments: <int>, // number of bevel layers
  19201. *
  19202. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  19203. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  19204. *
  19205. * material: <int> // material index for front and back faces
  19206. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  19207. * uvGenerator: <Object> // object that provides UV generator functions
  19208. *
  19209. * }
  19210. **/
  19211. THREE.ExtrudeGeometry = function ( shapes, options ) {
  19212. if ( typeof( shapes ) === "undefined" ) {
  19213. shapes = [];
  19214. return;
  19215. }
  19216. THREE.Geometry.call( this );
  19217. shapes = shapes instanceof Array ? shapes : [ shapes ];
  19218. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19219. this.addShapeList( shapes, options );
  19220. this.computeCentroids();
  19221. this.computeFaceNormals();
  19222. // can't really use automatic vertex normals
  19223. // as then front and back sides get smoothed too
  19224. // should do separate smoothing just for sides
  19225. //this.computeVertexNormals();
  19226. //console.log( "took", ( Date.now() - startTime ) );
  19227. };
  19228. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19229. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19230. var sl = shapes.length;
  19231. for ( var s = 0; s < sl; s ++ ) {
  19232. var shape = shapes[ s ];
  19233. this.addShape( shape, options );
  19234. }
  19235. };
  19236. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  19237. var amount = options.amount !== undefined ? options.amount : 100;
  19238. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  19239. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  19240. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  19241. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  19242. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19243. var steps = options.steps !== undefined ? options.steps : 1;
  19244. var extrudePath = options.extrudePath;
  19245. var extrudePts, extrudeByPath = false;
  19246. var material = options.material;
  19247. var extrudeMaterial = options.extrudeMaterial;
  19248. // Use default WorldUVGenerator if no UV generators are specified.
  19249. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  19250. var shapebb = this.shapebb;
  19251. //shapebb = shape.getBoundingBox();
  19252. var splineTube, binormal, normal, position2;
  19253. if ( extrudePath ) {
  19254. extrudePts = extrudePath.getSpacedPoints( steps );
  19255. extrudeByPath = true;
  19256. bevelEnabled = false; // bevels not supported for path extrusion
  19257. // SETUP TNB variables
  19258. // Reuse TNB from TubeGeomtry for now.
  19259. // TODO1 - have a .isClosed in spline?
  19260. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  19261. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  19262. binormal = new THREE.Vector3();
  19263. normal = new THREE.Vector3();
  19264. position2 = new THREE.Vector3();
  19265. }
  19266. // Safeguards if bevels are not enabled
  19267. if ( ! bevelEnabled ) {
  19268. bevelSegments = 0;
  19269. bevelThickness = 0;
  19270. bevelSize = 0;
  19271. }
  19272. // Variables initalization
  19273. var ahole, h, hl; // looping of holes
  19274. var scope = this;
  19275. var bevelPoints = [];
  19276. var shapesOffset = this.vertices.length;
  19277. var shapePoints = shape.extractPoints( curveSegments );
  19278. var vertices = shapePoints.shape;
  19279. var holes = shapePoints.holes;
  19280. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  19281. if ( reverse ) {
  19282. vertices = vertices.reverse();
  19283. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  19284. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19285. ahole = holes[ h ];
  19286. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  19287. holes[ h ] = ahole.reverse();
  19288. }
  19289. }
  19290. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  19291. }
  19292. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  19293. /* Vertices */
  19294. var contour = vertices; // vertices has all points but contour has only points of circumference
  19295. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19296. ahole = holes[ h ];
  19297. vertices = vertices.concat( ahole );
  19298. }
  19299. function scalePt2 ( pt, vec, size ) {
  19300. if ( !vec ) console.log( "die" );
  19301. return vec.clone().multiplyScalar( size ).add( pt );
  19302. }
  19303. var b, bs, t, z,
  19304. vert, vlen = vertices.length,
  19305. face, flen = faces.length,
  19306. cont, clen = contour.length;
  19307. // Find directions for point movement
  19308. var RAD_TO_DEGREES = 180 / Math.PI;
  19309. function getBevelVec( pt_i, pt_j, pt_k ) {
  19310. // Algorithm 2
  19311. return getBevelVec2( pt_i, pt_j, pt_k );
  19312. }
  19313. function getBevelVec1( pt_i, pt_j, pt_k ) {
  19314. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  19315. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  19316. if ( anglea > angleb ) {
  19317. angleb += Math.PI * 2;
  19318. }
  19319. var anglec = ( anglea + angleb ) / 2;
  19320. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  19321. var x = - Math.cos( anglec );
  19322. var y = - Math.sin( anglec );
  19323. var vec = new THREE.Vector2( x, y ); //.normalize();
  19324. return vec;
  19325. }
  19326. function getBevelVec2( pt_i, pt_j, pt_k ) {
  19327. var a = THREE.ExtrudeGeometry.__v1,
  19328. b = THREE.ExtrudeGeometry.__v2,
  19329. v_hat = THREE.ExtrudeGeometry.__v3,
  19330. w_hat = THREE.ExtrudeGeometry.__v4,
  19331. p = THREE.ExtrudeGeometry.__v5,
  19332. q = THREE.ExtrudeGeometry.__v6,
  19333. v, w,
  19334. v_dot_w_hat, q_sub_p_dot_w_hat,
  19335. s, intersection;
  19336. // good reading for line-line intersection
  19337. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  19338. // define a as vector j->i
  19339. // define b as vectot k->i
  19340. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  19341. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  19342. // get unit vectors
  19343. v = a.normalize();
  19344. w = b.normalize();
  19345. // normals from pt i
  19346. v_hat.set( -v.y, v.x );
  19347. w_hat.set( w.y, -w.x );
  19348. // pts from i
  19349. p.copy( pt_i ).add( v_hat );
  19350. q.copy( pt_i ).add( w_hat );
  19351. if ( p.equals( q ) ) {
  19352. //console.log("Warning: lines are straight");
  19353. return w_hat.clone();
  19354. }
  19355. // Points from j, k. helps prevents points cross overover most of the time
  19356. p.copy( pt_j ).add( v_hat );
  19357. q.copy( pt_k ).add( w_hat );
  19358. v_dot_w_hat = v.dot( w_hat );
  19359. q_sub_p_dot_w_hat = q.sub( p ).dot( w_hat );
  19360. // We should not reach these conditions
  19361. if ( v_dot_w_hat === 0 ) {
  19362. console.log( "Either infinite or no solutions!" );
  19363. if ( q_sub_p_dot_w_hat === 0 ) {
  19364. console.log( "Its finite solutions." );
  19365. } else {
  19366. console.log( "Too bad, no solutions." );
  19367. }
  19368. }
  19369. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  19370. if ( s < 0 ) {
  19371. // in case of emergecy, revert to algorithm 1.
  19372. return getBevelVec1( pt_i, pt_j, pt_k );
  19373. }
  19374. intersection = v.multiplyScalar( s ).add( p );
  19375. return intersection.sub( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  19376. }
  19377. var contourMovements = [];
  19378. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19379. if ( j === il ) j = 0;
  19380. if ( k === il ) k = 0;
  19381. // (j)---(i)---(k)
  19382. // console.log('i,j,k', i, j , k)
  19383. var pt_i = contour[ i ];
  19384. var pt_j = contour[ j ];
  19385. var pt_k = contour[ k ];
  19386. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  19387. }
  19388. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  19389. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19390. ahole = holes[ h ];
  19391. oneHoleMovements = [];
  19392. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  19393. if ( j === il ) j = 0;
  19394. if ( k === il ) k = 0;
  19395. // (j)---(i)---(k)
  19396. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  19397. }
  19398. holesMovements.push( oneHoleMovements );
  19399. verticesMovements = verticesMovements.concat( oneHoleMovements );
  19400. }
  19401. // Loop bevelSegments, 1 for the front, 1 for the back
  19402. for ( b = 0; b < bevelSegments; b ++ ) {
  19403. //for ( b = bevelSegments; b > 0; b -- ) {
  19404. t = b / bevelSegments;
  19405. z = bevelThickness * ( 1 - t );
  19406. //z = bevelThickness * t;
  19407. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  19408. //bs = bevelSize * t ; // linear
  19409. // contract shape
  19410. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19411. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19412. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  19413. v( vert.x, vert.y, - z );
  19414. }
  19415. // expand holes
  19416. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  19417. ahole = holes[ h ];
  19418. oneHoleMovements = holesMovements[ h ];
  19419. for ( i = 0, il = ahole.length; i < il; i++ ) {
  19420. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19421. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  19422. v( vert.x, vert.y, -z );
  19423. }
  19424. }
  19425. }
  19426. bs = bevelSize;
  19427. // Back facing vertices
  19428. for ( i = 0; i < vlen; i ++ ) {
  19429. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19430. if ( !extrudeByPath ) {
  19431. v( vert.x, vert.y, 0 );
  19432. } else {
  19433. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  19434. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  19435. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  19436. position2.copy( extrudePts[0] ).add(normal).add(binormal);
  19437. v( position2.x, position2.y, position2.z );
  19438. }
  19439. }
  19440. // Add stepped vertices...
  19441. // Including front facing vertices
  19442. var s;
  19443. for ( s = 1; s <= steps; s ++ ) {
  19444. for ( i = 0; i < vlen; i ++ ) {
  19445. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  19446. if ( !extrudeByPath ) {
  19447. v( vert.x, vert.y, amount / steps * s );
  19448. } else {
  19449. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  19450. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  19451. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  19452. position2.copy( extrudePts[s] ).add( normal ).add( binormal );
  19453. v( position2.x, position2.y, position2.z );
  19454. }
  19455. }
  19456. }
  19457. // Add bevel segments planes
  19458. //for ( b = 1; b <= bevelSegments; b ++ ) {
  19459. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  19460. t = b / bevelSegments;
  19461. z = bevelThickness * ( 1 - t );
  19462. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  19463. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  19464. // contract shape
  19465. for ( i = 0, il = contour.length; i < il; i ++ ) {
  19466. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  19467. v( vert.x, vert.y, amount + z );
  19468. }
  19469. // expand holes
  19470. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19471. ahole = holes[ h ];
  19472. oneHoleMovements = holesMovements[ h ];
  19473. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  19474. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  19475. if ( !extrudeByPath ) {
  19476. v( vert.x, vert.y, amount + z );
  19477. } else {
  19478. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  19479. }
  19480. }
  19481. }
  19482. }
  19483. /* Faces */
  19484. // Top and bottom faces
  19485. buildLidFaces();
  19486. // Sides faces
  19487. buildSideFaces();
  19488. ///// Internal functions
  19489. function buildLidFaces() {
  19490. if ( bevelEnabled ) {
  19491. var layer = 0 ; // steps + 1
  19492. var offset = vlen * layer;
  19493. // Bottom faces
  19494. for ( i = 0; i < flen; i ++ ) {
  19495. face = faces[ i ];
  19496. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  19497. }
  19498. layer = steps + bevelSegments * 2;
  19499. offset = vlen * layer;
  19500. // Top faces
  19501. for ( i = 0; i < flen; i ++ ) {
  19502. face = faces[ i ];
  19503. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  19504. }
  19505. } else {
  19506. // Bottom faces
  19507. for ( i = 0; i < flen; i++ ) {
  19508. face = faces[ i ];
  19509. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  19510. }
  19511. // Top faces
  19512. for ( i = 0; i < flen; i ++ ) {
  19513. face = faces[ i ];
  19514. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  19515. }
  19516. }
  19517. }
  19518. // Create faces for the z-sides of the shape
  19519. function buildSideFaces() {
  19520. var layeroffset = 0;
  19521. sidewalls( contour, layeroffset );
  19522. layeroffset += contour.length;
  19523. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  19524. ahole = holes[ h ];
  19525. sidewalls( ahole, layeroffset );
  19526. //, true
  19527. layeroffset += ahole.length;
  19528. }
  19529. }
  19530. function sidewalls( contour, layeroffset ) {
  19531. var j, k;
  19532. i = contour.length;
  19533. while ( --i >= 0 ) {
  19534. j = i;
  19535. k = i - 1;
  19536. if ( k < 0 ) k = contour.length - 1;
  19537. //console.log('b', i,j, i-1, k,vertices.length);
  19538. var s = 0, sl = steps + bevelSegments * 2;
  19539. for ( s = 0; s < sl; s ++ ) {
  19540. var slen1 = vlen * s;
  19541. var slen2 = vlen * ( s + 1 );
  19542. var a = layeroffset + j + slen1,
  19543. b = layeroffset + k + slen1,
  19544. c = layeroffset + k + slen2,
  19545. d = layeroffset + j + slen2;
  19546. f4( a, b, c, d, contour, s, sl, j, k );
  19547. }
  19548. }
  19549. }
  19550. function v( x, y, z ) {
  19551. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  19552. }
  19553. function f3( a, b, c, isBottom ) {
  19554. a += shapesOffset;
  19555. b += shapesOffset;
  19556. c += shapesOffset;
  19557. // normal, color, material
  19558. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19559. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  19560. scope.faceVertexUvs[ 0 ].push( uvs );
  19561. }
  19562. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  19563. a += shapesOffset;
  19564. b += shapesOffset;
  19565. c += shapesOffset;
  19566. d += shapesOffset;
  19567. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  19568. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19569. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19570. scope.faceVertexUvs[ 0 ].push( uvs );
  19571. }
  19572. };
  19573. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19574. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19575. var ax = geometry.vertices[ indexA ].x,
  19576. ay = geometry.vertices[ indexA ].y,
  19577. bx = geometry.vertices[ indexB ].x,
  19578. by = geometry.vertices[ indexB ].y,
  19579. cx = geometry.vertices[ indexC ].x,
  19580. cy = geometry.vertices[ indexC ].y;
  19581. return [
  19582. new THREE.Vector2( ax, ay ),
  19583. new THREE.Vector2( bx, by ),
  19584. new THREE.Vector2( cx, cy )
  19585. ];
  19586. },
  19587. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19588. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19589. },
  19590. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19591. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19592. contourIndex1, contourIndex2 ) {
  19593. var ax = geometry.vertices[ indexA ].x,
  19594. ay = geometry.vertices[ indexA ].y,
  19595. az = geometry.vertices[ indexA ].z,
  19596. bx = geometry.vertices[ indexB ].x,
  19597. by = geometry.vertices[ indexB ].y,
  19598. bz = geometry.vertices[ indexB ].z,
  19599. cx = geometry.vertices[ indexC ].x,
  19600. cy = geometry.vertices[ indexC ].y,
  19601. cz = geometry.vertices[ indexC ].z,
  19602. dx = geometry.vertices[ indexD ].x,
  19603. dy = geometry.vertices[ indexD ].y,
  19604. dz = geometry.vertices[ indexD ].z;
  19605. if ( Math.abs( ay - by ) < 0.01 ) {
  19606. return [
  19607. new THREE.Vector2( ax, 1 - az ),
  19608. new THREE.Vector2( bx, 1 - bz ),
  19609. new THREE.Vector2( cx, 1 - cz ),
  19610. new THREE.Vector2( dx, 1 - dz )
  19611. ];
  19612. } else {
  19613. return [
  19614. new THREE.Vector2( ay, 1 - az ),
  19615. new THREE.Vector2( by, 1 - bz ),
  19616. new THREE.Vector2( cy, 1 - cz ),
  19617. new THREE.Vector2( dy, 1 - dz )
  19618. ];
  19619. }
  19620. }
  19621. };
  19622. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19623. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19624. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19625. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19626. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19627. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19628. /**
  19629. * @author jonobr1 / http://jonobr1.com
  19630. *
  19631. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19632. * ExtrudeGeometry.
  19633. *
  19634. * parameters = {
  19635. *
  19636. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19637. *
  19638. * material: <int> // material index for front and back faces
  19639. * uvGenerator: <Object> // object that provides UV generator functions
  19640. *
  19641. * }
  19642. **/
  19643. THREE.ShapeGeometry = function ( shapes, options ) {
  19644. THREE.Geometry.call( this );
  19645. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19646. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19647. this.addShapeList( shapes, options );
  19648. this.computeCentroids();
  19649. this.computeFaceNormals();
  19650. };
  19651. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19652. /**
  19653. * Add an array of shapes to THREE.ShapeGeometry.
  19654. */
  19655. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19656. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19657. this.addShape( shapes[ i ], options );
  19658. }
  19659. return this;
  19660. };
  19661. /**
  19662. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19663. */
  19664. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19665. if ( options === undefined ) options = {};
  19666. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19667. var material = options.material;
  19668. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19669. var shapebb = this.shapebb;
  19670. //
  19671. var i, l, hole, s;
  19672. var shapesOffset = this.vertices.length;
  19673. var shapePoints = shape.extractPoints( curveSegments );
  19674. var vertices = shapePoints.shape;
  19675. var holes = shapePoints.holes;
  19676. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19677. if ( reverse ) {
  19678. vertices = vertices.reverse();
  19679. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19680. for ( i = 0, l = holes.length; i < l; i++ ) {
  19681. hole = holes[ i ];
  19682. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19683. holes[ i ] = hole.reverse();
  19684. }
  19685. }
  19686. reverse = false;
  19687. }
  19688. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19689. // Vertices
  19690. var contour = vertices;
  19691. for ( i = 0, l = holes.length; i < l; i++ ) {
  19692. hole = holes[ i ];
  19693. vertices = vertices.concat( hole );
  19694. }
  19695. //
  19696. var vert, vlen = vertices.length;
  19697. var face, flen = faces.length;
  19698. var cont, clen = contour.length;
  19699. for ( i = 0; i < vlen; i++ ) {
  19700. vert = vertices[ i ];
  19701. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19702. }
  19703. for ( i = 0; i < flen; i++ ) {
  19704. face = faces[ i ];
  19705. var a = face[ 0 ] + shapesOffset;
  19706. var b = face[ 1 ] + shapesOffset;
  19707. var c = face[ 2 ] + shapesOffset;
  19708. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19709. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19710. }
  19711. };
  19712. /**
  19713. * @author astrodud / http://astrodud.isgreat.org/
  19714. * @author zz85 / https://github.com/zz85
  19715. * @author bhouston / http://exocortex.com
  19716. */
  19717. // points - to create a closed torus, one must use a set of points
  19718. // like so: [ a, b, c, d, a ], see first is the same as last.
  19719. // segments - the number of circumference segments to create
  19720. // phiStart - the starting radian
  19721. // phiLength - the radian (0 to 2*PI) range of the lathed section
  19722. // 2*pi is a closed lathe, less than 2PI is a portion.
  19723. THREE.LatheGeometry = function ( points, segments, phiStart, phiLength ) {
  19724. THREE.Geometry.call( this );
  19725. segments = segments || 12;
  19726. phiStart = phiStart || 0;
  19727. phiLength = phiLength || 2 * Math.PI;
  19728. var inversePointLength = 1.0 / ( points.length - 1 );
  19729. var inverseSegments = 1.0 / segments;
  19730. for ( var i = 0, il = segments; i <= il; i ++ ) {
  19731. var phi = phiStart + i * inverseSegments * phiLength;
  19732. var c = Math.cos( phi ),
  19733. s = Math.sin( phi );
  19734. for ( var j = 0, jl = points.length; j < jl; j ++ ) {
  19735. var pt = points[ j ];
  19736. var vertex = new THREE.Vector3();
  19737. vertex.x = c * pt.x - s * pt.y;
  19738. vertex.y = s * pt.x + c * pt.y;
  19739. vertex.z = pt.z;
  19740. this.vertices.push( vertex );
  19741. }
  19742. }
  19743. var np = points.length;
  19744. for ( var i = 0, il = segments; i < il; i ++ ) {
  19745. for ( var j = 0, jl = points.length - 1; j < jl; j ++ ) {
  19746. var base = j + np * i;
  19747. var a = base;
  19748. var b = base + np;
  19749. var c = base + 1 + np;
  19750. var d = base + 1;
  19751. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19752. var u0 = i * inverseSegments;
  19753. var v0 = j * inversePointLength;
  19754. var u1 = u0 + inverseSegments;
  19755. var v1 = v0 + inversePointLength;
  19756. this.faceVertexUvs[ 0 ].push( [
  19757. new THREE.Vector2( u0, v0 ),
  19758. new THREE.Vector2( u1, v0 ),
  19759. new THREE.Vector2( u1, v1 ),
  19760. new THREE.Vector2( u0, v1 )
  19761. ] );
  19762. }
  19763. }
  19764. this.mergeVertices();
  19765. this.computeCentroids();
  19766. this.computeFaceNormals();
  19767. this.computeVertexNormals();
  19768. };
  19769. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19770. /**
  19771. * @author mrdoob / http://mrdoob.com/
  19772. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19773. */
  19774. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19775. THREE.Geometry.call( this );
  19776. this.width = width;
  19777. this.height = height;
  19778. this.widthSegments = widthSegments || 1;
  19779. this.heightSegments = heightSegments || 1;
  19780. var ix, iz;
  19781. var width_half = width / 2;
  19782. var height_half = height / 2;
  19783. var gridX = this.widthSegments;
  19784. var gridZ = this.heightSegments;
  19785. var gridX1 = gridX + 1;
  19786. var gridZ1 = gridZ + 1;
  19787. var segment_width = this.width / gridX;
  19788. var segment_height = this.height / gridZ;
  19789. var normal = new THREE.Vector3( 0, 0, 1 );
  19790. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19791. for ( ix = 0; ix < gridX1; ix ++ ) {
  19792. var x = ix * segment_width - width_half;
  19793. var y = iz * segment_height - height_half;
  19794. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19795. }
  19796. }
  19797. for ( iz = 0; iz < gridZ; iz ++ ) {
  19798. for ( ix = 0; ix < gridX; ix ++ ) {
  19799. var a = ix + gridX1 * iz;
  19800. var b = ix + gridX1 * ( iz + 1 );
  19801. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19802. var d = ( ix + 1 ) + gridX1 * iz;
  19803. var face = new THREE.Face4( a, b, c, d );
  19804. face.normal.copy( normal );
  19805. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19806. this.faces.push( face );
  19807. this.faceVertexUvs[ 0 ].push( [
  19808. new THREE.Vector2( ix / gridX, 1 - iz / gridZ ),
  19809. new THREE.Vector2( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19810. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19811. new THREE.Vector2( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19812. ] );
  19813. }
  19814. }
  19815. this.computeCentroids();
  19816. };
  19817. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19818. /**
  19819. * @author Kaleb Murphy
  19820. */
  19821. THREE.RingGeometry = function ( innerRadius, outerRadius, thetaSegments, phiSegments, thetaStart, thetaLength ) {
  19822. THREE.Geometry.call( this );
  19823. innerRadius = innerRadius || 0;
  19824. outerRadius = outerRadius || 50;
  19825. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19826. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  19827. thetaSegments = thetaSegments !== undefined ? Math.max( 3, thetaSegments ) : 8;
  19828. phiSegments = phiSegments !== undefined ? Math.max( 3, phiSegments ) : 8;
  19829. var i, o, uvs = [], radius = innerRadius, radiusStep = ( ( outerRadius - innerRadius ) / phiSegments );
  19830. for ( i = 0; i <= phiSegments; i ++ ) { // concentric circles inside ring
  19831. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19832. var vertex = new THREE.Vector3();
  19833. var segment = thetaStart + o / thetaSegments * thetaLength;
  19834. vertex.x = radius * Math.cos( segment );
  19835. vertex.y = radius * Math.sin( segment );
  19836. this.vertices.push( vertex );
  19837. uvs.push( new THREE.Vector2( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  19838. }
  19839. radius += radiusStep;
  19840. }
  19841. var n = new THREE.Vector3( 0, 0, 1 );
  19842. for ( i = 0; i < phiSegments; i ++ ) { // concentric circles inside ring
  19843. var thetaSegment = i * thetaSegments;
  19844. for ( o = 0; o <= thetaSegments; o ++ ) { // number of segments per circle
  19845. var segment = o + thetaSegment;
  19846. var v1 = segment + i;
  19847. var v2 = segment + thetaSegments + i;
  19848. var v3 = segment + thetaSegments + 1 + i;
  19849. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19850. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19851. v1 = segment + i;
  19852. v2 = segment + thetaSegments + 1 + i;
  19853. v3 = segment + 1 + i;
  19854. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  19855. this.faceVertexUvs[ 0 ].push( [ uvs[ v1 ], uvs[ v2 ], uvs[ v3 ] ]);
  19856. }
  19857. }
  19858. this.computeCentroids();
  19859. this.computeFaceNormals();
  19860. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19861. };
  19862. THREE.RingGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19863. /**
  19864. * @author mrdoob / http://mrdoob.com/
  19865. */
  19866. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19867. THREE.Geometry.call( this );
  19868. this.radius = radius = radius || 50;
  19869. this.widthSegments = widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19870. this.heightSegments = heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19871. this.phiStart = phiStart = phiStart !== undefined ? phiStart : 0;
  19872. this.phiLength = phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19873. this.thetaStart = thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19874. this.thetaLength = thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19875. var x, y, vertices = [], uvs = [];
  19876. for ( y = 0; y <= heightSegments; y ++ ) {
  19877. var verticesRow = [];
  19878. var uvsRow = [];
  19879. for ( x = 0; x <= widthSegments; x ++ ) {
  19880. var u = x / widthSegments;
  19881. var v = y / heightSegments;
  19882. var vertex = new THREE.Vector3();
  19883. vertex.x = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19884. vertex.y = radius * Math.cos( thetaStart + v * thetaLength );
  19885. vertex.z = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19886. this.vertices.push( vertex );
  19887. verticesRow.push( this.vertices.length - 1 );
  19888. uvsRow.push( new THREE.Vector2( u, 1 - v ) );
  19889. }
  19890. vertices.push( verticesRow );
  19891. uvs.push( uvsRow );
  19892. }
  19893. for ( y = 0; y < this.heightSegments; y ++ ) {
  19894. for ( x = 0; x < this.widthSegments; x ++ ) {
  19895. var v1 = vertices[ y ][ x + 1 ];
  19896. var v2 = vertices[ y ][ x ];
  19897. var v3 = vertices[ y + 1 ][ x ];
  19898. var v4 = vertices[ y + 1 ][ x + 1 ];
  19899. var n1 = this.vertices[ v1 ].clone().normalize();
  19900. var n2 = this.vertices[ v2 ].clone().normalize();
  19901. var n3 = this.vertices[ v3 ].clone().normalize();
  19902. var n4 = this.vertices[ v4 ].clone().normalize();
  19903. var uv1 = uvs[ y ][ x + 1 ].clone();
  19904. var uv2 = uvs[ y ][ x ].clone();
  19905. var uv3 = uvs[ y + 1 ][ x ].clone();
  19906. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19907. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19908. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19909. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19910. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19911. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19912. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19913. } else {
  19914. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19915. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19916. }
  19917. }
  19918. }
  19919. this.computeCentroids();
  19920. this.computeFaceNormals();
  19921. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  19922. };
  19923. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19924. /**
  19925. * @author zz85 / http://www.lab4games.net/zz85/blog
  19926. * @author alteredq / http://alteredqualia.com/
  19927. *
  19928. * For creating 3D text geometry in three.js
  19929. *
  19930. * Text = 3D Text
  19931. *
  19932. * parameters = {
  19933. * size: <float>, // size of the text
  19934. * height: <float>, // thickness to extrude text
  19935. * curveSegments: <int>, // number of points on the curves
  19936. *
  19937. * font: <string>, // font name
  19938. * weight: <string>, // font weight (normal, bold)
  19939. * style: <string>, // font style (normal, italics)
  19940. *
  19941. * bevelEnabled: <bool>, // turn on bevel
  19942. * bevelThickness: <float>, // how deep into text bevel goes
  19943. * bevelSize: <float>, // how far from text outline is bevel
  19944. * }
  19945. *
  19946. */
  19947. /* Usage Examples
  19948. // TextGeometry wrapper
  19949. var text3d = new TextGeometry( text, options );
  19950. // Complete manner
  19951. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19952. var text3d = new ExtrudeGeometry( textShapes, options );
  19953. */
  19954. THREE.TextGeometry = function ( text, parameters ) {
  19955. parameters = parameters || {};
  19956. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19957. // translate parameters to ExtrudeGeometry API
  19958. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19959. // defaults
  19960. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19961. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19962. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19963. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19964. };
  19965. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19966. /**
  19967. * @author oosmoxiecode
  19968. * @author mrdoob / http://mrdoob.com/
  19969. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19970. */
  19971. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19972. THREE.Geometry.call( this );
  19973. var scope = this;
  19974. this.radius = radius || 100;
  19975. this.tube = tube || 40;
  19976. this.radialSegments = radialSegments || 8;
  19977. this.tubularSegments = tubularSegments || 6;
  19978. this.arc = arc || Math.PI * 2;
  19979. var center = new THREE.Vector3(), uvs = [], normals = [];
  19980. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19981. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19982. var u = i / this.tubularSegments * this.arc;
  19983. var v = j / this.radialSegments * Math.PI * 2;
  19984. center.x = this.radius * Math.cos( u );
  19985. center.y = this.radius * Math.sin( u );
  19986. var vertex = new THREE.Vector3();
  19987. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19988. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19989. vertex.z = this.tube * Math.sin( v );
  19990. this.vertices.push( vertex );
  19991. uvs.push( new THREE.Vector2( i / this.tubularSegments, j / this.radialSegments ) );
  19992. normals.push( vertex.clone().sub( center ).normalize() );
  19993. }
  19994. }
  19995. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19996. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19997. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19998. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19999. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  20000. var d = ( this.tubularSegments + 1 ) * j + i;
  20001. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  20002. face.normal.add( normals[ a ] );
  20003. face.normal.add( normals[ b ] );
  20004. face.normal.add( normals[ c ] );
  20005. face.normal.add( normals[ d ] );
  20006. face.normal.normalize();
  20007. this.faces.push( face );
  20008. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  20009. }
  20010. }
  20011. this.computeCentroids();
  20012. };
  20013. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20014. /**
  20015. * @author oosmoxiecode
  20016. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20017. */
  20018. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  20019. THREE.Geometry.call( this );
  20020. var scope = this;
  20021. this.radius = radius || 100;
  20022. this.tube = tube || 40;
  20023. this.radialSegments = radialSegments || 64;
  20024. this.tubularSegments = tubularSegments || 8;
  20025. this.p = p || 2;
  20026. this.q = q || 3;
  20027. this.heightScale = heightScale || 1;
  20028. this.grid = new Array( this.radialSegments );
  20029. var tang = new THREE.Vector3();
  20030. var n = new THREE.Vector3();
  20031. var bitan = new THREE.Vector3();
  20032. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20033. this.grid[ i ] = new Array( this.tubularSegments );
  20034. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  20035. var p1 = getPos( u, this.q, this.p, this.radius, this.heightScale );
  20036. var p2 = getPos( u + 0.01, this.q, this.p, this.radius, this.heightScale );
  20037. tang.subVectors( p2, p1 );
  20038. n.addVectors( p2, p1 );
  20039. bitan.crossVectors( tang, n );
  20040. n.crossVectors( bitan, tang );
  20041. bitan.normalize();
  20042. n.normalize();
  20043. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20044. var v = j / this.tubularSegments * 2 * Math.PI;
  20045. var cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20046. var cy = this.tube * Math.sin( v );
  20047. var pos = new THREE.Vector3();
  20048. pos.x = p1.x + cx * n.x + cy * bitan.x;
  20049. pos.y = p1.y + cx * n.y + cy * bitan.y;
  20050. pos.z = p1.z + cx * n.z + cy * bitan.z;
  20051. this.grid[ i ][ j ] = scope.vertices.push( pos ) - 1;
  20052. }
  20053. }
  20054. for ( var i = 0; i < this.radialSegments; ++ i ) {
  20055. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  20056. var ip = ( i + 1 ) % this.radialSegments;
  20057. var jp = ( j + 1 ) % this.tubularSegments;
  20058. var a = this.grid[ i ][ j ];
  20059. var b = this.grid[ ip ][ j ];
  20060. var c = this.grid[ ip ][ jp ];
  20061. var d = this.grid[ i ][ jp ];
  20062. var uva = new THREE.Vector2( i / this.radialSegments, j / this.tubularSegments );
  20063. var uvb = new THREE.Vector2( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  20064. var uvc = new THREE.Vector2( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20065. var uvd = new THREE.Vector2( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  20066. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20067. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  20068. }
  20069. }
  20070. this.computeCentroids();
  20071. this.computeFaceNormals();
  20072. this.computeVertexNormals();
  20073. function getPos( u, in_q, in_p, radius, heightScale ) {
  20074. var cu = Math.cos( u );
  20075. var su = Math.sin( u );
  20076. var quOverP = in_q / in_p * u;
  20077. var cs = Math.cos( quOverP );
  20078. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  20079. var ty = radius * ( 2 + cs ) * su * 0.5;
  20080. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  20081. return new THREE.Vector3( tx, ty, tz );
  20082. }
  20083. };
  20084. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20085. /**
  20086. * @author WestLangley / https://github.com/WestLangley
  20087. * @author zz85 / https://github.com/zz85
  20088. * @author miningold / https://github.com/miningold
  20089. *
  20090. * Modified from the TorusKnotGeometry by @oosmoxiecode
  20091. *
  20092. * Creates a tube which extrudes along a 3d spline
  20093. *
  20094. * Uses parallel transport frames as described in
  20095. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  20096. */
  20097. THREE.TubeGeometry = function( path, segments, radius, radialSegments, closed ) {
  20098. THREE.Geometry.call( this );
  20099. this.path = path;
  20100. this.segments = segments || 64;
  20101. this.radius = radius || 1;
  20102. this.radialSegments = radialSegments || 8;
  20103. this.closed = closed || false;
  20104. this.grid = [];
  20105. var scope = this,
  20106. tangent,
  20107. normal,
  20108. binormal,
  20109. numpoints = this.segments + 1,
  20110. x, y, z,
  20111. tx, ty, tz,
  20112. u, v,
  20113. cx, cy,
  20114. pos, pos2 = new THREE.Vector3(),
  20115. i, j,
  20116. ip, jp,
  20117. a, b, c, d,
  20118. uva, uvb, uvc, uvd;
  20119. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  20120. tangents = frames.tangents,
  20121. normals = frames.normals,
  20122. binormals = frames.binormals;
  20123. // proxy internals
  20124. this.tangents = tangents;
  20125. this.normals = normals;
  20126. this.binormals = binormals;
  20127. function vert( x, y, z ) {
  20128. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  20129. }
  20130. // consruct the grid
  20131. for ( i = 0; i < numpoints; i++ ) {
  20132. this.grid[ i ] = [];
  20133. u = i / ( numpoints - 1 );
  20134. pos = path.getPointAt( u );
  20135. tangent = tangents[ i ];
  20136. normal = normals[ i ];
  20137. binormal = binormals[ i ];
  20138. for ( j = 0; j < this.radialSegments; j++ ) {
  20139. v = j / this.radialSegments * 2 * Math.PI;
  20140. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  20141. cy = this.radius * Math.sin( v );
  20142. pos2.copy( pos );
  20143. pos2.x += cx * normal.x + cy * binormal.x;
  20144. pos2.y += cx * normal.y + cy * binormal.y;
  20145. pos2.z += cx * normal.z + cy * binormal.z;
  20146. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  20147. }
  20148. }
  20149. // construct the mesh
  20150. for ( i = 0; i < this.segments; i++ ) {
  20151. for ( j = 0; j < this.radialSegments; j++ ) {
  20152. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  20153. jp = (j + 1) % this.radialSegments;
  20154. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  20155. b = this.grid[ ip ][ j ];
  20156. c = this.grid[ ip ][ jp ];
  20157. d = this.grid[ i ][ jp ];
  20158. uva = new THREE.Vector2( i / this.segments, j / this.radialSegments );
  20159. uvb = new THREE.Vector2( ( i + 1 ) / this.segments, j / this.radialSegments );
  20160. uvc = new THREE.Vector2( ( i + 1 ) / this.segments, ( j + 1 ) / this.radialSegments );
  20161. uvd = new THREE.Vector2( i / this.segments, ( j + 1 ) / this.radialSegments );
  20162. this.faces.push( new THREE.Face4( a, b, c, d ) );
  20163. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  20164. }
  20165. }
  20166. this.computeCentroids();
  20167. this.computeFaceNormals();
  20168. this.computeVertexNormals();
  20169. };
  20170. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20171. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  20172. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  20173. var tangent = new THREE.Vector3(),
  20174. normal = new THREE.Vector3(),
  20175. binormal = new THREE.Vector3(),
  20176. tangents = [],
  20177. normals = [],
  20178. binormals = [],
  20179. vec = new THREE.Vector3(),
  20180. mat = new THREE.Matrix4(),
  20181. numpoints = segments + 1,
  20182. theta,
  20183. epsilon = 0.0001,
  20184. smallest,
  20185. tx, ty, tz,
  20186. i, u, v;
  20187. // expose internals
  20188. this.tangents = tangents;
  20189. this.normals = normals;
  20190. this.binormals = binormals;
  20191. // compute the tangent vectors for each segment on the path
  20192. for ( i = 0; i < numpoints; i++ ) {
  20193. u = i / ( numpoints - 1 );
  20194. tangents[ i ] = path.getTangentAt( u );
  20195. tangents[ i ].normalize();
  20196. }
  20197. initialNormal3();
  20198. function initialNormal1(lastBinormal) {
  20199. // fixed start binormal. Has dangers of 0 vectors
  20200. normals[ 0 ] = new THREE.Vector3();
  20201. binormals[ 0 ] = new THREE.Vector3();
  20202. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  20203. normals[ 0 ].crossVectors( lastBinormal, tangents[ 0 ] ).normalize();
  20204. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20205. }
  20206. function initialNormal2() {
  20207. // This uses the Frenet-Serret formula for deriving binormal
  20208. var t2 = path.getTangentAt( epsilon );
  20209. normals[ 0 ] = new THREE.Vector3().subVectors( t2, tangents[ 0 ] ).normalize();
  20210. binormals[ 0 ] = new THREE.Vector3().crossVectors( tangents[ 0 ], normals[ 0 ] );
  20211. normals[ 0 ].crossVectors( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  20212. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] ).normalize();
  20213. }
  20214. function initialNormal3() {
  20215. // select an initial normal vector perpenicular to the first tangent vector,
  20216. // and in the direction of the smallest tangent xyz component
  20217. normals[ 0 ] = new THREE.Vector3();
  20218. binormals[ 0 ] = new THREE.Vector3();
  20219. smallest = Number.MAX_VALUE;
  20220. tx = Math.abs( tangents[ 0 ].x );
  20221. ty = Math.abs( tangents[ 0 ].y );
  20222. tz = Math.abs( tangents[ 0 ].z );
  20223. if ( tx <= smallest ) {
  20224. smallest = tx;
  20225. normal.set( 1, 0, 0 );
  20226. }
  20227. if ( ty <= smallest ) {
  20228. smallest = ty;
  20229. normal.set( 0, 1, 0 );
  20230. }
  20231. if ( tz <= smallest ) {
  20232. normal.set( 0, 0, 1 );
  20233. }
  20234. vec.crossVectors( tangents[ 0 ], normal ).normalize();
  20235. normals[ 0 ].crossVectors( tangents[ 0 ], vec );
  20236. binormals[ 0 ].crossVectors( tangents[ 0 ], normals[ 0 ] );
  20237. }
  20238. // compute the slowly-varying normal and binormal vectors for each segment on the path
  20239. for ( i = 1; i < numpoints; i++ ) {
  20240. normals[ i ] = normals[ i-1 ].clone();
  20241. binormals[ i ] = binormals[ i-1 ].clone();
  20242. vec.crossVectors( tangents[ i-1 ], tangents[ i ] );
  20243. if ( vec.length() > epsilon ) {
  20244. vec.normalize();
  20245. theta = Math.acos( THREE.Math.clamp( tangents[ i-1 ].dot( tangents[ i ] ), -1, 1 ) ); // clamp for floating pt errors
  20246. normals[ i ].applyMatrix4( mat.makeRotationAxis( vec, theta ) );
  20247. }
  20248. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20249. }
  20250. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  20251. if ( closed ) {
  20252. theta = Math.acos( THREE.Math.clamp( normals[ 0 ].dot( normals[ numpoints-1 ] ), -1, 1 ) );
  20253. theta /= ( numpoints - 1 );
  20254. if ( tangents[ 0 ].dot( vec.crossVectors( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  20255. theta = -theta;
  20256. }
  20257. for ( i = 1; i < numpoints; i++ ) {
  20258. // twist a little...
  20259. normals[ i ].applyMatrix4( mat.makeRotationAxis( tangents[ i ], theta * i ) );
  20260. binormals[ i ].crossVectors( tangents[ i ], normals[ i ] );
  20261. }
  20262. }
  20263. };
  20264. /**
  20265. * @author clockworkgeek / https://github.com/clockworkgeek
  20266. * @author timothypratley / https://github.com/timothypratley
  20267. * @author WestLangley / http://github.com/WestLangley
  20268. */
  20269. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  20270. THREE.Geometry.call( this );
  20271. radius = radius || 1;
  20272. detail = detail || 0;
  20273. var that = this;
  20274. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  20275. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  20276. }
  20277. var midpoints = [], p = this.vertices;
  20278. var f = [];
  20279. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20280. var v1 = p[ faces[ i ][ 0 ] ];
  20281. var v2 = p[ faces[ i ][ 1 ] ];
  20282. var v3 = p[ faces[ i ][ 2 ] ];
  20283. f[ i ] = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20284. }
  20285. for ( var i = 0, l = f.length; i < l; i ++ ) {
  20286. subdivide(f[ i ], detail);
  20287. }
  20288. // Handle case when face straddles the seam
  20289. for ( var i = 0, l = this.faceVertexUvs[ 0 ].length; i < l; i ++ ) {
  20290. var uvs = this.faceVertexUvs[ 0 ][ i ];
  20291. var x0 = uvs[ 0 ].x;
  20292. var x1 = uvs[ 1 ].x;
  20293. var x2 = uvs[ 2 ].x;
  20294. var max = Math.max( x0, Math.max( x1, x2 ) );
  20295. var min = Math.min( x0, Math.min( x1, x2 ) );
  20296. if ( max > 0.9 && min < 0.1 ) { // 0.9 is somewhat arbitrary
  20297. if ( x0 < 0.2 ) uvs[ 0 ].x += 1;
  20298. if ( x1 < 0.2 ) uvs[ 1 ].x += 1;
  20299. if ( x2 < 0.2 ) uvs[ 2 ].x += 1;
  20300. }
  20301. }
  20302. // Apply radius
  20303. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  20304. this.vertices[ i ].multiplyScalar( radius );
  20305. }
  20306. // Merge vertices
  20307. this.mergeVertices();
  20308. this.computeCentroids();
  20309. this.computeFaceNormals();
  20310. this.boundingSphere = new THREE.Sphere( new THREE.Vector3(), radius );
  20311. // Project vector onto sphere's surface
  20312. function prepare( vector ) {
  20313. var vertex = vector.normalize().clone();
  20314. vertex.index = that.vertices.push( vertex ) - 1;
  20315. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  20316. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  20317. var v = inclination( vector ) / Math.PI + 0.5;
  20318. vertex.uv = new THREE.Vector2( u, 1 - v );
  20319. return vertex;
  20320. }
  20321. // Approximate a curved face with recursively sub-divided triangles.
  20322. function make( v1, v2, v3 ) {
  20323. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  20324. face.centroid.add( v1 ).add( v2 ).add( v3 ).divideScalar( 3 );
  20325. that.faces.push( face );
  20326. var azi = azimuth( face.centroid );
  20327. that.faceVertexUvs[ 0 ].push( [
  20328. correctUV( v1.uv, v1, azi ),
  20329. correctUV( v2.uv, v2, azi ),
  20330. correctUV( v3.uv, v3, azi )
  20331. ] );
  20332. }
  20333. // Analytically subdivide a face to the required detail level.
  20334. function subdivide(face, detail ) {
  20335. var cols = Math.pow(2, detail);
  20336. var cells = Math.pow(4, detail);
  20337. var a = prepare( that.vertices[ face.a ] );
  20338. var b = prepare( that.vertices[ face.b ] );
  20339. var c = prepare( that.vertices[ face.c ] );
  20340. var v = [];
  20341. // Construct all of the vertices for this subdivision.
  20342. for ( var i = 0 ; i <= cols; i ++ ) {
  20343. v[ i ] = [];
  20344. var aj = prepare( a.clone().lerp( c, i / cols ) );
  20345. var bj = prepare( b.clone().lerp( c, i / cols ) );
  20346. var rows = cols - i;
  20347. for ( var j = 0; j <= rows; j ++) {
  20348. if ( j == 0 && i == cols ) {
  20349. v[ i ][ j ] = aj;
  20350. } else {
  20351. v[ i ][ j ] = prepare( aj.clone().lerp( bj, j / rows ) );
  20352. }
  20353. }
  20354. }
  20355. // Construct all of the faces.
  20356. for ( var i = 0; i < cols ; i ++ ) {
  20357. for ( var j = 0; j < 2 * (cols - i) - 1; j ++ ) {
  20358. var k = Math.floor( j / 2 );
  20359. if ( j % 2 == 0 ) {
  20360. make(
  20361. v[ i ][ k + 1],
  20362. v[ i + 1 ][ k ],
  20363. v[ i ][ k ]
  20364. );
  20365. } else {
  20366. make(
  20367. v[ i ][ k + 1 ],
  20368. v[ i + 1][ k + 1],
  20369. v[ i + 1 ][ k ]
  20370. );
  20371. }
  20372. }
  20373. }
  20374. }
  20375. // Angle around the Y axis, counter-clockwise when looking from above.
  20376. function azimuth( vector ) {
  20377. return Math.atan2( vector.z, -vector.x );
  20378. }
  20379. // Angle above the XZ plane.
  20380. function inclination( vector ) {
  20381. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  20382. }
  20383. // Texture fixing helper. Spheres have some odd behaviours.
  20384. function correctUV( uv, vector, azimuth ) {
  20385. if ( ( azimuth < 0 ) && ( uv.x === 1 ) ) uv = new THREE.Vector2( uv.x - 1, uv.y );
  20386. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.Vector2( azimuth / 2 / Math.PI + 0.5, uv.y );
  20387. return uv.clone();
  20388. }
  20389. };
  20390. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20391. /**
  20392. * @author timothypratley / https://github.com/timothypratley
  20393. */
  20394. THREE.IcosahedronGeometry = function ( radius, detail ) {
  20395. this.radius = radius;
  20396. this.detail = detail;
  20397. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  20398. var vertices = [
  20399. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  20400. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  20401. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  20402. ];
  20403. var faces = [
  20404. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  20405. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  20406. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  20407. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  20408. ];
  20409. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20410. };
  20411. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20412. /**
  20413. * @author timothypratley / https://github.com/timothypratley
  20414. */
  20415. THREE.OctahedronGeometry = function ( radius, detail ) {
  20416. var vertices = [
  20417. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  20418. ];
  20419. var faces = [
  20420. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  20421. ];
  20422. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20423. };
  20424. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20425. /**
  20426. * @author timothypratley / https://github.com/timothypratley
  20427. */
  20428. THREE.TetrahedronGeometry = function ( radius, detail ) {
  20429. var vertices = [
  20430. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  20431. ];
  20432. var faces = [
  20433. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  20434. ];
  20435. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  20436. };
  20437. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20438. /**
  20439. * @author zz85 / https://github.com/zz85
  20440. * Parametric Surfaces Geometry
  20441. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  20442. *
  20443. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  20444. *
  20445. */
  20446. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  20447. THREE.Geometry.call( this );
  20448. var verts = this.vertices;
  20449. var faces = this.faces;
  20450. var uvs = this.faceVertexUvs[ 0 ];
  20451. useTris = (useTris === undefined) ? false : useTris;
  20452. var i, il, j, p;
  20453. var u, v;
  20454. var stackCount = stacks + 1;
  20455. var sliceCount = slices + 1;
  20456. for ( i = 0; i <= stacks; i ++ ) {
  20457. v = i / stacks;
  20458. for ( j = 0; j <= slices; j ++ ) {
  20459. u = j / slices;
  20460. p = func( u, v );
  20461. verts.push( p );
  20462. }
  20463. }
  20464. var a, b, c, d;
  20465. var uva, uvb, uvc, uvd;
  20466. for ( i = 0; i < stacks; i ++ ) {
  20467. for ( j = 0; j < slices; j ++ ) {
  20468. a = i * sliceCount + j;
  20469. b = i * sliceCount + j + 1;
  20470. c = (i + 1) * sliceCount + j;
  20471. d = (i + 1) * sliceCount + j + 1;
  20472. uva = new THREE.Vector2( j / slices, i / stacks );
  20473. uvb = new THREE.Vector2( ( j + 1 ) / slices, i / stacks );
  20474. uvc = new THREE.Vector2( j / slices, ( i + 1 ) / stacks );
  20475. uvd = new THREE.Vector2( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  20476. if ( useTris ) {
  20477. faces.push( new THREE.Face3( a, b, c ) );
  20478. faces.push( new THREE.Face3( b, d, c ) );
  20479. uvs.push( [ uva, uvb, uvc ] );
  20480. uvs.push( [ uvb, uvd, uvc ] );
  20481. } else {
  20482. faces.push( new THREE.Face4( a, b, d, c ) );
  20483. uvs.push( [ uva, uvb, uvd, uvc ] );
  20484. }
  20485. }
  20486. }
  20487. // console.log(this);
  20488. // magic bullet
  20489. // var diff = this.mergeVertices();
  20490. // console.log('removed ', diff, ' vertices by merging');
  20491. this.computeCentroids();
  20492. this.computeFaceNormals();
  20493. this.computeVertexNormals();
  20494. };
  20495. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20496. /**
  20497. * @author qiao / https://github.com/qiao
  20498. * @fileoverview This is a convex hull generator using the incremental method.
  20499. * The complexity is O(n^2) where n is the number of vertices.
  20500. * O(nlogn) algorithms do exist, but they are much more complicated.
  20501. *
  20502. * Benchmark:
  20503. *
  20504. * Platform: CPU: P7350 @2.00GHz Engine: V8
  20505. *
  20506. * Num Vertices Time(ms)
  20507. *
  20508. * 10 1
  20509. * 20 3
  20510. * 30 19
  20511. * 40 48
  20512. * 50 107
  20513. */
  20514. THREE.ConvexGeometry = function( vertices ) {
  20515. THREE.Geometry.call( this );
  20516. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  20517. for ( var i = 3; i < vertices.length; i++ ) {
  20518. addPoint( i );
  20519. }
  20520. function addPoint( vertexId ) {
  20521. var vertex = vertices[ vertexId ].clone();
  20522. var mag = vertex.length();
  20523. vertex.x += mag * randomOffset();
  20524. vertex.y += mag * randomOffset();
  20525. vertex.z += mag * randomOffset();
  20526. var hole = [];
  20527. for ( var f = 0; f < faces.length; ) {
  20528. var face = faces[ f ];
  20529. // for each face, if the vertex can see it,
  20530. // then we try to add the face's edges into the hole.
  20531. if ( visible( face, vertex ) ) {
  20532. for ( var e = 0; e < 3; e++ ) {
  20533. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  20534. var boundary = true;
  20535. // remove duplicated edges.
  20536. for ( var h = 0; h < hole.length; h++ ) {
  20537. if ( equalEdge( hole[ h ], edge ) ) {
  20538. hole[ h ] = hole[ hole.length - 1 ];
  20539. hole.pop();
  20540. boundary = false;
  20541. break;
  20542. }
  20543. }
  20544. if ( boundary ) {
  20545. hole.push( edge );
  20546. }
  20547. }
  20548. // remove faces[ f ]
  20549. faces[ f ] = faces[ faces.length - 1 ];
  20550. faces.pop();
  20551. } else { // not visible
  20552. f++;
  20553. }
  20554. }
  20555. // construct the new faces formed by the edges of the hole and the vertex
  20556. for ( var h = 0; h < hole.length; h++ ) {
  20557. faces.push( [
  20558. hole[ h ][ 0 ],
  20559. hole[ h ][ 1 ],
  20560. vertexId
  20561. ] );
  20562. }
  20563. }
  20564. /**
  20565. * Whether the face is visible from the vertex
  20566. */
  20567. function visible( face, vertex ) {
  20568. var va = vertices[ face[ 0 ] ];
  20569. var vb = vertices[ face[ 1 ] ];
  20570. var vc = vertices[ face[ 2 ] ];
  20571. var n = normal( va, vb, vc );
  20572. // distance from face to origin
  20573. var dist = n.dot( va );
  20574. return n.dot( vertex ) >= dist;
  20575. }
  20576. /**
  20577. * Face normal
  20578. */
  20579. function normal( va, vb, vc ) {
  20580. var cb = new THREE.Vector3();
  20581. var ab = new THREE.Vector3();
  20582. cb.subVectors( vc, vb );
  20583. ab.subVectors( va, vb );
  20584. cb.cross( ab );
  20585. cb.normalize();
  20586. return cb;
  20587. }
  20588. /**
  20589. * Detect whether two edges are equal.
  20590. * Note that when constructing the convex hull, two same edges can only
  20591. * be of the negative direction.
  20592. */
  20593. function equalEdge( ea, eb ) {
  20594. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  20595. }
  20596. /**
  20597. * Create a random offset between -1e-6 and 1e-6.
  20598. */
  20599. function randomOffset() {
  20600. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  20601. }
  20602. /**
  20603. * XXX: Not sure if this is the correct approach. Need someone to review.
  20604. */
  20605. function vertexUv( vertex ) {
  20606. var mag = vertex.length();
  20607. return new THREE.Vector2( vertex.x / mag, vertex.y / mag );
  20608. }
  20609. // Push vertices into `this.vertices`, skipping those inside the hull
  20610. var id = 0;
  20611. var newId = new Array( vertices.length ); // map from old vertex id to new id
  20612. for ( var i = 0; i < faces.length; i++ ) {
  20613. var face = faces[ i ];
  20614. for ( var j = 0; j < 3; j++ ) {
  20615. if ( newId[ face[ j ] ] === undefined ) {
  20616. newId[ face[ j ] ] = id++;
  20617. this.vertices.push( vertices[ face[ j ] ] );
  20618. }
  20619. face[ j ] = newId[ face[ j ] ];
  20620. }
  20621. }
  20622. // Convert faces into instances of THREE.Face3
  20623. for ( var i = 0; i < faces.length; i++ ) {
  20624. this.faces.push( new THREE.Face3(
  20625. faces[ i ][ 0 ],
  20626. faces[ i ][ 1 ],
  20627. faces[ i ][ 2 ]
  20628. ) );
  20629. }
  20630. // Compute UVs
  20631. for ( var i = 0; i < this.faces.length; i++ ) {
  20632. var face = this.faces[ i ];
  20633. this.faceVertexUvs[ 0 ].push( [
  20634. vertexUv( this.vertices[ face.a ] ),
  20635. vertexUv( this.vertices[ face.b ] ),
  20636. vertexUv( this.vertices[ face.c ])
  20637. ] );
  20638. }
  20639. this.computeCentroids();
  20640. this.computeFaceNormals();
  20641. this.computeVertexNormals();
  20642. };
  20643. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  20644. /**
  20645. * @author sroucheray / http://sroucheray.org/
  20646. * @author mrdoob / http://mrdoob.com/
  20647. */
  20648. THREE.AxisHelper = function ( size ) {
  20649. size = size || 1;
  20650. var geometry = new THREE.Geometry();
  20651. geometry.vertices.push(
  20652. new THREE.Vector3(), new THREE.Vector3( size, 0, 0 ),
  20653. new THREE.Vector3(), new THREE.Vector3( 0, size, 0 ),
  20654. new THREE.Vector3(), new THREE.Vector3( 0, 0, size )
  20655. );
  20656. geometry.colors.push(
  20657. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  20658. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  20659. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  20660. );
  20661. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  20662. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20663. };
  20664. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  20665. /**
  20666. * @author WestLangley / http://github.com/WestLangley
  20667. * @author zz85 / http://github.com/zz85
  20668. * @author bhouston / http://exocortex.com
  20669. *
  20670. * Creates an arrow for visualizing directions
  20671. *
  20672. * Parameters:
  20673. * dir - Vector3
  20674. * origin - Vector3
  20675. * length - Number
  20676. * hex - color in hex value
  20677. */
  20678. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20679. // dir is assumed to be normalized
  20680. THREE.Object3D.call( this );
  20681. if ( hex === undefined ) hex = 0xffff00;
  20682. if ( length === undefined ) length = 1;
  20683. this.position = origin;
  20684. var lineGeometry = new THREE.Geometry();
  20685. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20686. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20687. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20688. this.line.matrixAutoUpdate = false;
  20689. this.add( this.line );
  20690. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20691. coneGeometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, 0.875, 0 ) );
  20692. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20693. this.cone.matrixAutoUpdate = false;
  20694. this.add( this.cone );
  20695. this.setDirection( dir );
  20696. this.setLength( length );
  20697. };
  20698. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20699. THREE.ArrowHelper.prototype.setDirection = function () {
  20700. var axis = new THREE.Vector3();
  20701. var radians;
  20702. return function ( dir ) {
  20703. // dir is assumed to be normalized
  20704. if ( dir.y > 0.99999 ) {
  20705. this.quaternion.set( 0, 0, 0, 1 );
  20706. } else if ( dir.y < - 0.99999 ) {
  20707. this.quaternion.set( 1, 0, 0, 0 );
  20708. } else {
  20709. axis.set( dir.z, 0, - dir.x ).normalize();
  20710. radians = Math.acos( dir.y );
  20711. this.quaternion.setFromAxisAngle( axis, radians );
  20712. }
  20713. };
  20714. }();
  20715. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20716. this.scale.set( length, length, length );
  20717. };
  20718. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20719. this.line.material.color.setHex( hex );
  20720. this.cone.material.color.setHex( hex );
  20721. };
  20722. /**
  20723. * @author mrdoob / http://mrdoob.com/
  20724. */
  20725. THREE.BoxHelper = function ( object ) {
  20726. // 5____4
  20727. // 1/___0/|
  20728. // | 6__|_7
  20729. // 2/___3/
  20730. var vertices = [
  20731. new THREE.Vector3( 1, 1, 1 ),
  20732. new THREE.Vector3( - 1, 1, 1 ),
  20733. new THREE.Vector3( - 1, - 1, 1 ),
  20734. new THREE.Vector3( 1, - 1, 1 ),
  20735. new THREE.Vector3( 1, 1, - 1 ),
  20736. new THREE.Vector3( - 1, 1, - 1 ),
  20737. new THREE.Vector3( - 1, - 1, - 1 ),
  20738. new THREE.Vector3( 1, - 1, - 1 )
  20739. ];
  20740. this.vertices = vertices;
  20741. // TODO: Wouldn't be nice if Line had .segments?
  20742. var geometry = new THREE.Geometry();
  20743. geometry.vertices.push(
  20744. vertices[ 0 ], vertices[ 1 ],
  20745. vertices[ 1 ], vertices[ 2 ],
  20746. vertices[ 2 ], vertices[ 3 ],
  20747. vertices[ 3 ], vertices[ 0 ],
  20748. vertices[ 4 ], vertices[ 5 ],
  20749. vertices[ 5 ], vertices[ 6 ],
  20750. vertices[ 6 ], vertices[ 7 ],
  20751. vertices[ 7 ], vertices[ 4 ],
  20752. vertices[ 0 ], vertices[ 4 ],
  20753. vertices[ 1 ], vertices[ 5 ],
  20754. vertices[ 2 ], vertices[ 6 ],
  20755. vertices[ 3 ], vertices[ 7 ]
  20756. );
  20757. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffff00 } ), THREE.LinePieces );
  20758. if ( object !== undefined ) {
  20759. this.update( object );
  20760. }
  20761. };
  20762. THREE.BoxHelper.prototype = Object.create( THREE.Line.prototype );
  20763. THREE.BoxHelper.prototype.update = function ( object ) {
  20764. var geometry = object.geometry;
  20765. if ( geometry.boundingBox === null ) {
  20766. geometry.computeBoundingBox();
  20767. }
  20768. var min = geometry.boundingBox.min;
  20769. var max = geometry.boundingBox.max;
  20770. var vertices = this.vertices;
  20771. vertices[ 0 ].set( max.x, max.y, max.z );
  20772. vertices[ 1 ].set( min.x, max.y, max.z );
  20773. vertices[ 2 ].set( min.x, min.y, max.z );
  20774. vertices[ 3 ].set( max.x, min.y, max.z );
  20775. vertices[ 4 ].set( max.x, max.y, min.z );
  20776. vertices[ 5 ].set( min.x, max.y, min.z );
  20777. vertices[ 6 ].set( min.x, min.y, min.z );
  20778. vertices[ 7 ].set( max.x, min.y, min.z );
  20779. this.geometry.computeBoundingSphere();
  20780. this.geometry.verticesNeedUpdate = true;
  20781. this.matrixAutoUpdate = false;
  20782. this.matrixWorld = object.matrixWorld;
  20783. };
  20784. /**
  20785. * @author WestLangley / http://github.com/WestLangley
  20786. */
  20787. // a helper to show the world-axis-aligned bounding box for an object
  20788. THREE.BoundingBoxHelper = function ( object, hex ) {
  20789. var color = hex || 0x888888;
  20790. this.object = object;
  20791. this.box = new THREE.Box3();
  20792. THREE.Mesh.call( this, new THREE.CubeGeometry( 1, 1, 1 ), new THREE.MeshBasicMaterial( { color: color, wireframe: true } ) );
  20793. };
  20794. THREE.BoundingBoxHelper.prototype = Object.create( THREE.Mesh.prototype );
  20795. THREE.BoundingBoxHelper.prototype.update = function () {
  20796. this.box.setFromObject( this.object );
  20797. this.box.size( this.scale );
  20798. this.box.center( this.position );
  20799. };
  20800. /**
  20801. * @author alteredq / http://alteredqualia.com/
  20802. *
  20803. * - shows frustum, line of sight and up of the camera
  20804. * - suitable for fast updates
  20805. * - based on frustum visualization in lightgl.js shadowmap example
  20806. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20807. */
  20808. THREE.CameraHelper = function ( camera ) {
  20809. THREE.Line.call( this );
  20810. var geometry = new THREE.Geometry();
  20811. var material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20812. var pointMap = {};
  20813. // colors
  20814. var hexFrustum = 0xffaa00;
  20815. var hexCone = 0xff0000;
  20816. var hexUp = 0x00aaff;
  20817. var hexTarget = 0xffffff;
  20818. var hexCross = 0x333333;
  20819. // near
  20820. addLine( "n1", "n2", hexFrustum );
  20821. addLine( "n2", "n4", hexFrustum );
  20822. addLine( "n4", "n3", hexFrustum );
  20823. addLine( "n3", "n1", hexFrustum );
  20824. // far
  20825. addLine( "f1", "f2", hexFrustum );
  20826. addLine( "f2", "f4", hexFrustum );
  20827. addLine( "f4", "f3", hexFrustum );
  20828. addLine( "f3", "f1", hexFrustum );
  20829. // sides
  20830. addLine( "n1", "f1", hexFrustum );
  20831. addLine( "n2", "f2", hexFrustum );
  20832. addLine( "n3", "f3", hexFrustum );
  20833. addLine( "n4", "f4", hexFrustum );
  20834. // cone
  20835. addLine( "p", "n1", hexCone );
  20836. addLine( "p", "n2", hexCone );
  20837. addLine( "p", "n3", hexCone );
  20838. addLine( "p", "n4", hexCone );
  20839. // up
  20840. addLine( "u1", "u2", hexUp );
  20841. addLine( "u2", "u3", hexUp );
  20842. addLine( "u3", "u1", hexUp );
  20843. // target
  20844. addLine( "c", "t", hexTarget );
  20845. addLine( "p", "c", hexCross );
  20846. // cross
  20847. addLine( "cn1", "cn2", hexCross );
  20848. addLine( "cn3", "cn4", hexCross );
  20849. addLine( "cf1", "cf2", hexCross );
  20850. addLine( "cf3", "cf4", hexCross );
  20851. function addLine( a, b, hex ) {
  20852. addPoint( a, hex );
  20853. addPoint( b, hex );
  20854. }
  20855. function addPoint( id, hex ) {
  20856. geometry.vertices.push( new THREE.Vector3() );
  20857. geometry.colors.push( new THREE.Color( hex ) );
  20858. if ( pointMap[ id ] === undefined ) {
  20859. pointMap[ id ] = [];
  20860. }
  20861. pointMap[ id ].push( geometry.vertices.length - 1 );
  20862. }
  20863. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  20864. this.camera = camera;
  20865. this.matrixWorld = camera.matrixWorld;
  20866. this.matrixAutoUpdate = false;
  20867. this.pointMap = pointMap;
  20868. this.update();
  20869. };
  20870. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20871. THREE.CameraHelper.prototype.update = function () {
  20872. var vector = new THREE.Vector3();
  20873. var camera = new THREE.Camera();
  20874. var projector = new THREE.Projector();
  20875. return function () {
  20876. var scope = this;
  20877. var w = 1, h = 1;
  20878. // we need just camera projection matrix
  20879. // world matrix must be identity
  20880. camera.projectionMatrix.copy( this.camera.projectionMatrix );
  20881. // center / target
  20882. setPoint( "c", 0, 0, -1 );
  20883. setPoint( "t", 0, 0, 1 );
  20884. // near
  20885. setPoint( "n1", -w, -h, -1 );
  20886. setPoint( "n2", w, -h, -1 );
  20887. setPoint( "n3", -w, h, -1 );
  20888. setPoint( "n4", w, h, -1 );
  20889. // far
  20890. setPoint( "f1", -w, -h, 1 );
  20891. setPoint( "f2", w, -h, 1 );
  20892. setPoint( "f3", -w, h, 1 );
  20893. setPoint( "f4", w, h, 1 );
  20894. // up
  20895. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20896. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20897. setPoint( "u3", 0, h * 2, -1 );
  20898. // cross
  20899. setPoint( "cf1", -w, 0, 1 );
  20900. setPoint( "cf2", w, 0, 1 );
  20901. setPoint( "cf3", 0, -h, 1 );
  20902. setPoint( "cf4", 0, h, 1 );
  20903. setPoint( "cn1", -w, 0, -1 );
  20904. setPoint( "cn2", w, 0, -1 );
  20905. setPoint( "cn3", 0, -h, -1 );
  20906. setPoint( "cn4", 0, h, -1 );
  20907. function setPoint( point, x, y, z ) {
  20908. vector.set( x, y, z );
  20909. projector.unprojectVector( vector, camera );
  20910. var points = scope.pointMap[ point ];
  20911. if ( points !== undefined ) {
  20912. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20913. scope.geometry.vertices[ points[ i ] ].copy( vector );
  20914. }
  20915. }
  20916. }
  20917. this.geometry.verticesNeedUpdate = true;
  20918. };
  20919. }();
  20920. /**
  20921. * @author alteredq / http://alteredqualia.com/
  20922. * @author mrdoob / http://mrdoob.com/
  20923. */
  20924. THREE.DirectionalLightHelper = function ( light, sphereSize ) {
  20925. THREE.Object3D.call( this );
  20926. this.matrixAutoUpdate = false;
  20927. this.light = light;
  20928. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  20929. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  20930. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20931. this.lightSphere = new THREE.Mesh( geometry, material );
  20932. this.lightSphere.matrixWorld = this.light.matrixWorld;
  20933. this.lightSphere.matrixAutoUpdate = false;
  20934. this.add( this.lightSphere );
  20935. /*
  20936. this.targetSphere = new THREE.Mesh( geometry, material );
  20937. this.targetSphere.position = this.light.target.position;
  20938. this.add( this.targetSphere );
  20939. */
  20940. geometry = new THREE.Geometry();
  20941. geometry.vertices.push( this.light.position );
  20942. geometry.vertices.push( this.light.target.position );
  20943. geometry.computeLineDistances();
  20944. material = new THREE.LineDashedMaterial( { dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20945. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20946. this.targetLine = new THREE.Line( geometry, material );
  20947. this.add( this.targetLine );
  20948. }
  20949. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20950. THREE.DirectionalLightHelper.prototype.update = function () {
  20951. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20952. this.targetLine.geometry.computeLineDistances();
  20953. this.targetLine.geometry.verticesNeedUpdate = true;
  20954. this.targetLine.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  20955. };
  20956. /**
  20957. * @author mrdoob / http://mrdoob.com/
  20958. * @author WestLangley / http://github.com/WestLangley
  20959. */
  20960. THREE.FaceNormalsHelper = function ( object, size, hex, linewidth ) {
  20961. this.object = object;
  20962. this.size = size || 1;
  20963. var color = hex || 0xffff00;
  20964. var width = linewidth || 1;
  20965. var geometry = new THREE.Geometry();
  20966. var faces = this.object.geometry.faces;
  20967. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20968. geometry.vertices.push( new THREE.Vector3() );
  20969. geometry.vertices.push( new THREE.Vector3() );
  20970. }
  20971. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  20972. this.matrixAutoUpdate = false;
  20973. this.normalMatrix = new THREE.Matrix3();
  20974. this.update();
  20975. };
  20976. THREE.FaceNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  20977. THREE.FaceNormalsHelper.prototype.update = ( function ( object ) {
  20978. var v1 = new THREE.Vector3();
  20979. return function( object ) {
  20980. this.object.updateMatrixWorld( true );
  20981. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  20982. var vertices = this.geometry.vertices;
  20983. var faces = this.object.geometry.faces;
  20984. var worldMatrix = this.object.matrixWorld;
  20985. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  20986. var face = faces[ i ];
  20987. v1.copy( face.normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  20988. var idx = 2 * i;
  20989. vertices[ idx ].copy( face.centroid ).applyMatrix4( worldMatrix );
  20990. vertices[ idx + 1 ].addVectors( vertices[ idx ], v1 );
  20991. }
  20992. this.geometry.verticesNeedUpdate = true;
  20993. return this;
  20994. }
  20995. }());
  20996. /**
  20997. * @author mrdoob / http://mrdoob.com/
  20998. */
  20999. THREE.GridHelper = function ( size, step ) {
  21000. var geometry = new THREE.Geometry();
  21001. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  21002. this.color1 = new THREE.Color( 0x444444 );
  21003. this.color2 = new THREE.Color( 0x888888 );
  21004. for ( var i = - size; i <= size; i += step ) {
  21005. geometry.vertices.push(
  21006. new THREE.Vector3( - size, 0, i ), new THREE.Vector3( size, 0, i ),
  21007. new THREE.Vector3( i, 0, - size ), new THREE.Vector3( i, 0, size )
  21008. );
  21009. var color = i === 0 ? this.color1 : this.color2;
  21010. geometry.colors.push( color, color, color, color );
  21011. }
  21012. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  21013. };
  21014. THREE.GridHelper.prototype = Object.create( THREE.Line.prototype );
  21015. THREE.GridHelper.prototype.setColors = function( colorCenterLine, colorGrid ) {
  21016. this.color1.set( colorCenterLine );
  21017. this.color2.set( colorGrid );
  21018. this.geometry.colorsNeedUpdate = true;
  21019. }
  21020. /**
  21021. * @author alteredq / http://alteredqualia.com/
  21022. * @author mrdoob / http://mrdoob.com/
  21023. */
  21024. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  21025. THREE.Object3D.call( this );
  21026. this.light = light;
  21027. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21028. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21029. for ( var i = 0, il = 8; i < il; i ++ ) {
  21030. geometry.faces[ i ].materialIndex = i < 4 ? 0 : 1;
  21031. }
  21032. var materialSky = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21033. materialSky.color.copy( light.color ).multiplyScalar( light.intensity );
  21034. var materialGround = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21035. materialGround.color.copy( light.groundColor ).multiplyScalar( light.intensity );
  21036. this.lightSphere = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( [ materialSky, materialGround ] ) );
  21037. this.lightSphere.position = light.position;
  21038. this.lightSphere.lookAt( new THREE.Vector3() );
  21039. this.add( this.lightSphere );
  21040. };
  21041. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21042. THREE.HemisphereLightHelper.prototype.update = function () {
  21043. this.lightSphere.lookAt( new THREE.Vector3() );
  21044. this.lightSphere.material.materials[ 0 ].color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21045. this.lightSphere.material.materials[ 1 ].color.copy( this.light.groundColor ).multiplyScalar( this.light.intensity );
  21046. };
  21047. /**
  21048. * @author alteredq / http://alteredqualia.com/
  21049. * @author mrdoob / http://mrdoob.com/
  21050. */
  21051. THREE.PointLightHelper = function ( light, sphereSize ) {
  21052. THREE.Object3D.call( this );
  21053. this.matrixAutoUpdate = false;
  21054. this.light = light;
  21055. var geometry = new THREE.SphereGeometry( sphereSize, 4, 2 );
  21056. var material = new THREE.MeshBasicMaterial( { fog: false, wireframe: true } );
  21057. material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21058. this.lightSphere = new THREE.Mesh( geometry, material );
  21059. this.lightSphere.matrixWorld = this.light.matrixWorld;
  21060. this.lightSphere.matrixAutoUpdate = false;
  21061. this.add( this.lightSphere );
  21062. /*
  21063. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  21064. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  21065. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  21066. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  21067. var d = light.distance;
  21068. if ( d === 0.0 ) {
  21069. this.lightDistance.visible = false;
  21070. } else {
  21071. this.lightDistance.scale.set( d, d, d );
  21072. }
  21073. this.add( this.lightDistance );
  21074. */
  21075. };
  21076. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  21077. THREE.PointLightHelper.prototype.update = function () {
  21078. this.lightSphere.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21079. /*
  21080. this.lightDistance.material.color.copy( this.color );
  21081. var d = this.light.distance;
  21082. if ( d === 0.0 ) {
  21083. this.lightDistance.visible = false;
  21084. } else {
  21085. this.lightDistance.visible = true;
  21086. this.lightDistance.scale.set( d, d, d );
  21087. }
  21088. */
  21089. };
  21090. /**
  21091. * @author alteredq / http://alteredqualia.com/
  21092. * @author mrdoob / http://mrdoob.com/
  21093. * @author WestLangley / http://github.com/WestLangley
  21094. */
  21095. THREE.SpotLightHelper = function ( light ) {
  21096. // spotlight helper must be a child of the scene
  21097. this.light = light;
  21098. var geometry = new THREE.CylinderGeometry( 0, 1, 1, 8, 1, true );
  21099. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( 0, -0.5, 0 ) );
  21100. geometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
  21101. var material = new THREE.MeshBasicMaterial( { wireframe: true, opacity: 0.3, transparent: true } );
  21102. THREE.Mesh.call( this, geometry, material );
  21103. this.update();
  21104. };
  21105. THREE.SpotLightHelper.prototype = Object.create( THREE.Mesh.prototype );
  21106. THREE.SpotLightHelper.prototype.update = ( function () {
  21107. var targetPosition = new THREE.Vector3();
  21108. return function() {
  21109. var coneLength = this.light.distance ? this.light.distance : 10000;
  21110. var coneWidth = coneLength * Math.tan( this.light.angle );
  21111. this.scale.set( coneWidth, coneWidth, coneLength );
  21112. this.light.updateMatrixWorld( true );
  21113. this.position.getPositionFromMatrix( this.light.matrixWorld );
  21114. this.light.target.updateMatrixWorld( true );
  21115. targetPosition.getPositionFromMatrix( this.light.target.matrixWorld );
  21116. this.lookAt( targetPosition );
  21117. this.material.color.copy( this.light.color ).multiplyScalar( this.light.intensity );
  21118. }
  21119. }());
  21120. /**
  21121. * @author mrdoob / http://mrdoob.com/
  21122. * @author WestLangley / http://github.com/WestLangley
  21123. */
  21124. THREE.VertexNormalsHelper = function ( object, size, hex, linewidth ) {
  21125. this.object = object;
  21126. this.size = size || 1;
  21127. var color = hex || 0xff0000;
  21128. var width = linewidth || 1;
  21129. var geometry = new THREE.Geometry();
  21130. var vertices = object.geometry.vertices;
  21131. var faces = object.geometry.faces;
  21132. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21133. var face = faces[ i ];
  21134. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21135. geometry.vertices.push( new THREE.Vector3() );
  21136. geometry.vertices.push( new THREE.Vector3() );
  21137. }
  21138. }
  21139. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21140. this.matrixAutoUpdate = false;
  21141. this.normalMatrix = new THREE.Matrix3();
  21142. this.update();
  21143. };
  21144. THREE.VertexNormalsHelper.prototype = Object.create( THREE.Line.prototype );
  21145. THREE.VertexNormalsHelper.prototype.update = ( function ( object ) {
  21146. var v1 = new THREE.Vector3();
  21147. return function( object ) {
  21148. var keys = [ 'a', 'b', 'c', 'd' ];
  21149. this.object.updateMatrixWorld( true );
  21150. this.normalMatrix.getNormalMatrix( this.object.matrixWorld );
  21151. var vertices = this.geometry.vertices;
  21152. var verts = this.object.geometry.vertices;
  21153. var faces = this.object.geometry.faces;
  21154. var worldMatrix = this.object.matrixWorld;
  21155. var idx = 0;
  21156. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21157. var face = faces[ i ];
  21158. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  21159. var vertexId = face[ keys[ j ] ];
  21160. var vertex = verts[ vertexId ];
  21161. var normal = face.vertexNormals[ j ];
  21162. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21163. v1.copy( normal ).applyMatrix3( this.normalMatrix ).normalize().multiplyScalar( this.size );
  21164. v1.add( vertices[ idx ] );
  21165. idx = idx + 1;
  21166. vertices[ idx ].copy( v1 );
  21167. idx = idx + 1;
  21168. }
  21169. }
  21170. this.geometry.verticesNeedUpdate = true;
  21171. return this;
  21172. }
  21173. }());
  21174. /**
  21175. * @author mrdoob / http://mrdoob.com/
  21176. * @author WestLangley / http://github.com/WestLangley
  21177. */
  21178. THREE.VertexTangentsHelper = function ( object, size, hex, linewidth ) {
  21179. this.object = object;
  21180. this.size = size || 1;
  21181. var color = hex || 0x0000ff;
  21182. var width = linewidth || 1;
  21183. var geometry = new THREE.Geometry();
  21184. var vertices = object.geometry.vertices;
  21185. var faces = object.geometry.faces;
  21186. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21187. var face = faces[ i ];
  21188. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21189. geometry.vertices.push( new THREE.Vector3() );
  21190. geometry.vertices.push( new THREE.Vector3() );
  21191. }
  21192. }
  21193. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: color, linewidth: width } ), THREE.LinePieces );
  21194. this.matrixAutoUpdate = false;
  21195. this.update();
  21196. };
  21197. THREE.VertexTangentsHelper.prototype = Object.create( THREE.Line.prototype );
  21198. THREE.VertexTangentsHelper.prototype.update = ( function ( object ) {
  21199. var v1 = new THREE.Vector3();
  21200. return function( object ) {
  21201. var keys = [ 'a', 'b', 'c', 'd' ];
  21202. this.object.updateMatrixWorld( true );
  21203. var vertices = this.geometry.vertices;
  21204. var verts = this.object.geometry.vertices;
  21205. var faces = this.object.geometry.faces;
  21206. var worldMatrix = this.object.matrixWorld;
  21207. var idx = 0;
  21208. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21209. var face = faces[ i ];
  21210. for ( var j = 0, jl = face.vertexTangents.length; j < jl; j ++ ) {
  21211. var vertexId = face[ keys[ j ] ];
  21212. var vertex = verts[ vertexId ];
  21213. var tangent = face.vertexTangents[ j ];
  21214. vertices[ idx ].copy( vertex ).applyMatrix4( worldMatrix );
  21215. v1.copy( tangent ).transformDirection( worldMatrix ).multiplyScalar( this.size );
  21216. v1.add( vertices[ idx ] );
  21217. idx = idx + 1;
  21218. vertices[ idx ].copy( v1 );
  21219. idx = idx + 1;
  21220. }
  21221. }
  21222. this.geometry.verticesNeedUpdate = true;
  21223. return this;
  21224. }
  21225. }());
  21226. /**
  21227. * @author mrdoob / http://mrdoob.com/
  21228. */
  21229. THREE.WireframeHelper = function ( object ) {
  21230. var edge = [ 0, 0 ], hash = {};
  21231. var sortFunction = function ( a, b ) { return a - b };
  21232. var keys = [ 'a', 'b', 'c', 'd' ];
  21233. var geometry = new THREE.Geometry();
  21234. var vertices = object.geometry.vertices;
  21235. var faces = object.geometry.faces;
  21236. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  21237. var face = faces[ i ];
  21238. var length = face instanceof THREE.Face4 ? 4 : 3;
  21239. for ( var j = 0; j < length; j ++ ) {
  21240. edge[ 0 ] = face[ keys[ j ] ];
  21241. edge[ 1 ] = face[ keys[ ( j + 1 ) % length ] ];
  21242. edge.sort( sortFunction );
  21243. var key = edge.toString();
  21244. if ( hash[ key ] === undefined ) {
  21245. geometry.vertices.push( vertices[ edge[ 0 ] ] );
  21246. geometry.vertices.push( vertices[ edge[ 1 ] ] );
  21247. hash[ key ] = true;
  21248. }
  21249. }
  21250. }
  21251. THREE.Line.call( this, geometry, new THREE.LineBasicMaterial( { color: 0xffffff } ), THREE.LinePieces );
  21252. this.matrixAutoUpdate = false;
  21253. this.matrixWorld = object.matrixWorld;
  21254. };
  21255. THREE.WireframeHelper.prototype = Object.create( THREE.Line.prototype );
  21256. /**
  21257. * @author alteredq / http://alteredqualia.com/
  21258. */
  21259. THREE.ImmediateRenderObject = function () {
  21260. THREE.Object3D.call( this );
  21261. this.render = function ( renderCallback ) { };
  21262. };
  21263. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  21264. /**
  21265. * @author mikael emtinger / http://gomo.se/
  21266. * @author alteredq / http://alteredqualia.com/
  21267. */
  21268. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  21269. THREE.Object3D.call( this );
  21270. this.lensFlares = [];
  21271. this.positionScreen = new THREE.Vector3();
  21272. this.customUpdateCallback = undefined;
  21273. if( texture !== undefined ) {
  21274. this.add( texture, size, distance, blending, color );
  21275. }
  21276. };
  21277. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  21278. /*
  21279. * Add: adds another flare
  21280. */
  21281. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  21282. if( size === undefined ) size = -1;
  21283. if( distance === undefined ) distance = 0;
  21284. if( opacity === undefined ) opacity = 1;
  21285. if( color === undefined ) color = new THREE.Color( 0xffffff );
  21286. if( blending === undefined ) blending = THREE.NormalBlending;
  21287. distance = Math.min( distance, Math.max( 0, distance ) );
  21288. this.lensFlares.push( { texture: texture, // THREE.Texture
  21289. size: size, // size in pixels (-1 = use texture.width)
  21290. distance: distance, // distance (0-1) from light source (0=at light source)
  21291. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  21292. scale: 1, // scale
  21293. rotation: 1, // rotation
  21294. opacity: opacity, // opacity
  21295. color: color, // color
  21296. blending: blending } ); // blending
  21297. };
  21298. /*
  21299. * Update lens flares update positions on all flares based on the screen position
  21300. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  21301. */
  21302. THREE.LensFlare.prototype.updateLensFlares = function () {
  21303. var f, fl = this.lensFlares.length;
  21304. var flare;
  21305. var vecX = -this.positionScreen.x * 2;
  21306. var vecY = -this.positionScreen.y * 2;
  21307. for( f = 0; f < fl; f ++ ) {
  21308. flare = this.lensFlares[ f ];
  21309. flare.x = this.positionScreen.x + vecX * flare.distance;
  21310. flare.y = this.positionScreen.y + vecY * flare.distance;
  21311. flare.wantedRotation = flare.x * Math.PI * 0.25;
  21312. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  21313. }
  21314. };
  21315. /**
  21316. * @author alteredq / http://alteredqualia.com/
  21317. */
  21318. THREE.MorphBlendMesh = function( geometry, material ) {
  21319. THREE.Mesh.call( this, geometry, material );
  21320. this.animationsMap = {};
  21321. this.animationsList = [];
  21322. // prepare default animation
  21323. // (all frames played together in 1 second)
  21324. var numFrames = this.geometry.morphTargets.length;
  21325. var name = "__default";
  21326. var startFrame = 0;
  21327. var endFrame = numFrames - 1;
  21328. var fps = numFrames / 1;
  21329. this.createAnimation( name, startFrame, endFrame, fps );
  21330. this.setAnimationWeight( name, 1 );
  21331. };
  21332. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21333. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21334. var animation = {
  21335. startFrame: start,
  21336. endFrame: end,
  21337. length: end - start + 1,
  21338. fps: fps,
  21339. duration: ( end - start ) / fps,
  21340. lastFrame: 0,
  21341. currentFrame: 0,
  21342. active: false,
  21343. time: 0,
  21344. direction: 1,
  21345. weight: 1,
  21346. directionBackwards: false,
  21347. mirroredLoop: false
  21348. };
  21349. this.animationsMap[ name ] = animation;
  21350. this.animationsList.push( animation );
  21351. };
  21352. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21353. var pattern = /([a-z]+)(\d+)/;
  21354. var firstAnimation, frameRanges = {};
  21355. var geometry = this.geometry;
  21356. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21357. var morph = geometry.morphTargets[ i ];
  21358. var chunks = morph.name.match( pattern );
  21359. if ( chunks && chunks.length > 1 ) {
  21360. var name = chunks[ 1 ];
  21361. var num = chunks[ 2 ];
  21362. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21363. var range = frameRanges[ name ];
  21364. if ( i < range.start ) range.start = i;
  21365. if ( i > range.end ) range.end = i;
  21366. if ( ! firstAnimation ) firstAnimation = name;
  21367. }
  21368. }
  21369. for ( var name in frameRanges ) {
  21370. var range = frameRanges[ name ];
  21371. this.createAnimation( name, range.start, range.end, fps );
  21372. }
  21373. this.firstAnimation = firstAnimation;
  21374. };
  21375. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21376. var animation = this.animationsMap[ name ];
  21377. if ( animation ) {
  21378. animation.direction = 1;
  21379. animation.directionBackwards = false;
  21380. }
  21381. };
  21382. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21383. var animation = this.animationsMap[ name ];
  21384. if ( animation ) {
  21385. animation.direction = -1;
  21386. animation.directionBackwards = true;
  21387. }
  21388. };
  21389. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21390. var animation = this.animationsMap[ name ];
  21391. if ( animation ) {
  21392. animation.fps = fps;
  21393. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21394. }
  21395. };
  21396. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21397. var animation = this.animationsMap[ name ];
  21398. if ( animation ) {
  21399. animation.duration = duration;
  21400. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21401. }
  21402. };
  21403. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21404. var animation = this.animationsMap[ name ];
  21405. if ( animation ) {
  21406. animation.weight = weight;
  21407. }
  21408. };
  21409. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21410. var animation = this.animationsMap[ name ];
  21411. if ( animation ) {
  21412. animation.time = time;
  21413. }
  21414. };
  21415. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21416. var time = 0;
  21417. var animation = this.animationsMap[ name ];
  21418. if ( animation ) {
  21419. time = animation.time;
  21420. }
  21421. return time;
  21422. };
  21423. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21424. var duration = -1;
  21425. var animation = this.animationsMap[ name ];
  21426. if ( animation ) {
  21427. duration = animation.duration;
  21428. }
  21429. return duration;
  21430. };
  21431. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21432. var animation = this.animationsMap[ name ];
  21433. if ( animation ) {
  21434. animation.time = 0;
  21435. animation.active = true;
  21436. } else {
  21437. console.warn( "animation[" + name + "] undefined" );
  21438. }
  21439. };
  21440. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21441. var animation = this.animationsMap[ name ];
  21442. if ( animation ) {
  21443. animation.active = false;
  21444. }
  21445. };
  21446. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21447. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21448. var animation = this.animationsList[ i ];
  21449. if ( ! animation.active ) continue;
  21450. var frameTime = animation.duration / animation.length;
  21451. animation.time += animation.direction * delta;
  21452. if ( animation.mirroredLoop ) {
  21453. if ( animation.time > animation.duration || animation.time < 0 ) {
  21454. animation.direction *= -1;
  21455. if ( animation.time > animation.duration ) {
  21456. animation.time = animation.duration;
  21457. animation.directionBackwards = true;
  21458. }
  21459. if ( animation.time < 0 ) {
  21460. animation.time = 0;
  21461. animation.directionBackwards = false;
  21462. }
  21463. }
  21464. } else {
  21465. animation.time = animation.time % animation.duration;
  21466. if ( animation.time < 0 ) animation.time += animation.duration;
  21467. }
  21468. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21469. var weight = animation.weight;
  21470. if ( keyframe !== animation.currentFrame ) {
  21471. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21472. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21473. this.morphTargetInfluences[ keyframe ] = 0;
  21474. animation.lastFrame = animation.currentFrame;
  21475. animation.currentFrame = keyframe;
  21476. }
  21477. var mix = ( animation.time % frameTime ) / frameTime;
  21478. if ( animation.directionBackwards ) mix = 1 - mix;
  21479. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21480. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21481. }
  21482. };
  21483. /**
  21484. * @author mikael emtinger / http://gomo.se/
  21485. * @author alteredq / http://alteredqualia.com/
  21486. */
  21487. THREE.LensFlarePlugin = function () {
  21488. var _gl, _renderer, _precision, _lensFlare = {};
  21489. this.init = function ( renderer ) {
  21490. _gl = renderer.context;
  21491. _renderer = renderer;
  21492. _precision = renderer.getPrecision();
  21493. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21494. _lensFlare.faces = new Uint16Array( 6 );
  21495. var i = 0;
  21496. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21497. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21498. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21499. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21500. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21501. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21502. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21503. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21504. i = 0;
  21505. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21506. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21507. // buffers
  21508. _lensFlare.vertexBuffer = _gl.createBuffer();
  21509. _lensFlare.elementBuffer = _gl.createBuffer();
  21510. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21511. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21512. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21513. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21514. // textures
  21515. _lensFlare.tempTexture = _gl.createTexture();
  21516. _lensFlare.occlusionTexture = _gl.createTexture();
  21517. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21518. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21519. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21520. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21521. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21522. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21523. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21524. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21525. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21526. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21527. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21528. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21529. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21530. _lensFlare.hasVertexTexture = false;
  21531. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ], _precision );
  21532. } else {
  21533. _lensFlare.hasVertexTexture = true;
  21534. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ], _precision );
  21535. }
  21536. _lensFlare.attributes = {};
  21537. _lensFlare.uniforms = {};
  21538. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21539. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21540. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21541. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21542. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21543. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21544. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21545. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21546. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21547. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21548. };
  21549. /*
  21550. * Render lens flares
  21551. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21552. * reads these back and calculates occlusion.
  21553. * Then _lensFlare.update_lensFlares() is called to re-position and
  21554. * update transparency of flares. Then they are rendered.
  21555. *
  21556. */
  21557. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21558. var flares = scene.__webglFlares,
  21559. nFlares = flares.length;
  21560. if ( ! nFlares ) return;
  21561. var tempPosition = new THREE.Vector3();
  21562. var invAspect = viewportHeight / viewportWidth,
  21563. halfViewportWidth = viewportWidth * 0.5,
  21564. halfViewportHeight = viewportHeight * 0.5;
  21565. var size = 16 / viewportHeight,
  21566. scale = new THREE.Vector2( size * invAspect, size );
  21567. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21568. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21569. var uniforms = _lensFlare.uniforms,
  21570. attributes = _lensFlare.attributes;
  21571. // set _lensFlare program and reset blending
  21572. _gl.useProgram( _lensFlare.program );
  21573. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21574. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21575. // loop through all lens flares to update their occlusion and positions
  21576. // setup gl and common used attribs/unforms
  21577. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21578. _gl.uniform1i( uniforms.map, 1 );
  21579. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21580. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21581. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21582. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21583. _gl.disable( _gl.CULL_FACE );
  21584. _gl.depthMask( false );
  21585. var i, j, jl, flare, sprite;
  21586. for ( i = 0; i < nFlares; i ++ ) {
  21587. size = 16 / viewportHeight;
  21588. scale.set( size * invAspect, size );
  21589. // calc object screen position
  21590. flare = flares[ i ];
  21591. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21592. tempPosition.applyMatrix4( camera.matrixWorldInverse );
  21593. tempPosition.applyProjection( camera.projectionMatrix );
  21594. // setup arrays for gl programs
  21595. screenPosition.copy( tempPosition )
  21596. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21597. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21598. // screen cull
  21599. if ( _lensFlare.hasVertexTexture || (
  21600. screenPositionPixels.x > 0 &&
  21601. screenPositionPixels.x < viewportWidth &&
  21602. screenPositionPixels.y > 0 &&
  21603. screenPositionPixels.y < viewportHeight ) ) {
  21604. // save current RGB to temp texture
  21605. _gl.activeTexture( _gl.TEXTURE1 );
  21606. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21607. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21608. // render pink quad
  21609. _gl.uniform1i( uniforms.renderType, 0 );
  21610. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21611. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21612. _gl.disable( _gl.BLEND );
  21613. _gl.enable( _gl.DEPTH_TEST );
  21614. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21615. // copy result to occlusionMap
  21616. _gl.activeTexture( _gl.TEXTURE0 );
  21617. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21618. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21619. // restore graphics
  21620. _gl.uniform1i( uniforms.renderType, 1 );
  21621. _gl.disable( _gl.DEPTH_TEST );
  21622. _gl.activeTexture( _gl.TEXTURE1 );
  21623. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21624. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21625. // update object positions
  21626. flare.positionScreen.copy( screenPosition )
  21627. if ( flare.customUpdateCallback ) {
  21628. flare.customUpdateCallback( flare );
  21629. } else {
  21630. flare.updateLensFlares();
  21631. }
  21632. // render flares
  21633. _gl.uniform1i( uniforms.renderType, 2 );
  21634. _gl.enable( _gl.BLEND );
  21635. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21636. sprite = flare.lensFlares[ j ];
  21637. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21638. screenPosition.x = sprite.x;
  21639. screenPosition.y = sprite.y;
  21640. screenPosition.z = sprite.z;
  21641. size = sprite.size * sprite.scale / viewportHeight;
  21642. scale.x = size * invAspect;
  21643. scale.y = size;
  21644. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21645. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21646. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21647. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21648. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21649. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21650. _renderer.setTexture( sprite.texture, 1 );
  21651. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21652. }
  21653. }
  21654. }
  21655. }
  21656. // restore gl
  21657. _gl.enable( _gl.CULL_FACE );
  21658. _gl.enable( _gl.DEPTH_TEST );
  21659. _gl.depthMask( true );
  21660. };
  21661. function createProgram ( shader, precision ) {
  21662. var program = _gl.createProgram();
  21663. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21664. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21665. var prefix = "precision " + precision + " float;\n";
  21666. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  21667. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  21668. _gl.compileShader( fragmentShader );
  21669. _gl.compileShader( vertexShader );
  21670. _gl.attachShader( program, fragmentShader );
  21671. _gl.attachShader( program, vertexShader );
  21672. _gl.linkProgram( program );
  21673. return program;
  21674. };
  21675. };
  21676. /**
  21677. * @author alteredq / http://alteredqualia.com/
  21678. */
  21679. THREE.ShadowMapPlugin = function () {
  21680. var _gl,
  21681. _renderer,
  21682. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21683. _frustum = new THREE.Frustum(),
  21684. _projScreenMatrix = new THREE.Matrix4(),
  21685. _min = new THREE.Vector3(),
  21686. _max = new THREE.Vector3(),
  21687. _matrixPosition = new THREE.Vector3();
  21688. this.init = function ( renderer ) {
  21689. _gl = renderer.context;
  21690. _renderer = renderer;
  21691. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21692. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21693. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21694. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21695. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21696. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21697. _depthMaterial._shadowPass = true;
  21698. _depthMaterialMorph._shadowPass = true;
  21699. _depthMaterialSkin._shadowPass = true;
  21700. _depthMaterialMorphSkin._shadowPass = true;
  21701. };
  21702. this.render = function ( scene, camera ) {
  21703. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21704. this.update( scene, camera );
  21705. };
  21706. this.update = function ( scene, camera ) {
  21707. var i, il, j, jl, n,
  21708. shadowMap, shadowMatrix, shadowCamera,
  21709. program, buffer, material,
  21710. webglObject, object, light,
  21711. renderList,
  21712. lights = [],
  21713. k = 0,
  21714. fog = null;
  21715. // set GL state for depth map
  21716. _gl.clearColor( 1, 1, 1, 1 );
  21717. _gl.disable( _gl.BLEND );
  21718. _gl.enable( _gl.CULL_FACE );
  21719. _gl.frontFace( _gl.CCW );
  21720. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21721. _gl.cullFace( _gl.FRONT );
  21722. } else {
  21723. _gl.cullFace( _gl.BACK );
  21724. }
  21725. _renderer.setDepthTest( true );
  21726. // preprocess lights
  21727. // - skip lights that are not casting shadows
  21728. // - create virtual lights for cascaded shadow maps
  21729. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21730. light = scene.__lights[ i ];
  21731. if ( ! light.castShadow ) continue;
  21732. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21733. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21734. var virtualLight;
  21735. if ( ! light.shadowCascadeArray[ n ] ) {
  21736. virtualLight = createVirtualLight( light, n );
  21737. virtualLight.originalCamera = camera;
  21738. var gyro = new THREE.Gyroscope();
  21739. gyro.position = light.shadowCascadeOffset;
  21740. gyro.add( virtualLight );
  21741. gyro.add( virtualLight.target );
  21742. camera.add( gyro );
  21743. light.shadowCascadeArray[ n ] = virtualLight;
  21744. console.log( "Created virtualLight", virtualLight );
  21745. } else {
  21746. virtualLight = light.shadowCascadeArray[ n ];
  21747. }
  21748. updateVirtualLight( light, n );
  21749. lights[ k ] = virtualLight;
  21750. k ++;
  21751. }
  21752. } else {
  21753. lights[ k ] = light;
  21754. k ++;
  21755. }
  21756. }
  21757. // render depth map
  21758. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21759. light = lights[ i ];
  21760. if ( ! light.shadowMap ) {
  21761. var shadowFilter = THREE.LinearFilter;
  21762. if ( _renderer.shadowMapType === THREE.PCFSoftShadowMap ) {
  21763. shadowFilter = THREE.NearestFilter;
  21764. }
  21765. var pars = { minFilter: shadowFilter, magFilter: shadowFilter, format: THREE.RGBAFormat };
  21766. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21767. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21768. light.shadowMatrix = new THREE.Matrix4();
  21769. }
  21770. if ( ! light.shadowCamera ) {
  21771. if ( light instanceof THREE.SpotLight ) {
  21772. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21773. } else if ( light instanceof THREE.DirectionalLight ) {
  21774. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21775. } else {
  21776. console.error( "Unsupported light type for shadow" );
  21777. continue;
  21778. }
  21779. scene.add( light.shadowCamera );
  21780. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  21781. }
  21782. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21783. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21784. light.shadowCamera.add( light.cameraHelper );
  21785. }
  21786. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21787. updateShadowCamera( camera, light );
  21788. }
  21789. shadowMap = light.shadowMap;
  21790. shadowMatrix = light.shadowMatrix;
  21791. shadowCamera = light.shadowCamera;
  21792. shadowCamera.position.getPositionFromMatrix( light.matrixWorld );
  21793. _matrixPosition.getPositionFromMatrix( light.target.matrixWorld );
  21794. shadowCamera.lookAt( _matrixPosition );
  21795. shadowCamera.updateMatrixWorld();
  21796. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21797. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21798. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21799. // compute shadow matrix
  21800. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21801. 0.0, 0.5, 0.0, 0.5,
  21802. 0.0, 0.0, 0.5, 0.5,
  21803. 0.0, 0.0, 0.0, 1.0 );
  21804. shadowMatrix.multiply( shadowCamera.projectionMatrix );
  21805. shadowMatrix.multiply( shadowCamera.matrixWorldInverse );
  21806. // update camera matrices and frustum
  21807. _projScreenMatrix.multiplyMatrices( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21808. _frustum.setFromMatrix( _projScreenMatrix );
  21809. // render shadow map
  21810. _renderer.setRenderTarget( shadowMap );
  21811. _renderer.clear();
  21812. // set object matrices & frustum culling
  21813. renderList = scene.__webglObjects;
  21814. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21815. webglObject = renderList[ j ];
  21816. object = webglObject.object;
  21817. webglObject.render = false;
  21818. if ( object.visible && object.castShadow ) {
  21819. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  21820. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21821. webglObject.render = true;
  21822. }
  21823. }
  21824. }
  21825. // render regular objects
  21826. var objectMaterial, useMorphing, useSkinning;
  21827. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21828. webglObject = renderList[ j ];
  21829. if ( webglObject.render ) {
  21830. object = webglObject.object;
  21831. buffer = webglObject.buffer;
  21832. // culling is overriden globally for all objects
  21833. // while rendering depth map
  21834. // need to deal with MeshFaceMaterial somehow
  21835. // in that case just use the first of material.materials for now
  21836. // (proper solution would require to break objects by materials
  21837. // similarly to regular rendering and then set corresponding
  21838. // depth materials per each chunk instead of just once per object)
  21839. objectMaterial = getObjectMaterial( object );
  21840. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21841. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21842. if ( object.customDepthMaterial ) {
  21843. material = object.customDepthMaterial;
  21844. } else if ( useSkinning ) {
  21845. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21846. } else if ( useMorphing ) {
  21847. material = _depthMaterialMorph;
  21848. } else {
  21849. material = _depthMaterial;
  21850. }
  21851. if ( buffer instanceof THREE.BufferGeometry ) {
  21852. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21853. } else {
  21854. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21855. }
  21856. }
  21857. }
  21858. // set matrices and render immediate objects
  21859. renderList = scene.__webglObjectsImmediate;
  21860. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21861. webglObject = renderList[ j ];
  21862. object = webglObject.object;
  21863. if ( object.visible && object.castShadow ) {
  21864. object._modelViewMatrix.multiplyMatrices( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21865. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21866. }
  21867. }
  21868. }
  21869. // restore GL state
  21870. var clearColor = _renderer.getClearColor(),
  21871. clearAlpha = _renderer.getClearAlpha();
  21872. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21873. _gl.enable( _gl.BLEND );
  21874. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21875. _gl.cullFace( _gl.BACK );
  21876. }
  21877. };
  21878. function createVirtualLight( light, cascade ) {
  21879. var virtualLight = new THREE.DirectionalLight();
  21880. virtualLight.isVirtual = true;
  21881. virtualLight.onlyShadow = true;
  21882. virtualLight.castShadow = true;
  21883. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21884. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21885. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21886. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21887. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21888. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21889. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21890. virtualLight.shadowDarkness = light.shadowDarkness;
  21891. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21892. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21893. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21894. virtualLight.pointsWorld = [];
  21895. virtualLight.pointsFrustum = [];
  21896. var pointsWorld = virtualLight.pointsWorld,
  21897. pointsFrustum = virtualLight.pointsFrustum;
  21898. for ( var i = 0; i < 8; i ++ ) {
  21899. pointsWorld[ i ] = new THREE.Vector3();
  21900. pointsFrustum[ i ] = new THREE.Vector3();
  21901. }
  21902. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21903. var farZ = light.shadowCascadeFarZ[ cascade ];
  21904. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21905. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21906. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21907. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21908. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21909. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21910. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21911. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21912. return virtualLight;
  21913. }
  21914. // Synchronize virtual light with the original light
  21915. function updateVirtualLight( light, cascade ) {
  21916. var virtualLight = light.shadowCascadeArray[ cascade ];
  21917. virtualLight.position.copy( light.position );
  21918. virtualLight.target.position.copy( light.target.position );
  21919. virtualLight.lookAt( virtualLight.target );
  21920. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21921. virtualLight.shadowDarkness = light.shadowDarkness;
  21922. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21923. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21924. var farZ = light.shadowCascadeFarZ[ cascade ];
  21925. var pointsFrustum = virtualLight.pointsFrustum;
  21926. pointsFrustum[ 0 ].z = nearZ;
  21927. pointsFrustum[ 1 ].z = nearZ;
  21928. pointsFrustum[ 2 ].z = nearZ;
  21929. pointsFrustum[ 3 ].z = nearZ;
  21930. pointsFrustum[ 4 ].z = farZ;
  21931. pointsFrustum[ 5 ].z = farZ;
  21932. pointsFrustum[ 6 ].z = farZ;
  21933. pointsFrustum[ 7 ].z = farZ;
  21934. }
  21935. // Fit shadow camera's ortho frustum to camera frustum
  21936. function updateShadowCamera( camera, light ) {
  21937. var shadowCamera = light.shadowCamera,
  21938. pointsFrustum = light.pointsFrustum,
  21939. pointsWorld = light.pointsWorld;
  21940. _min.set( Infinity, Infinity, Infinity );
  21941. _max.set( -Infinity, -Infinity, -Infinity );
  21942. for ( var i = 0; i < 8; i ++ ) {
  21943. var p = pointsWorld[ i ];
  21944. p.copy( pointsFrustum[ i ] );
  21945. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21946. p.applyMatrix4( shadowCamera.matrixWorldInverse );
  21947. if ( p.x < _min.x ) _min.x = p.x;
  21948. if ( p.x > _max.x ) _max.x = p.x;
  21949. if ( p.y < _min.y ) _min.y = p.y;
  21950. if ( p.y > _max.y ) _max.y = p.y;
  21951. if ( p.z < _min.z ) _min.z = p.z;
  21952. if ( p.z > _max.z ) _max.z = p.z;
  21953. }
  21954. shadowCamera.left = _min.x;
  21955. shadowCamera.right = _max.x;
  21956. shadowCamera.top = _max.y;
  21957. shadowCamera.bottom = _min.y;
  21958. // can't really fit near/far
  21959. //shadowCamera.near = _min.z;
  21960. //shadowCamera.far = _max.z;
  21961. shadowCamera.updateProjectionMatrix();
  21962. }
  21963. // For the moment just ignore objects that have multiple materials with different animation methods
  21964. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21965. function getObjectMaterial( object ) {
  21966. return object.material instanceof THREE.MeshFaceMaterial
  21967. ? object.material.materials[ 0 ]
  21968. : object.material;
  21969. };
  21970. };
  21971. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21972. /**
  21973. * @author mikael emtinger / http://gomo.se/
  21974. * @author alteredq / http://alteredqualia.com/
  21975. */
  21976. THREE.SpritePlugin = function () {
  21977. var _gl, _renderer, _precision, _sprite = {};
  21978. this.init = function ( renderer ) {
  21979. _gl = renderer.context;
  21980. _renderer = renderer;
  21981. _precision = renderer.getPrecision();
  21982. _sprite.vertices = new Float32Array( 8 + 8 );
  21983. _sprite.faces = new Uint16Array( 6 );
  21984. var i = 0;
  21985. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21986. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21987. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21988. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21989. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21990. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21991. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21992. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21993. i = 0;
  21994. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21995. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21996. _sprite.vertexBuffer = _gl.createBuffer();
  21997. _sprite.elementBuffer = _gl.createBuffer();
  21998. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21999. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  22000. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22001. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  22002. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ], _precision );
  22003. _sprite.attributes = {};
  22004. _sprite.uniforms = {};
  22005. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  22006. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  22007. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  22008. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  22009. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  22010. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  22011. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  22012. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  22013. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  22014. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  22015. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  22016. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  22017. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  22018. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  22019. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  22020. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  22021. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  22022. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  22023. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  22024. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  22025. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  22026. };
  22027. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  22028. var sprites = scene.__webglSprites,
  22029. nSprites = sprites.length;
  22030. if ( ! nSprites ) return;
  22031. var attributes = _sprite.attributes,
  22032. uniforms = _sprite.uniforms;
  22033. var invAspect = viewportHeight / viewportWidth;
  22034. var halfViewportWidth = viewportWidth * 0.5,
  22035. halfViewportHeight = viewportHeight * 0.5;
  22036. // setup gl
  22037. _gl.useProgram( _sprite.program );
  22038. _gl.enableVertexAttribArray( attributes.position );
  22039. _gl.enableVertexAttribArray( attributes.uv );
  22040. _gl.disable( _gl.CULL_FACE );
  22041. _gl.enable( _gl.BLEND );
  22042. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  22043. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  22044. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  22045. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  22046. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  22047. _gl.activeTexture( _gl.TEXTURE0 );
  22048. _gl.uniform1i( uniforms.map, 0 );
  22049. var oldFogType = 0;
  22050. var sceneFogType = 0;
  22051. var fog = scene.fog;
  22052. if ( fog ) {
  22053. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  22054. if ( fog instanceof THREE.Fog ) {
  22055. _gl.uniform1f( uniforms.fogNear, fog.near );
  22056. _gl.uniform1f( uniforms.fogFar, fog.far );
  22057. _gl.uniform1i( uniforms.fogType, 1 );
  22058. oldFogType = 1;
  22059. sceneFogType = 1;
  22060. } else if ( fog instanceof THREE.FogExp2 ) {
  22061. _gl.uniform1f( uniforms.fogDensity, fog.density );
  22062. _gl.uniform1i( uniforms.fogType, 2 );
  22063. oldFogType = 2;
  22064. sceneFogType = 2;
  22065. }
  22066. } else {
  22067. _gl.uniform1i( uniforms.fogType, 0 );
  22068. oldFogType = 0;
  22069. sceneFogType = 0;
  22070. }
  22071. // update positions and sort
  22072. var i, sprite, material, screenPosition, size, fogType, scale = [];
  22073. for( i = 0; i < nSprites; i ++ ) {
  22074. sprite = sprites[ i ];
  22075. material = sprite.material;
  22076. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22077. if ( ! material.useScreenCoordinates ) {
  22078. sprite._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, sprite.matrixWorld );
  22079. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  22080. } else {
  22081. sprite.z = - sprite.position.z;
  22082. }
  22083. }
  22084. sprites.sort( painterSortStable );
  22085. // render all sprites
  22086. for( i = 0; i < nSprites; i ++ ) {
  22087. sprite = sprites[ i ];
  22088. material = sprite.material;
  22089. if ( ! sprite.visible || material.opacity === 0 ) continue;
  22090. if ( material.map && material.map.image && material.map.image.width ) {
  22091. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  22092. if ( material.useScreenCoordinates === true ) {
  22093. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  22094. _gl.uniform3f(
  22095. uniforms.screenPosition,
  22096. ( ( sprite.position.x * _renderer.devicePixelRatio ) - halfViewportWidth ) / halfViewportWidth,
  22097. ( halfViewportHeight - ( sprite.position.y * _renderer.devicePixelRatio ) ) / halfViewportHeight,
  22098. Math.max( 0, Math.min( 1, sprite.position.z ) )
  22099. );
  22100. scale[ 0 ] = _renderer.devicePixelRatio;
  22101. scale[ 1 ] = _renderer.devicePixelRatio;
  22102. } else {
  22103. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  22104. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  22105. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  22106. scale[ 0 ] = 1;
  22107. scale[ 1 ] = 1;
  22108. }
  22109. if ( scene.fog && material.fog ) {
  22110. fogType = sceneFogType;
  22111. } else {
  22112. fogType = 0;
  22113. }
  22114. if ( oldFogType !== fogType ) {
  22115. _gl.uniform1i( uniforms.fogType, fogType );
  22116. oldFogType = fogType;
  22117. }
  22118. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  22119. scale[ 0 ] *= size * invAspect * sprite.scale.x
  22120. scale[ 1 ] *= size * sprite.scale.y;
  22121. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  22122. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  22123. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  22124. _gl.uniform1f( uniforms.opacity, material.opacity );
  22125. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  22126. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  22127. _gl.uniform2fv( uniforms.scale, scale );
  22128. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  22129. _renderer.setDepthTest( material.depthTest );
  22130. _renderer.setDepthWrite( material.depthWrite );
  22131. _renderer.setTexture( material.map, 0 );
  22132. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  22133. }
  22134. }
  22135. // restore gl
  22136. _gl.enable( _gl.CULL_FACE );
  22137. };
  22138. function createProgram ( shader, precision ) {
  22139. var program = _gl.createProgram();
  22140. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  22141. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  22142. var prefix = "precision " + precision + " float;\n";
  22143. _gl.shaderSource( fragmentShader, prefix + shader.fragmentShader );
  22144. _gl.shaderSource( vertexShader, prefix + shader.vertexShader );
  22145. _gl.compileShader( fragmentShader );
  22146. _gl.compileShader( vertexShader );
  22147. _gl.attachShader( program, fragmentShader );
  22148. _gl.attachShader( program, vertexShader );
  22149. _gl.linkProgram( program );
  22150. return program;
  22151. };
  22152. function painterSortStable ( a, b ) {
  22153. if ( a.z !== b.z ) {
  22154. return b.z - a.z;
  22155. } else {
  22156. return b.id - a.id;
  22157. }
  22158. };
  22159. };
  22160. /**
  22161. * @author alteredq / http://alteredqualia.com/
  22162. */
  22163. THREE.DepthPassPlugin = function () {
  22164. this.enabled = false;
  22165. this.renderTarget = null;
  22166. var _gl,
  22167. _renderer,
  22168. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  22169. _frustum = new THREE.Frustum(),
  22170. _projScreenMatrix = new THREE.Matrix4();
  22171. this.init = function ( renderer ) {
  22172. _gl = renderer.context;
  22173. _renderer = renderer;
  22174. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  22175. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  22176. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  22177. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  22178. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  22179. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  22180. _depthMaterial._shadowPass = true;
  22181. _depthMaterialMorph._shadowPass = true;
  22182. _depthMaterialSkin._shadowPass = true;
  22183. _depthMaterialMorphSkin._shadowPass = true;
  22184. };
  22185. this.render = function ( scene, camera ) {
  22186. if ( ! this.enabled ) return;
  22187. this.update( scene, camera );
  22188. };
  22189. this.update = function ( scene, camera ) {
  22190. var i, il, j, jl, n,
  22191. program, buffer, material,
  22192. webglObject, object, light,
  22193. renderList,
  22194. fog = null;
  22195. // set GL state for depth map
  22196. _gl.clearColor( 1, 1, 1, 1 );
  22197. _gl.disable( _gl.BLEND );
  22198. _renderer.setDepthTest( true );
  22199. // update scene
  22200. if ( scene.autoUpdate === true ) scene.updateMatrixWorld();
  22201. // update camera matrices and frustum
  22202. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  22203. _projScreenMatrix.multiplyMatrices( camera.projectionMatrix, camera.matrixWorldInverse );
  22204. _frustum.setFromMatrix( _projScreenMatrix );
  22205. // render depth map
  22206. _renderer.setRenderTarget( this.renderTarget );
  22207. _renderer.clear();
  22208. // set object matrices & frustum culling
  22209. renderList = scene.__webglObjects;
  22210. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22211. webglObject = renderList[ j ];
  22212. object = webglObject.object;
  22213. webglObject.render = false;
  22214. if ( object.visible ) {
  22215. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.intersectsObject( object ) ) {
  22216. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22217. webglObject.render = true;
  22218. }
  22219. }
  22220. }
  22221. // render regular objects
  22222. var objectMaterial, useMorphing, useSkinning;
  22223. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22224. webglObject = renderList[ j ];
  22225. if ( webglObject.render ) {
  22226. object = webglObject.object;
  22227. buffer = webglObject.buffer;
  22228. // todo: create proper depth material for particles
  22229. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  22230. objectMaterial = getObjectMaterial( object );
  22231. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  22232. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  22233. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  22234. if ( object.customDepthMaterial ) {
  22235. material = object.customDepthMaterial;
  22236. } else if ( useSkinning ) {
  22237. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  22238. } else if ( useMorphing ) {
  22239. material = _depthMaterialMorph;
  22240. } else {
  22241. material = _depthMaterial;
  22242. }
  22243. if ( buffer instanceof THREE.BufferGeometry ) {
  22244. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  22245. } else {
  22246. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  22247. }
  22248. }
  22249. }
  22250. // set matrices and render immediate objects
  22251. renderList = scene.__webglObjectsImmediate;
  22252. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  22253. webglObject = renderList[ j ];
  22254. object = webglObject.object;
  22255. if ( object.visible ) {
  22256. object._modelViewMatrix.multiplyMatrices( camera.matrixWorldInverse, object.matrixWorld );
  22257. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  22258. }
  22259. }
  22260. // restore GL state
  22261. var clearColor = _renderer.getClearColor(),
  22262. clearAlpha = _renderer.getClearAlpha();
  22263. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  22264. _gl.enable( _gl.BLEND );
  22265. };
  22266. // For the moment just ignore objects that have multiple materials with different animation methods
  22267. // Only the first material will be taken into account for deciding which depth material to use
  22268. function getObjectMaterial( object ) {
  22269. return object.material instanceof THREE.MeshFaceMaterial
  22270. ? object.material.materials[ 0 ]
  22271. : object.material;
  22272. };
  22273. };
  22274. /**
  22275. * @author mikael emtinger / http://gomo.se/
  22276. */
  22277. THREE.ShaderFlares = {
  22278. 'lensFlareVertexTexture': {
  22279. vertexShader: [
  22280. "uniform lowp int renderType;",
  22281. "uniform vec3 screenPosition;",
  22282. "uniform vec2 scale;",
  22283. "uniform float rotation;",
  22284. "uniform sampler2D occlusionMap;",
  22285. "attribute vec2 position;",
  22286. "attribute vec2 uv;",
  22287. "varying vec2 vUV;",
  22288. "varying float vVisibility;",
  22289. "void main() {",
  22290. "vUV = uv;",
  22291. "vec2 pos = position;",
  22292. "if( renderType == 2 ) {",
  22293. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) );",
  22294. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.1 ) );",
  22295. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.1 ) );",
  22296. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) );",
  22297. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.9 ) );",
  22298. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) );",
  22299. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.9 ) );",
  22300. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) );",
  22301. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  22302. "vVisibility = visibility.r / 9.0;",
  22303. "vVisibility *= 1.0 - visibility.g / 9.0;",
  22304. "vVisibility *= visibility.b / 9.0;",
  22305. "vVisibility *= 1.0 - visibility.a / 9.0;",
  22306. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22307. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22308. "}",
  22309. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22310. "}"
  22311. ].join( "\n" ),
  22312. fragmentShader: [
  22313. "uniform lowp int renderType;",
  22314. "uniform sampler2D map;",
  22315. "uniform float opacity;",
  22316. "uniform vec3 color;",
  22317. "varying vec2 vUV;",
  22318. "varying float vVisibility;",
  22319. "void main() {",
  22320. // pink square
  22321. "if( renderType == 0 ) {",
  22322. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  22323. // restore
  22324. "} else if( renderType == 1 ) {",
  22325. "gl_FragColor = texture2D( map, vUV );",
  22326. // flare
  22327. "} else {",
  22328. "vec4 texture = texture2D( map, vUV );",
  22329. "texture.a *= opacity * vVisibility;",
  22330. "gl_FragColor = texture;",
  22331. "gl_FragColor.rgb *= color;",
  22332. "}",
  22333. "}"
  22334. ].join( "\n" )
  22335. },
  22336. 'lensFlare': {
  22337. vertexShader: [
  22338. "uniform lowp int renderType;",
  22339. "uniform vec3 screenPosition;",
  22340. "uniform vec2 scale;",
  22341. "uniform float rotation;",
  22342. "attribute vec2 position;",
  22343. "attribute vec2 uv;",
  22344. "varying vec2 vUV;",
  22345. "void main() {",
  22346. "vUV = uv;",
  22347. "vec2 pos = position;",
  22348. "if( renderType == 2 ) {",
  22349. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22350. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22351. "}",
  22352. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22353. "}"
  22354. ].join( "\n" ),
  22355. fragmentShader: [
  22356. "precision mediump float;",
  22357. "uniform lowp int renderType;",
  22358. "uniform sampler2D map;",
  22359. "uniform sampler2D occlusionMap;",
  22360. "uniform float opacity;",
  22361. "uniform vec3 color;",
  22362. "varying vec2 vUV;",
  22363. "void main() {",
  22364. // pink square
  22365. "if( renderType == 0 ) {",
  22366. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22367. // restore
  22368. "} else if( renderType == 1 ) {",
  22369. "gl_FragColor = texture2D( map, vUV );",
  22370. // flare
  22371. "} else {",
  22372. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a;",
  22373. "visibility += texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a;",
  22374. "visibility += texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a;",
  22375. "visibility += texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22376. "visibility = ( 1.0 - visibility / 4.0 );",
  22377. "vec4 texture = texture2D( map, vUV );",
  22378. "texture.a *= opacity * visibility;",
  22379. "gl_FragColor = texture;",
  22380. "gl_FragColor.rgb *= color;",
  22381. "}",
  22382. "}"
  22383. ].join( "\n" )
  22384. }
  22385. };
  22386. /**
  22387. * @author mikael emtinger / http://gomo.se/
  22388. * @author alteredq / http://alteredqualia.com/
  22389. *
  22390. */
  22391. THREE.ShaderSprite = {
  22392. 'sprite': {
  22393. vertexShader: [
  22394. "uniform int useScreenCoordinates;",
  22395. "uniform int sizeAttenuation;",
  22396. "uniform vec3 screenPosition;",
  22397. "uniform mat4 modelViewMatrix;",
  22398. "uniform mat4 projectionMatrix;",
  22399. "uniform float rotation;",
  22400. "uniform vec2 scale;",
  22401. "uniform vec2 alignment;",
  22402. "uniform vec2 uvOffset;",
  22403. "uniform vec2 uvScale;",
  22404. "attribute vec2 position;",
  22405. "attribute vec2 uv;",
  22406. "varying vec2 vUV;",
  22407. "void main() {",
  22408. "vUV = uvOffset + uv * uvScale;",
  22409. "vec2 alignedPosition = position + alignment;",
  22410. "vec2 rotatedPosition;",
  22411. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22412. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22413. "vec4 finalPosition;",
  22414. "if( useScreenCoordinates != 0 ) {",
  22415. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22416. "} else {",
  22417. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22418. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22419. "}",
  22420. "gl_Position = finalPosition;",
  22421. "}"
  22422. ].join( "\n" ),
  22423. fragmentShader: [
  22424. "uniform vec3 color;",
  22425. "uniform sampler2D map;",
  22426. "uniform float opacity;",
  22427. "uniform int fogType;",
  22428. "uniform vec3 fogColor;",
  22429. "uniform float fogDensity;",
  22430. "uniform float fogNear;",
  22431. "uniform float fogFar;",
  22432. "uniform float alphaTest;",
  22433. "varying vec2 vUV;",
  22434. "void main() {",
  22435. "vec4 texture = texture2D( map, vUV );",
  22436. "if ( texture.a < alphaTest ) discard;",
  22437. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22438. "if ( fogType > 0 ) {",
  22439. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22440. "float fogFactor = 0.0;",
  22441. "if ( fogType == 1 ) {",
  22442. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22443. "} else {",
  22444. "const float LOG2 = 1.442695;",
  22445. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22446. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22447. "}",
  22448. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22449. "}",
  22450. "}"
  22451. ].join( "\n" )
  22452. }
  22453. };