three.js 823 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '54dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  32. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  33. // requestAnimationFrame polyfill by Erik Möller
  34. // fixes from Paul Irish and Tino Zijdel
  35. ( function () {
  36. var lastTime = 0;
  37. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  38. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  39. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  40. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  41. }
  42. if ( window.requestAnimationFrame === undefined ) {
  43. window.requestAnimationFrame = function ( callback, element ) {
  44. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  45. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  46. lastTime = currTime + timeToCall;
  47. return id;
  48. };
  49. }
  50. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  51. }() );
  52. // MATERIAL CONSTANTS
  53. // side
  54. THREE.FrontSide = 0;
  55. THREE.BackSide = 1;
  56. THREE.DoubleSide = 2;
  57. // shading
  58. THREE.NoShading = 0;
  59. THREE.FlatShading = 1;
  60. THREE.SmoothShading = 2;
  61. // colors
  62. THREE.NoColors = 0;
  63. THREE.FaceColors = 1;
  64. THREE.VertexColors = 2;
  65. // blending modes
  66. THREE.NoBlending = 0;
  67. THREE.NormalBlending = 1;
  68. THREE.AdditiveBlending = 2;
  69. THREE.SubtractiveBlending = 3;
  70. THREE.MultiplyBlending = 4;
  71. THREE.CustomBlending = 5;
  72. // custom blending equations
  73. // (numbers start from 100 not to clash with other
  74. // mappings to OpenGL constants defined in Texture.js)
  75. THREE.AddEquation = 100;
  76. THREE.SubtractEquation = 101;
  77. THREE.ReverseSubtractEquation = 102;
  78. // custom blending destination factors
  79. THREE.ZeroFactor = 200;
  80. THREE.OneFactor = 201;
  81. THREE.SrcColorFactor = 202;
  82. THREE.OneMinusSrcColorFactor = 203;
  83. THREE.SrcAlphaFactor = 204;
  84. THREE.OneMinusSrcAlphaFactor = 205;
  85. THREE.DstAlphaFactor = 206;
  86. THREE.OneMinusDstAlphaFactor = 207;
  87. // custom blending source factors
  88. //THREE.ZeroFactor = 200;
  89. //THREE.OneFactor = 201;
  90. //THREE.SrcAlphaFactor = 204;
  91. //THREE.OneMinusSrcAlphaFactor = 205;
  92. //THREE.DstAlphaFactor = 206;
  93. //THREE.OneMinusDstAlphaFactor = 207;
  94. THREE.DstColorFactor = 208;
  95. THREE.OneMinusDstColorFactor = 209;
  96. THREE.SrcAlphaSaturateFactor = 210;
  97. // TEXTURE CONSTANTS
  98. THREE.MultiplyOperation = 0;
  99. THREE.MixOperation = 1;
  100. THREE.AddOperation = 2;
  101. // Mapping modes
  102. THREE.UVMapping = function () {};
  103. THREE.CubeReflectionMapping = function () {};
  104. THREE.CubeRefractionMapping = function () {};
  105. THREE.SphericalReflectionMapping = function () {};
  106. THREE.SphericalRefractionMapping = function () {};
  107. // Wrapping modes
  108. THREE.RepeatWrapping = 1000;
  109. THREE.ClampToEdgeWrapping = 1001;
  110. THREE.MirroredRepeatWrapping = 1002;
  111. // Filters
  112. THREE.NearestFilter = 1003;
  113. THREE.NearestMipMapNearestFilter = 1004;
  114. THREE.NearestMipMapLinearFilter = 1005;
  115. THREE.LinearFilter = 1006;
  116. THREE.LinearMipMapNearestFilter = 1007;
  117. THREE.LinearMipMapLinearFilter = 1008;
  118. // Data types
  119. THREE.UnsignedByteType = 1009;
  120. THREE.ByteType = 1010;
  121. THREE.ShortType = 1011;
  122. THREE.UnsignedShortType = 1012;
  123. THREE.IntType = 1013;
  124. THREE.UnsignedIntType = 1014;
  125. THREE.FloatType = 1015;
  126. // Pixel types
  127. //THREE.UnsignedByteType = 1009;
  128. THREE.UnsignedShort4444Type = 1016;
  129. THREE.UnsignedShort5551Type = 1017;
  130. THREE.UnsignedShort565Type = 1018;
  131. // Pixel formats
  132. THREE.AlphaFormat = 1019;
  133. THREE.RGBFormat = 1020;
  134. THREE.RGBAFormat = 1021;
  135. THREE.LuminanceFormat = 1022;
  136. THREE.LuminanceAlphaFormat = 1023;
  137. // Compressed texture formats
  138. THREE.RGB_S3TC_DXT1_Format = 2001;
  139. THREE.RGBA_S3TC_DXT1_Format = 2002;
  140. THREE.RGBA_S3TC_DXT3_Format = 2003;
  141. THREE.RGBA_S3TC_DXT5_Format = 2004;
  142. /*
  143. // Potential future PVRTC compressed texture formats
  144. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  145. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  146. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  147. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  148. */
  149. /**
  150. * @author alteredq / http://alteredqualia.com/
  151. */
  152. THREE.Clock = function ( autoStart ) {
  153. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  154. this.startTime = 0;
  155. this.oldTime = 0;
  156. this.elapsedTime = 0;
  157. this.running = false;
  158. };
  159. THREE.Clock.prototype.start = function () {
  160. this.startTime = Date.now();
  161. this.oldTime = this.startTime;
  162. this.running = true;
  163. };
  164. THREE.Clock.prototype.stop = function () {
  165. this.getElapsedTime();
  166. this.running = false;
  167. };
  168. THREE.Clock.prototype.getElapsedTime = function () {
  169. this.getDelta();
  170. return this.elapsedTime;
  171. };
  172. THREE.Clock.prototype.getDelta = function () {
  173. var diff = 0;
  174. if ( this.autoStart && ! this.running ) {
  175. this.start();
  176. }
  177. if ( this.running ) {
  178. var newTime = Date.now();
  179. diff = 0.001 * ( newTime - this.oldTime );
  180. this.oldTime = newTime;
  181. this.elapsedTime += diff;
  182. }
  183. return diff;
  184. };/**
  185. * @author mrdoob / http://mrdoob.com/
  186. */
  187. THREE.Color = function ( hex ) {
  188. if ( hex !== undefined ) this.setHex( hex );
  189. return this;
  190. };
  191. THREE.Color.prototype = {
  192. constructor: THREE.Color,
  193. r: 1, g: 1, b: 1,
  194. copy: function ( color ) {
  195. this.r = color.r;
  196. this.g = color.g;
  197. this.b = color.b;
  198. return this;
  199. },
  200. copyGammaToLinear: function ( color ) {
  201. this.r = color.r * color.r;
  202. this.g = color.g * color.g;
  203. this.b = color.b * color.b;
  204. return this;
  205. },
  206. copyLinearToGamma: function ( color ) {
  207. this.r = Math.sqrt( color.r );
  208. this.g = Math.sqrt( color.g );
  209. this.b = Math.sqrt( color.b );
  210. return this;
  211. },
  212. convertGammaToLinear: function () {
  213. var r = this.r, g = this.g, b = this.b;
  214. this.r = r * r;
  215. this.g = g * g;
  216. this.b = b * b;
  217. return this;
  218. },
  219. convertLinearToGamma: function () {
  220. this.r = Math.sqrt( this.r );
  221. this.g = Math.sqrt( this.g );
  222. this.b = Math.sqrt( this.b );
  223. return this;
  224. },
  225. setRGB: function ( r, g, b ) {
  226. this.r = r;
  227. this.g = g;
  228. this.b = b;
  229. return this;
  230. },
  231. setHSV: function ( h, s, v ) {
  232. // based on MochiKit implementation by Bob Ippolito
  233. // h,s,v ranges are < 0.0 - 1.0 >
  234. var i, f, p, q, t;
  235. if ( v === 0 ) {
  236. this.r = this.g = this.b = 0;
  237. } else {
  238. i = Math.floor( h * 6 );
  239. f = ( h * 6 ) - i;
  240. p = v * ( 1 - s );
  241. q = v * ( 1 - ( s * f ) );
  242. t = v * ( 1 - ( s * ( 1 - f ) ) );
  243. if ( i === 0 ) {
  244. this.r = v;
  245. this.g = t;
  246. this.b = p;
  247. } else if ( i === 1 ) {
  248. this.r = q;
  249. this.g = v;
  250. this.b = p;
  251. } else if ( i === 2 ) {
  252. this.r = p;
  253. this.g = v;
  254. this.b = t;
  255. } else if ( i === 3 ) {
  256. this.r = p;
  257. this.g = q;
  258. this.b = v;
  259. } else if ( i === 4 ) {
  260. this.r = t;
  261. this.g = p;
  262. this.b = v;
  263. } else if ( i === 5 ) {
  264. this.r = v;
  265. this.g = p;
  266. this.b = q;
  267. }
  268. }
  269. return this;
  270. },
  271. getHex: function () {
  272. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  273. },
  274. setHex: function ( hex ) {
  275. hex = Math.floor( hex );
  276. this.r = ( hex >> 16 & 255 ) / 255;
  277. this.g = ( hex >> 8 & 255 ) / 255;
  278. this.b = ( hex & 255 ) / 255;
  279. return this;
  280. },
  281. getHexString: function () {
  282. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  283. },
  284. getContextStyle: function () {
  285. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  286. },
  287. setContextStyle: function ( style ) {
  288. var color = /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/i.exec( style );
  289. this.r = parseInt( color[ 1 ], 10 ) / 255;
  290. this.g = parseInt( color[ 2 ], 10 ) / 255;
  291. this.b = parseInt( color[ 3 ], 10 ) / 255;
  292. return this;
  293. },
  294. getHSV: function ( hsv ) {
  295. // based on MochiKit implementation by Bob Ippolito
  296. // h,s,v ranges are < 0.0 - 1.0 >
  297. var r = this.r;
  298. var g = this.g;
  299. var b = this.b;
  300. var max = Math.max( Math.max( r, g ), b );
  301. var min = Math.min( Math.min( r, g ), b );
  302. var hue;
  303. var saturation;
  304. var value = max;
  305. if ( min === max ) {
  306. hue = 0;
  307. saturation = 0;
  308. } else {
  309. var delta = ( max - min );
  310. saturation = delta / max;
  311. if ( r === max ) {
  312. hue = ( g - b ) / delta;
  313. } else if ( g === max ) {
  314. hue = 2 + ( ( b - r ) / delta );
  315. } else {
  316. hue = 4 + ( ( r - g ) / delta );
  317. }
  318. hue /= 6;
  319. if ( hue < 0 ) {
  320. hue += 1;
  321. }
  322. if ( hue > 1 ) {
  323. hue -= 1;
  324. }
  325. }
  326. if ( hsv === undefined ) {
  327. hsv = { h: 0, s: 0, v: 0 };
  328. }
  329. hsv.h = hue;
  330. hsv.s = saturation;
  331. hsv.v = value;
  332. return hsv;
  333. },
  334. lerpSelf: function ( color, alpha ) {
  335. this.r += ( color.r - this.r ) * alpha;
  336. this.g += ( color.g - this.g ) * alpha;
  337. this.b += ( color.b - this.b ) * alpha;
  338. return this;
  339. },
  340. clone: function () {
  341. return new THREE.Color().setRGB( this.r, this.g, this.b );
  342. }
  343. };
  344. /**
  345. * @author mrdoob / http://mrdoob.com/
  346. * @author philogb / http://blog.thejit.org/
  347. * @author egraether / http://egraether.com/
  348. * @author zz85 / http://www.lab4games.net/zz85/blog
  349. */
  350. THREE.Vector2 = function ( x, y ) {
  351. this.x = x || 0;
  352. this.y = y || 0;
  353. };
  354. THREE.Vector2.prototype = {
  355. constructor: THREE.Vector2,
  356. set: function ( x, y ) {
  357. this.x = x;
  358. this.y = y;
  359. return this;
  360. },
  361. copy: function ( v ) {
  362. this.x = v.x;
  363. this.y = v.y;
  364. return this;
  365. },
  366. add: function ( a, b ) {
  367. this.x = a.x + b.x;
  368. this.y = a.y + b.y;
  369. return this;
  370. },
  371. addSelf: function ( v ) {
  372. this.x += v.x;
  373. this.y += v.y;
  374. return this;
  375. },
  376. sub: function ( a, b ) {
  377. this.x = a.x - b.x;
  378. this.y = a.y - b.y;
  379. return this;
  380. },
  381. subSelf: function ( v ) {
  382. this.x -= v.x;
  383. this.y -= v.y;
  384. return this;
  385. },
  386. multiplyScalar: function ( s ) {
  387. this.x *= s;
  388. this.y *= s;
  389. return this;
  390. },
  391. divideScalar: function ( s ) {
  392. if ( s ) {
  393. this.x /= s;
  394. this.y /= s;
  395. } else {
  396. this.set( 0, 0 );
  397. }
  398. return this;
  399. },
  400. negate: function() {
  401. return this.multiplyScalar( - 1 );
  402. },
  403. dot: function ( v ) {
  404. return this.x * v.x + this.y * v.y;
  405. },
  406. lengthSq: function () {
  407. return this.x * this.x + this.y * this.y;
  408. },
  409. length: function () {
  410. return Math.sqrt( this.lengthSq() );
  411. },
  412. normalize: function () {
  413. return this.divideScalar( this.length() );
  414. },
  415. distanceTo: function ( v ) {
  416. return Math.sqrt( this.distanceToSquared( v ) );
  417. },
  418. distanceToSquared: function ( v ) {
  419. var dx = this.x - v.x, dy = this.y - v.y;
  420. return dx * dx + dy * dy;
  421. },
  422. setLength: function ( l ) {
  423. return this.normalize().multiplyScalar( l );
  424. },
  425. lerpSelf: function ( v, alpha ) {
  426. this.x += ( v.x - this.x ) * alpha;
  427. this.y += ( v.y - this.y ) * alpha;
  428. return this;
  429. },
  430. equals: function( v ) {
  431. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  432. },
  433. clone: function () {
  434. return new THREE.Vector2( this.x, this.y );
  435. }
  436. };
  437. /**
  438. * @author mrdoob / http://mrdoob.com/
  439. * @author kile / http://kile.stravaganza.org/
  440. * @author philogb / http://blog.thejit.org/
  441. * @author mikael emtinger / http://gomo.se/
  442. * @author egraether / http://egraether.com/
  443. * @author WestLangley / http://github.com/WestLangley
  444. */
  445. THREE.Vector3 = function ( x, y, z ) {
  446. this.x = x || 0;
  447. this.y = y || 0;
  448. this.z = z || 0;
  449. };
  450. THREE.Vector3.prototype = {
  451. constructor: THREE.Vector3,
  452. set: function ( x, y, z ) {
  453. this.x = x;
  454. this.y = y;
  455. this.z = z;
  456. return this;
  457. },
  458. setX: function ( x ) {
  459. this.x = x;
  460. return this;
  461. },
  462. setY: function ( y ) {
  463. this.y = y;
  464. return this;
  465. },
  466. setZ: function ( z ) {
  467. this.z = z;
  468. return this;
  469. },
  470. copy: function ( v ) {
  471. this.x = v.x;
  472. this.y = v.y;
  473. this.z = v.z;
  474. return this;
  475. },
  476. add: function ( a, b ) {
  477. this.x = a.x + b.x;
  478. this.y = a.y + b.y;
  479. this.z = a.z + b.z;
  480. return this;
  481. },
  482. addSelf: function ( v ) {
  483. this.x += v.x;
  484. this.y += v.y;
  485. this.z += v.z;
  486. return this;
  487. },
  488. addScalar: function ( s ) {
  489. this.x += s;
  490. this.y += s;
  491. this.z += s;
  492. return this;
  493. },
  494. sub: function ( a, b ) {
  495. this.x = a.x - b.x;
  496. this.y = a.y - b.y;
  497. this.z = a.z - b.z;
  498. return this;
  499. },
  500. subSelf: function ( v ) {
  501. this.x -= v.x;
  502. this.y -= v.y;
  503. this.z -= v.z;
  504. return this;
  505. },
  506. multiply: function ( a, b ) {
  507. this.x = a.x * b.x;
  508. this.y = a.y * b.y;
  509. this.z = a.z * b.z;
  510. return this;
  511. },
  512. multiplySelf: function ( v ) {
  513. this.x *= v.x;
  514. this.y *= v.y;
  515. this.z *= v.z;
  516. return this;
  517. },
  518. multiplyScalar: function ( s ) {
  519. this.x *= s;
  520. this.y *= s;
  521. this.z *= s;
  522. return this;
  523. },
  524. divideSelf: function ( v ) {
  525. this.x /= v.x;
  526. this.y /= v.y;
  527. this.z /= v.z;
  528. return this;
  529. },
  530. divideScalar: function ( s ) {
  531. if ( s ) {
  532. this.x /= s;
  533. this.y /= s;
  534. this.z /= s;
  535. } else {
  536. this.x = 0;
  537. this.y = 0;
  538. this.z = 0;
  539. }
  540. return this;
  541. },
  542. negate: function() {
  543. return this.multiplyScalar( - 1 );
  544. },
  545. dot: function ( v ) {
  546. return this.x * v.x + this.y * v.y + this.z * v.z;
  547. },
  548. lengthSq: function () {
  549. return this.x * this.x + this.y * this.y + this.z * this.z;
  550. },
  551. length: function () {
  552. return Math.sqrt( this.lengthSq() );
  553. },
  554. lengthManhattan: function () {
  555. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  556. },
  557. normalize: function () {
  558. return this.divideScalar( this.length() );
  559. },
  560. setLength: function ( l ) {
  561. return this.normalize().multiplyScalar( l );
  562. },
  563. lerpSelf: function ( v, alpha ) {
  564. this.x += ( v.x - this.x ) * alpha;
  565. this.y += ( v.y - this.y ) * alpha;
  566. this.z += ( v.z - this.z ) * alpha;
  567. return this;
  568. },
  569. cross: function ( a, b ) {
  570. this.x = a.y * b.z - a.z * b.y;
  571. this.y = a.z * b.x - a.x * b.z;
  572. this.z = a.x * b.y - a.y * b.x;
  573. return this;
  574. },
  575. crossSelf: function ( v ) {
  576. var x = this.x, y = this.y, z = this.z;
  577. this.x = y * v.z - z * v.y;
  578. this.y = z * v.x - x * v.z;
  579. this.z = x * v.y - y * v.x;
  580. return this;
  581. },
  582. angleTo: function ( v ) {
  583. return Math.acos( this.dot( v ) / this.length() / v.length() );
  584. },
  585. distanceTo: function ( v ) {
  586. return Math.sqrt( this.distanceToSquared( v ) );
  587. },
  588. distanceToSquared: function ( v ) {
  589. return new THREE.Vector3().sub( this, v ).lengthSq();
  590. },
  591. getPositionFromMatrix: function ( m ) {
  592. this.x = m.elements[12];
  593. this.y = m.elements[13];
  594. this.z = m.elements[14];
  595. return this;
  596. },
  597. setEulerFromRotationMatrix: function ( m, order ) {
  598. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  599. // clamp, to handle numerical problems
  600. function clamp( x ) {
  601. return Math.min( Math.max( x, -1 ), 1 );
  602. }
  603. var te = m.elements;
  604. var m11 = te[0], m12 = te[4], m13 = te[8];
  605. var m21 = te[1], m22 = te[5], m23 = te[9];
  606. var m31 = te[2], m32 = te[6], m33 = te[10];
  607. if ( order === undefined || order === 'XYZ' ) {
  608. this.y = Math.asin( clamp( m13 ) );
  609. if ( Math.abs( m13 ) < 0.99999 ) {
  610. this.x = Math.atan2( - m23, m33 );
  611. this.z = Math.atan2( - m12, m11 );
  612. } else {
  613. this.x = Math.atan2( m32, m22 );
  614. this.z = 0;
  615. }
  616. } else if ( order === 'YXZ' ) {
  617. this.x = Math.asin( - clamp( m23 ) );
  618. if ( Math.abs( m23 ) < 0.99999 ) {
  619. this.y = Math.atan2( m13, m33 );
  620. this.z = Math.atan2( m21, m22 );
  621. } else {
  622. this.y = Math.atan2( - m31, m11 );
  623. this.z = 0;
  624. }
  625. } else if ( order === 'ZXY' ) {
  626. this.x = Math.asin( clamp( m32 ) );
  627. if ( Math.abs( m32 ) < 0.99999 ) {
  628. this.y = Math.atan2( - m31, m33 );
  629. this.z = Math.atan2( - m12, m22 );
  630. } else {
  631. this.y = 0;
  632. this.z = Math.atan2( m21, m11 );
  633. }
  634. } else if ( order === 'ZYX' ) {
  635. this.y = Math.asin( - clamp( m31 ) );
  636. if ( Math.abs( m31 ) < 0.99999 ) {
  637. this.x = Math.atan2( m32, m33 );
  638. this.z = Math.atan2( m21, m11 );
  639. } else {
  640. this.x = 0;
  641. this.z = Math.atan2( - m12, m22 );
  642. }
  643. } else if ( order === 'YZX' ) {
  644. this.z = Math.asin( clamp( m21 ) );
  645. if ( Math.abs( m21 ) < 0.99999 ) {
  646. this.x = Math.atan2( - m23, m22 );
  647. this.y = Math.atan2( - m31, m11 );
  648. } else {
  649. this.x = 0;
  650. this.y = Math.atan2( m13, m33 );
  651. }
  652. } else if ( order === 'XZY' ) {
  653. this.z = Math.asin( - clamp( m12 ) );
  654. if ( Math.abs( m12 ) < 0.99999 ) {
  655. this.x = Math.atan2( m32, m22 );
  656. this.y = Math.atan2( m13, m11 );
  657. } else {
  658. this.x = Math.atan2( - m23, m33 );
  659. this.y = 0;
  660. }
  661. }
  662. return this;
  663. },
  664. setEulerFromQuaternion: function ( q, order ) {
  665. // q is assumed to be normalized
  666. // clamp, to handle numerical problems
  667. function clamp( x ) {
  668. return Math.min( Math.max( x, -1 ), 1 );
  669. }
  670. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  671. var sqx = q.x * q.x;
  672. var sqy = q.y * q.y;
  673. var sqz = q.z * q.z;
  674. var sqw = q.w * q.w;
  675. if ( order === undefined || order === 'XYZ' ) {
  676. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  677. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  678. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  679. } else if ( order === 'YXZ' ) {
  680. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  681. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  682. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  683. } else if ( order === 'ZXY' ) {
  684. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  685. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  686. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  687. } else if ( order === 'ZYX' ) {
  688. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  689. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  690. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  691. } else if ( order === 'YZX' ) {
  692. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  693. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  694. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  695. } else if ( order === 'XZY' ) {
  696. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  697. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  698. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  699. }
  700. return this;
  701. },
  702. getScaleFromMatrix: function ( m ) {
  703. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  704. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  705. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  706. this.x = sx;
  707. this.y = sy;
  708. this.z = sz;
  709. return this;
  710. },
  711. equals: function ( v ) {
  712. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  713. },
  714. clone: function () {
  715. return new THREE.Vector3( this.x, this.y, this.z );
  716. }
  717. };
  718. /**
  719. * @author supereggbert / http://www.paulbrunt.co.uk/
  720. * @author philogb / http://blog.thejit.org/
  721. * @author mikael emtinger / http://gomo.se/
  722. * @author egraether / http://egraether.com/
  723. * @author WestLangley / http://github.com/WestLangley
  724. */
  725. THREE.Vector4 = function ( x, y, z, w ) {
  726. this.x = x || 0;
  727. this.y = y || 0;
  728. this.z = z || 0;
  729. this.w = ( w !== undefined ) ? w : 1;
  730. };
  731. THREE.Vector4.prototype = {
  732. constructor: THREE.Vector4,
  733. set: function ( x, y, z, w ) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. return this;
  739. },
  740. copy: function ( v ) {
  741. this.x = v.x;
  742. this.y = v.y;
  743. this.z = v.z;
  744. this.w = ( v.w !== undefined ) ? v.w : 1;
  745. return this;
  746. },
  747. add: function ( a, b ) {
  748. this.x = a.x + b.x;
  749. this.y = a.y + b.y;
  750. this.z = a.z + b.z;
  751. this.w = a.w + b.w;
  752. return this;
  753. },
  754. addSelf: function ( v ) {
  755. this.x += v.x;
  756. this.y += v.y;
  757. this.z += v.z;
  758. this.w += v.w;
  759. return this;
  760. },
  761. sub: function ( a, b ) {
  762. this.x = a.x - b.x;
  763. this.y = a.y - b.y;
  764. this.z = a.z - b.z;
  765. this.w = a.w - b.w;
  766. return this;
  767. },
  768. subSelf: function ( v ) {
  769. this.x -= v.x;
  770. this.y -= v.y;
  771. this.z -= v.z;
  772. this.w -= v.w;
  773. return this;
  774. },
  775. multiplyScalar: function ( s ) {
  776. this.x *= s;
  777. this.y *= s;
  778. this.z *= s;
  779. this.w *= s;
  780. return this;
  781. },
  782. divideScalar: function ( s ) {
  783. if ( s ) {
  784. this.x /= s;
  785. this.y /= s;
  786. this.z /= s;
  787. this.w /= s;
  788. } else {
  789. this.x = 0;
  790. this.y = 0;
  791. this.z = 0;
  792. this.w = 1;
  793. }
  794. return this;
  795. },
  796. negate: function() {
  797. return this.multiplyScalar( -1 );
  798. },
  799. dot: function ( v ) {
  800. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  801. },
  802. lengthSq: function () {
  803. return this.dot( this );
  804. },
  805. length: function () {
  806. return Math.sqrt( this.lengthSq() );
  807. },
  808. lengthManhattan: function () {
  809. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  810. },
  811. normalize: function () {
  812. return this.divideScalar( this.length() );
  813. },
  814. setLength: function ( l ) {
  815. return this.normalize().multiplyScalar( l );
  816. },
  817. lerpSelf: function ( v, alpha ) {
  818. this.x += ( v.x - this.x ) * alpha;
  819. this.y += ( v.y - this.y ) * alpha;
  820. this.z += ( v.z - this.z ) * alpha;
  821. this.w += ( v.w - this.w ) * alpha;
  822. return this;
  823. },
  824. clone: function () {
  825. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  826. },
  827. setAxisAngleFromQuaternion: function ( q ) {
  828. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  829. // q is assumed to be normalized
  830. this.w = 2 * Math.acos( q.w );
  831. var s = Math.sqrt( 1 - q.w * q.w );
  832. if ( s < 0.0001 ) {
  833. this.x = 1;
  834. this.y = 0;
  835. this.z = 0;
  836. } else {
  837. this.x = q.x / s;
  838. this.y = q.y / s;
  839. this.z = q.z / s;
  840. }
  841. return this;
  842. },
  843. setAxisAngleFromRotationMatrix: function ( m ) {
  844. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  845. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  846. var angle, x, y, z, // variables for result
  847. epsilon = 0.01, // margin to allow for rounding errors
  848. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  849. te = m.elements,
  850. m11 = te[0], m12 = te[4], m13 = te[8],
  851. m21 = te[1], m22 = te[5], m23 = te[9],
  852. m31 = te[2], m32 = te[6], m33 = te[10];
  853. if ( ( Math.abs( m12 - m21 ) < epsilon )
  854. && ( Math.abs( m13 - m31 ) < epsilon )
  855. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  856. // singularity found
  857. // first check for identity matrix which must have +1 for all terms
  858. // in leading diagonal and zero in other terms
  859. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  860. && ( Math.abs( m13 + m31 ) < epsilon2 )
  861. && ( Math.abs( m23 + m32 ) < epsilon2 )
  862. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  863. // this singularity is identity matrix so angle = 0
  864. this.set( 1, 0, 0, 0 );
  865. return this; // zero angle, arbitrary axis
  866. }
  867. // otherwise this singularity is angle = 180
  868. angle = Math.PI;
  869. var xx = ( m11 + 1 ) / 2;
  870. var yy = ( m22 + 1 ) / 2;
  871. var zz = ( m33 + 1 ) / 2;
  872. var xy = ( m12 + m21 ) / 4;
  873. var xz = ( m13 + m31 ) / 4;
  874. var yz = ( m23 + m32 ) / 4;
  875. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  876. if ( xx < epsilon ) {
  877. x = 0;
  878. y = 0.707106781;
  879. z = 0.707106781;
  880. } else {
  881. x = Math.sqrt( xx );
  882. y = xy / x;
  883. z = xz / x;
  884. }
  885. } else if ( yy > zz ) { // m22 is the largest diagonal term
  886. if ( yy < epsilon ) {
  887. x = 0.707106781;
  888. y = 0;
  889. z = 0.707106781;
  890. } else {
  891. y = Math.sqrt( yy );
  892. x = xy / y;
  893. z = yz / y;
  894. }
  895. } else { // m33 is the largest diagonal term so base result on this
  896. if ( zz < epsilon ) {
  897. x = 0.707106781;
  898. y = 0.707106781;
  899. z = 0;
  900. } else {
  901. z = Math.sqrt( zz );
  902. x = xz / z;
  903. y = yz / z;
  904. }
  905. }
  906. this.set( x, y, z, angle );
  907. return this; // return 180 deg rotation
  908. }
  909. // as we have reached here there are no singularities so we can handle normally
  910. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  911. + ( m13 - m31 ) * ( m13 - m31 )
  912. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  913. if ( Math.abs( s ) < 0.001 ) s = 1;
  914. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  915. // caught by singularity test above, but I've left it in just in case
  916. this.x = ( m32 - m23 ) / s;
  917. this.y = ( m13 - m31 ) / s;
  918. this.z = ( m21 - m12 ) / s;
  919. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  920. return this;
  921. }
  922. };
  923. /**
  924. * @author alteredq / http://alteredqualia.com/
  925. * @author WestLangley / http://github.com/WestLangley
  926. */
  927. THREE.Matrix3 = function () {
  928. this.elements = new Float32Array(9);
  929. };
  930. THREE.Matrix3.prototype = {
  931. constructor: THREE.Matrix3,
  932. multiplyVector3: function ( v ) {
  933. var te = this.elements;
  934. var vx = v.x, vy = v.y, vz = v.z;
  935. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  936. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  937. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  938. return v;
  939. },
  940. multiplyVector3Array: function ( a ) {
  941. var tmp = THREE.Matrix3.__v1;
  942. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  943. tmp.x = a[ i ];
  944. tmp.y = a[ i + 1 ];
  945. tmp.z = a[ i + 2 ];
  946. this.multiplyVector3( tmp );
  947. a[ i ] = tmp.x;
  948. a[ i + 1 ] = tmp.y;
  949. a[ i + 2 ] = tmp.z;
  950. }
  951. return a;
  952. },
  953. getInverse: function ( matrix ) {
  954. // input: THREE.Matrix4
  955. // ( based on http://code.google.com/p/webgl-mjs/ )
  956. var me = matrix.elements;
  957. var a11 = me[10] * me[5] - me[6] * me[9];
  958. var a21 = - me[10] * me[1] + me[2] * me[9];
  959. var a31 = me[6] * me[1] - me[2] * me[5];
  960. var a12 = - me[10] * me[4] + me[6] * me[8];
  961. var a22 = me[10] * me[0] - me[2] * me[8];
  962. var a32 = - me[6] * me[0] + me[2] * me[4];
  963. var a13 = me[9] * me[4] - me[5] * me[8];
  964. var a23 = - me[9] * me[0] + me[1] * me[8];
  965. var a33 = me[5] * me[0] - me[1] * me[4];
  966. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  967. // no inverse
  968. if ( det === 0 ) {
  969. console.warn( "Matrix3.getInverse(): determinant == 0" );
  970. }
  971. var idet = 1.0 / det;
  972. var m = this.elements;
  973. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  974. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  975. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  976. return this;
  977. },
  978. transpose: function () {
  979. var tmp, m = this.elements;
  980. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  981. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  982. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  983. return this;
  984. },
  985. transposeIntoArray: function ( r ) {
  986. var m = this.elements;
  987. r[ 0 ] = m[ 0 ];
  988. r[ 1 ] = m[ 3 ];
  989. r[ 2 ] = m[ 6 ];
  990. r[ 3 ] = m[ 1 ];
  991. r[ 4 ] = m[ 4 ];
  992. r[ 5 ] = m[ 7 ];
  993. r[ 6 ] = m[ 2 ];
  994. r[ 7 ] = m[ 5 ];
  995. r[ 8 ] = m[ 8 ];
  996. return this;
  997. }
  998. };
  999. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1000. * @author mrdoob / http://mrdoob.com/
  1001. * @author supereggbert / http://www.paulbrunt.co.uk/
  1002. * @author philogb / http://blog.thejit.org/
  1003. * @author jordi_ros / http://plattsoft.com
  1004. * @author D1plo1d / http://github.com/D1plo1d
  1005. * @author alteredq / http://alteredqualia.com/
  1006. * @author mikael emtinger / http://gomo.se/
  1007. * @author timknip / http://www.floorplanner.com/
  1008. */
  1009. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1010. this.elements = new Float32Array( 16 );
  1011. this.set(
  1012. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1013. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1014. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1015. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1016. );
  1017. };
  1018. THREE.Matrix4.prototype = {
  1019. constructor: THREE.Matrix4,
  1020. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1021. var te = this.elements;
  1022. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1023. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1024. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1025. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1026. return this;
  1027. },
  1028. identity: function () {
  1029. this.set(
  1030. 1, 0, 0, 0,
  1031. 0, 1, 0, 0,
  1032. 0, 0, 1, 0,
  1033. 0, 0, 0, 1
  1034. );
  1035. return this;
  1036. },
  1037. copy: function ( m ) {
  1038. var me = m.elements;
  1039. this.set(
  1040. me[0], me[4], me[8], me[12],
  1041. me[1], me[5], me[9], me[13],
  1042. me[2], me[6], me[10], me[14],
  1043. me[3], me[7], me[11], me[15]
  1044. );
  1045. return this;
  1046. },
  1047. lookAt: function ( eye, target, up ) {
  1048. var te = this.elements;
  1049. var x = THREE.Matrix4.__v1;
  1050. var y = THREE.Matrix4.__v2;
  1051. var z = THREE.Matrix4.__v3;
  1052. z.sub( eye, target ).normalize();
  1053. if ( z.length() === 0 ) {
  1054. z.z = 1;
  1055. }
  1056. x.cross( up, z ).normalize();
  1057. if ( x.length() === 0 ) {
  1058. z.x += 0.0001;
  1059. x.cross( up, z ).normalize();
  1060. }
  1061. y.cross( z, x );
  1062. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1063. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1064. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1065. return this;
  1066. },
  1067. multiply: function ( a, b ) {
  1068. var ae = a.elements;
  1069. var be = b.elements;
  1070. var te = this.elements;
  1071. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1072. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1073. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1074. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1075. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1076. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1077. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1078. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1079. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1080. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1081. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1082. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1083. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1084. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1085. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1086. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1087. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1088. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1089. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1090. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1091. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1092. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1093. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1094. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1095. return this;
  1096. },
  1097. multiplySelf: function ( m ) {
  1098. return this.multiply( this, m );
  1099. },
  1100. multiplyToArray: function ( a, b, r ) {
  1101. var te = this.elements;
  1102. this.multiply( a, b );
  1103. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1104. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1105. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1106. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1107. return this;
  1108. },
  1109. multiplyScalar: function ( s ) {
  1110. var te = this.elements;
  1111. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1112. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1113. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1114. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1115. return this;
  1116. },
  1117. multiplyVector3: function ( v ) {
  1118. var te = this.elements;
  1119. var vx = v.x, vy = v.y, vz = v.z;
  1120. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1121. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1122. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1123. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1124. return v;
  1125. },
  1126. multiplyVector4: function ( v ) {
  1127. var te = this.elements;
  1128. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1129. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1130. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1131. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1132. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1133. return v;
  1134. },
  1135. multiplyVector3Array: function ( a ) {
  1136. var tmp = THREE.Matrix4.__v1;
  1137. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1138. tmp.x = a[ i ];
  1139. tmp.y = a[ i + 1 ];
  1140. tmp.z = a[ i + 2 ];
  1141. this.multiplyVector3( tmp );
  1142. a[ i ] = tmp.x;
  1143. a[ i + 1 ] = tmp.y;
  1144. a[ i + 2 ] = tmp.z;
  1145. }
  1146. return a;
  1147. },
  1148. rotateAxis: function ( v ) {
  1149. var te = this.elements;
  1150. var vx = v.x, vy = v.y, vz = v.z;
  1151. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1152. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1153. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1154. v.normalize();
  1155. return v;
  1156. },
  1157. crossVector: function ( a ) {
  1158. var te = this.elements;
  1159. var v = new THREE.Vector4();
  1160. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1161. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1162. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1163. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1164. return v;
  1165. },
  1166. determinant: function () {
  1167. var te = this.elements;
  1168. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1169. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1170. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1171. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1172. //TODO: make this more efficient
  1173. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1174. return (
  1175. n14 * n23 * n32 * n41-
  1176. n13 * n24 * n32 * n41-
  1177. n14 * n22 * n33 * n41+
  1178. n12 * n24 * n33 * n41+
  1179. n13 * n22 * n34 * n41-
  1180. n12 * n23 * n34 * n41-
  1181. n14 * n23 * n31 * n42+
  1182. n13 * n24 * n31 * n42+
  1183. n14 * n21 * n33 * n42-
  1184. n11 * n24 * n33 * n42-
  1185. n13 * n21 * n34 * n42+
  1186. n11 * n23 * n34 * n42+
  1187. n14 * n22 * n31 * n43-
  1188. n12 * n24 * n31 * n43-
  1189. n14 * n21 * n32 * n43+
  1190. n11 * n24 * n32 * n43+
  1191. n12 * n21 * n34 * n43-
  1192. n11 * n22 * n34 * n43-
  1193. n13 * n22 * n31 * n44+
  1194. n12 * n23 * n31 * n44+
  1195. n13 * n21 * n32 * n44-
  1196. n11 * n23 * n32 * n44-
  1197. n12 * n21 * n33 * n44+
  1198. n11 * n22 * n33 * n44
  1199. );
  1200. },
  1201. transpose: function () {
  1202. var te = this.elements;
  1203. var tmp;
  1204. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1205. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1206. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1207. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1208. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1209. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1210. return this;
  1211. },
  1212. flattenToArray: function ( flat ) {
  1213. var te = this.elements;
  1214. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1215. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1216. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1217. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1218. return flat;
  1219. },
  1220. flattenToArrayOffset: function( flat, offset ) {
  1221. var te = this.elements;
  1222. flat[ offset ] = te[0];
  1223. flat[ offset + 1 ] = te[1];
  1224. flat[ offset + 2 ] = te[2];
  1225. flat[ offset + 3 ] = te[3];
  1226. flat[ offset + 4 ] = te[4];
  1227. flat[ offset + 5 ] = te[5];
  1228. flat[ offset + 6 ] = te[6];
  1229. flat[ offset + 7 ] = te[7];
  1230. flat[ offset + 8 ] = te[8];
  1231. flat[ offset + 9 ] = te[9];
  1232. flat[ offset + 10 ] = te[10];
  1233. flat[ offset + 11 ] = te[11];
  1234. flat[ offset + 12 ] = te[12];
  1235. flat[ offset + 13 ] = te[13];
  1236. flat[ offset + 14 ] = te[14];
  1237. flat[ offset + 15 ] = te[15];
  1238. return flat;
  1239. },
  1240. getPosition: function () {
  1241. var te = this.elements;
  1242. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1243. },
  1244. setPosition: function ( v ) {
  1245. var te = this.elements;
  1246. te[12] = v.x;
  1247. te[13] = v.y;
  1248. te[14] = v.z;
  1249. return this;
  1250. },
  1251. getColumnX: function () {
  1252. var te = this.elements;
  1253. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1254. },
  1255. getColumnY: function () {
  1256. var te = this.elements;
  1257. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1258. },
  1259. getColumnZ: function() {
  1260. var te = this.elements;
  1261. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1262. },
  1263. getInverse: function ( m ) {
  1264. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1265. var te = this.elements;
  1266. var me = m.elements;
  1267. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1268. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1269. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1270. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1271. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1272. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1273. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1274. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1275. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1276. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1277. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1278. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1279. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1280. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1281. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1282. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1283. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1284. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1285. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1286. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1287. this.multiplyScalar( 1 / m.determinant() );
  1288. return this;
  1289. },
  1290. setRotationFromEuler: function ( v, order ) {
  1291. var te = this.elements;
  1292. var x = v.x, y = v.y, z = v.z;
  1293. var a = Math.cos( x ), b = Math.sin( x );
  1294. var c = Math.cos( y ), d = Math.sin( y );
  1295. var e = Math.cos( z ), f = Math.sin( z );
  1296. if ( order === undefined || order === 'XYZ' ) {
  1297. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1298. te[0] = c * e;
  1299. te[4] = - c * f;
  1300. te[8] = d;
  1301. te[1] = af + be * d;
  1302. te[5] = ae - bf * d;
  1303. te[9] = - b * c;
  1304. te[2] = bf - ae * d;
  1305. te[6] = be + af * d;
  1306. te[10] = a * c;
  1307. } else if ( order === 'YXZ' ) {
  1308. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1309. te[0] = ce + df * b;
  1310. te[4] = de * b - cf;
  1311. te[8] = a * d;
  1312. te[1] = a * f;
  1313. te[5] = a * e;
  1314. te[9] = - b;
  1315. te[2] = cf * b - de;
  1316. te[6] = df + ce * b;
  1317. te[10] = a * c;
  1318. } else if ( order === 'ZXY' ) {
  1319. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1320. te[0] = ce - df * b;
  1321. te[4] = - a * f;
  1322. te[8] = de + cf * b;
  1323. te[1] = cf + de * b;
  1324. te[5] = a * e;
  1325. te[9] = df - ce * b;
  1326. te[2] = - a * d;
  1327. te[6] = b;
  1328. te[10] = a * c;
  1329. } else if ( order === 'ZYX' ) {
  1330. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1331. te[0] = c * e;
  1332. te[4] = be * d - af;
  1333. te[8] = ae * d + bf;
  1334. te[1] = c * f;
  1335. te[5] = bf * d + ae;
  1336. te[9] = af * d - be;
  1337. te[2] = - d;
  1338. te[6] = b * c;
  1339. te[10] = a * c;
  1340. } else if ( order === 'YZX' ) {
  1341. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1342. te[0] = c * e;
  1343. te[4] = bd - ac * f;
  1344. te[8] = bc * f + ad;
  1345. te[1] = f;
  1346. te[5] = a * e;
  1347. te[9] = - b * e;
  1348. te[2] = - d * e;
  1349. te[6] = ad * f + bc;
  1350. te[10] = ac - bd * f;
  1351. } else if ( order === 'XZY' ) {
  1352. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1353. te[0] = c * e;
  1354. te[4] = - f;
  1355. te[8] = d * e;
  1356. te[1] = ac * f + bd;
  1357. te[5] = a * e;
  1358. te[9] = ad * f - bc;
  1359. te[2] = bc * f - ad;
  1360. te[6] = b * e;
  1361. te[10] = bd * f + ac;
  1362. }
  1363. return this;
  1364. },
  1365. setRotationFromQuaternion: function ( q ) {
  1366. var te = this.elements;
  1367. var x = q.x, y = q.y, z = q.z, w = q.w;
  1368. var x2 = x + x, y2 = y + y, z2 = z + z;
  1369. var xx = x * x2, xy = x * y2, xz = x * z2;
  1370. var yy = y * y2, yz = y * z2, zz = z * z2;
  1371. var wx = w * x2, wy = w * y2, wz = w * z2;
  1372. te[0] = 1 - ( yy + zz );
  1373. te[4] = xy - wz;
  1374. te[8] = xz + wy;
  1375. te[1] = xy + wz;
  1376. te[5] = 1 - ( xx + zz );
  1377. te[9] = yz - wx;
  1378. te[2] = xz - wy;
  1379. te[6] = yz + wx;
  1380. te[10] = 1 - ( xx + yy );
  1381. return this;
  1382. },
  1383. compose: function ( translation, rotation, scale ) {
  1384. var te = this.elements;
  1385. var mRotation = THREE.Matrix4.__m1;
  1386. var mScale = THREE.Matrix4.__m2;
  1387. mRotation.identity();
  1388. mRotation.setRotationFromQuaternion( rotation );
  1389. mScale.makeScale( scale.x, scale.y, scale.z );
  1390. this.multiply( mRotation, mScale );
  1391. te[12] = translation.x;
  1392. te[13] = translation.y;
  1393. te[14] = translation.z;
  1394. return this;
  1395. },
  1396. decompose: function ( translation, rotation, scale ) {
  1397. var te = this.elements;
  1398. // grab the axis vectors
  1399. var x = THREE.Matrix4.__v1;
  1400. var y = THREE.Matrix4.__v2;
  1401. var z = THREE.Matrix4.__v3;
  1402. x.set( te[0], te[1], te[2] );
  1403. y.set( te[4], te[5], te[6] );
  1404. z.set( te[8], te[9], te[10] );
  1405. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1406. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1407. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1408. scale.x = x.length();
  1409. scale.y = y.length();
  1410. scale.z = z.length();
  1411. translation.x = te[12];
  1412. translation.y = te[13];
  1413. translation.z = te[14];
  1414. // scale the rotation part
  1415. var matrix = THREE.Matrix4.__m1;
  1416. matrix.copy( this );
  1417. matrix.elements[0] /= scale.x;
  1418. matrix.elements[1] /= scale.x;
  1419. matrix.elements[2] /= scale.x;
  1420. matrix.elements[4] /= scale.y;
  1421. matrix.elements[5] /= scale.y;
  1422. matrix.elements[6] /= scale.y;
  1423. matrix.elements[8] /= scale.z;
  1424. matrix.elements[9] /= scale.z;
  1425. matrix.elements[10] /= scale.z;
  1426. rotation.setFromRotationMatrix( matrix );
  1427. return [ translation, rotation, scale ];
  1428. },
  1429. extractPosition: function ( m ) {
  1430. var te = this.elements;
  1431. var me = m.elements;
  1432. te[12] = me[12];
  1433. te[13] = me[13];
  1434. te[14] = me[14];
  1435. return this;
  1436. },
  1437. extractRotation: function ( m ) {
  1438. var te = this.elements;
  1439. var me = m.elements;
  1440. var vector = THREE.Matrix4.__v1;
  1441. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1442. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1443. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1444. te[0] = me[0] * scaleX;
  1445. te[1] = me[1] * scaleX;
  1446. te[2] = me[2] * scaleX;
  1447. te[4] = me[4] * scaleY;
  1448. te[5] = me[5] * scaleY;
  1449. te[6] = me[6] * scaleY;
  1450. te[8] = me[8] * scaleZ;
  1451. te[9] = me[9] * scaleZ;
  1452. te[10] = me[10] * scaleZ;
  1453. return this;
  1454. },
  1455. //
  1456. translate: function ( v ) {
  1457. var te = this.elements;
  1458. var x = v.x, y = v.y, z = v.z;
  1459. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1460. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1461. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1462. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1463. return this;
  1464. },
  1465. rotateX: function ( angle ) {
  1466. var te = this.elements;
  1467. var m12 = te[4];
  1468. var m22 = te[5];
  1469. var m32 = te[6];
  1470. var m42 = te[7];
  1471. var m13 = te[8];
  1472. var m23 = te[9];
  1473. var m33 = te[10];
  1474. var m43 = te[11];
  1475. var c = Math.cos( angle );
  1476. var s = Math.sin( angle );
  1477. te[4] = c * m12 + s * m13;
  1478. te[5] = c * m22 + s * m23;
  1479. te[6] = c * m32 + s * m33;
  1480. te[7] = c * m42 + s * m43;
  1481. te[8] = c * m13 - s * m12;
  1482. te[9] = c * m23 - s * m22;
  1483. te[10] = c * m33 - s * m32;
  1484. te[11] = c * m43 - s * m42;
  1485. return this;
  1486. },
  1487. rotateY: function ( angle ) {
  1488. var te = this.elements;
  1489. var m11 = te[0];
  1490. var m21 = te[1];
  1491. var m31 = te[2];
  1492. var m41 = te[3];
  1493. var m13 = te[8];
  1494. var m23 = te[9];
  1495. var m33 = te[10];
  1496. var m43 = te[11];
  1497. var c = Math.cos( angle );
  1498. var s = Math.sin( angle );
  1499. te[0] = c * m11 - s * m13;
  1500. te[1] = c * m21 - s * m23;
  1501. te[2] = c * m31 - s * m33;
  1502. te[3] = c * m41 - s * m43;
  1503. te[8] = c * m13 + s * m11;
  1504. te[9] = c * m23 + s * m21;
  1505. te[10] = c * m33 + s * m31;
  1506. te[11] = c * m43 + s * m41;
  1507. return this;
  1508. },
  1509. rotateZ: function ( angle ) {
  1510. var te = this.elements;
  1511. var m11 = te[0];
  1512. var m21 = te[1];
  1513. var m31 = te[2];
  1514. var m41 = te[3];
  1515. var m12 = te[4];
  1516. var m22 = te[5];
  1517. var m32 = te[6];
  1518. var m42 = te[7];
  1519. var c = Math.cos( angle );
  1520. var s = Math.sin( angle );
  1521. te[0] = c * m11 + s * m12;
  1522. te[1] = c * m21 + s * m22;
  1523. te[2] = c * m31 + s * m32;
  1524. te[3] = c * m41 + s * m42;
  1525. te[4] = c * m12 - s * m11;
  1526. te[5] = c * m22 - s * m21;
  1527. te[6] = c * m32 - s * m31;
  1528. te[7] = c * m42 - s * m41;
  1529. return this;
  1530. },
  1531. rotateByAxis: function ( axis, angle ) {
  1532. var te = this.elements;
  1533. // optimize by checking axis
  1534. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1535. return this.rotateX( angle );
  1536. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1537. return this.rotateY( angle );
  1538. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1539. return this.rotateZ( angle );
  1540. }
  1541. var x = axis.x, y = axis.y, z = axis.z;
  1542. var n = Math.sqrt(x * x + y * y + z * z);
  1543. x /= n;
  1544. y /= n;
  1545. z /= n;
  1546. var xx = x * x, yy = y * y, zz = z * z;
  1547. var c = Math.cos( angle );
  1548. var s = Math.sin( angle );
  1549. var oneMinusCosine = 1 - c;
  1550. var xy = x * y * oneMinusCosine;
  1551. var xz = x * z * oneMinusCosine;
  1552. var yz = y * z * oneMinusCosine;
  1553. var xs = x * s;
  1554. var ys = y * s;
  1555. var zs = z * s;
  1556. var r11 = xx + (1 - xx) * c;
  1557. var r21 = xy + zs;
  1558. var r31 = xz - ys;
  1559. var r12 = xy - zs;
  1560. var r22 = yy + (1 - yy) * c;
  1561. var r32 = yz + xs;
  1562. var r13 = xz + ys;
  1563. var r23 = yz - xs;
  1564. var r33 = zz + (1 - zz) * c;
  1565. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1566. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1567. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1568. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1569. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1570. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1571. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1572. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1573. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1574. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1575. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1576. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1577. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1578. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1579. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1580. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1581. return this;
  1582. },
  1583. scale: function ( v ) {
  1584. var te = this.elements;
  1585. var x = v.x, y = v.y, z = v.z;
  1586. te[0] *= x; te[4] *= y; te[8] *= z;
  1587. te[1] *= x; te[5] *= y; te[9] *= z;
  1588. te[2] *= x; te[6] *= y; te[10] *= z;
  1589. te[3] *= x; te[7] *= y; te[11] *= z;
  1590. return this;
  1591. },
  1592. getMaxScaleOnAxis: function () {
  1593. var te = this.elements;
  1594. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1595. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1596. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1597. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1598. },
  1599. //
  1600. makeTranslation: function ( x, y, z ) {
  1601. this.set(
  1602. 1, 0, 0, x,
  1603. 0, 1, 0, y,
  1604. 0, 0, 1, z,
  1605. 0, 0, 0, 1
  1606. );
  1607. return this;
  1608. },
  1609. makeRotationX: function ( theta ) {
  1610. var c = Math.cos( theta ), s = Math.sin( theta );
  1611. this.set(
  1612. 1, 0, 0, 0,
  1613. 0, c, -s, 0,
  1614. 0, s, c, 0,
  1615. 0, 0, 0, 1
  1616. );
  1617. return this;
  1618. },
  1619. makeRotationY: function ( theta ) {
  1620. var c = Math.cos( theta ), s = Math.sin( theta );
  1621. this.set(
  1622. c, 0, s, 0,
  1623. 0, 1, 0, 0,
  1624. -s, 0, c, 0,
  1625. 0, 0, 0, 1
  1626. );
  1627. return this;
  1628. },
  1629. makeRotationZ: function ( theta ) {
  1630. var c = Math.cos( theta ), s = Math.sin( theta );
  1631. this.set(
  1632. c, -s, 0, 0,
  1633. s, c, 0, 0,
  1634. 0, 0, 1, 0,
  1635. 0, 0, 0, 1
  1636. );
  1637. return this;
  1638. },
  1639. makeRotationAxis: function ( axis, angle ) {
  1640. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1641. var c = Math.cos( angle );
  1642. var s = Math.sin( angle );
  1643. var t = 1 - c;
  1644. var x = axis.x, y = axis.y, z = axis.z;
  1645. var tx = t * x, ty = t * y;
  1646. this.set(
  1647. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1648. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1649. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1650. 0, 0, 0, 1
  1651. );
  1652. return this;
  1653. },
  1654. makeScale: function ( x, y, z ) {
  1655. this.set(
  1656. x, 0, 0, 0,
  1657. 0, y, 0, 0,
  1658. 0, 0, z, 0,
  1659. 0, 0, 0, 1
  1660. );
  1661. return this;
  1662. },
  1663. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1664. var te = this.elements;
  1665. var x = 2 * near / ( right - left );
  1666. var y = 2 * near / ( top - bottom );
  1667. var a = ( right + left ) / ( right - left );
  1668. var b = ( top + bottom ) / ( top - bottom );
  1669. var c = - ( far + near ) / ( far - near );
  1670. var d = - 2 * far * near / ( far - near );
  1671. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1672. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1673. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1674. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1675. return this;
  1676. },
  1677. makePerspective: function ( fov, aspect, near, far ) {
  1678. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1679. var ymin = - ymax;
  1680. var xmin = ymin * aspect;
  1681. var xmax = ymax * aspect;
  1682. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1683. },
  1684. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1685. var te = this.elements;
  1686. var w = right - left;
  1687. var h = top - bottom;
  1688. var p = far - near;
  1689. var x = ( right + left ) / w;
  1690. var y = ( top + bottom ) / h;
  1691. var z = ( far + near ) / p;
  1692. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1693. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1694. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1695. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1696. return this;
  1697. },
  1698. clone: function () {
  1699. var te = this.elements;
  1700. return new THREE.Matrix4(
  1701. te[0], te[4], te[8], te[12],
  1702. te[1], te[5], te[9], te[13],
  1703. te[2], te[6], te[10], te[14],
  1704. te[3], te[7], te[11], te[15]
  1705. );
  1706. }
  1707. };
  1708. THREE.Matrix4.__v1 = new THREE.Vector3();
  1709. THREE.Matrix4.__v2 = new THREE.Vector3();
  1710. THREE.Matrix4.__v3 = new THREE.Vector3();
  1711. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1712. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1713. /**
  1714. * https://github.com/mrdoob/eventtarget.js/
  1715. */
  1716. THREE.EventTarget = function () {
  1717. var listeners = {};
  1718. this.addEventListener = function ( type, listener ) {
  1719. if ( listeners[ type ] === undefined ) {
  1720. listeners[ type ] = [];
  1721. }
  1722. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1723. listeners[ type ].push( listener );
  1724. }
  1725. };
  1726. this.dispatchEvent = function ( event ) {
  1727. var listenerArray = listeners[ event.type ];
  1728. if ( listenerArray !== undefined ) {
  1729. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  1730. listenerArray[ i ]( event );
  1731. }
  1732. }
  1733. };
  1734. this.removeEventListener = function ( type, listener ) {
  1735. var index = listeners[ type ].indexOf( listener );
  1736. if ( index !== - 1 ) {
  1737. listeners[ type ].splice( index, 1 );
  1738. }
  1739. };
  1740. };
  1741. /**
  1742. * @author mrdoob / http://mrdoob.com/
  1743. * @author alteredq / http://alteredqualia.com/
  1744. */
  1745. THREE.Frustum = function ( ) {
  1746. this.planes = [
  1747. new THREE.Vector4(),
  1748. new THREE.Vector4(),
  1749. new THREE.Vector4(),
  1750. new THREE.Vector4(),
  1751. new THREE.Vector4(),
  1752. new THREE.Vector4()
  1753. ];
  1754. };
  1755. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1756. var plane;
  1757. var planes = this.planes;
  1758. var me = m.elements;
  1759. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1760. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1761. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1762. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1763. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1764. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1765. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1766. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1767. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1768. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1769. for ( var i = 0; i < 6; i ++ ) {
  1770. plane = planes[ i ];
  1771. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1772. }
  1773. };
  1774. THREE.Frustum.prototype.contains = function ( object ) {
  1775. var distance = 0.0;
  1776. var planes = this.planes;
  1777. var matrix = object.matrixWorld;
  1778. var me = matrix.elements;
  1779. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1780. for ( var i = 0; i < 6; i ++ ) {
  1781. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1782. if ( distance <= radius ) return false;
  1783. }
  1784. return true;
  1785. };
  1786. THREE.Frustum.__v1 = new THREE.Vector3();
  1787. /**
  1788. * @author mrdoob / http://mrdoob.com/
  1789. */
  1790. ( function ( THREE ) {
  1791. THREE.Ray = function ( origin, direction, near, far ) {
  1792. this.origin = origin || new THREE.Vector3();
  1793. this.direction = direction || new THREE.Vector3();
  1794. this.near = near || 0;
  1795. this.far = far || Infinity;
  1796. };
  1797. var originCopy = new THREE.Vector3();
  1798. var localOriginCopy = new THREE.Vector3();
  1799. var localDirectionCopy = new THREE.Vector3();
  1800. var vector = new THREE.Vector3();
  1801. var normal = new THREE.Vector3();
  1802. var intersectPoint = new THREE.Vector3();
  1803. var inverseMatrix = new THREE.Matrix4();
  1804. var descSort = function ( a, b ) {
  1805. return a.distance - b.distance;
  1806. };
  1807. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1808. var distanceFromIntersection = function ( origin, direction, position ) {
  1809. v0.sub( position, origin );
  1810. var dot = v0.dot( direction );
  1811. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1812. var distance = position.distanceTo( intersect );
  1813. return distance;
  1814. };
  1815. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1816. var pointInFace3 = function ( p, a, b, c ) {
  1817. v0.sub( c, a );
  1818. v1.sub( b, a );
  1819. v2.sub( p, a );
  1820. var dot00 = v0.dot( v0 );
  1821. var dot01 = v0.dot( v1 );
  1822. var dot02 = v0.dot( v2 );
  1823. var dot11 = v1.dot( v1 );
  1824. var dot12 = v1.dot( v2 );
  1825. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1826. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1827. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1828. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1829. };
  1830. var intersectObject = function ( object, ray, intersects ) {
  1831. if ( object instanceof THREE.Particle ) {
  1832. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1833. if ( distance > object.scale.x ) {
  1834. return intersects;
  1835. }
  1836. intersects.push( {
  1837. distance: distance,
  1838. point: object.position,
  1839. face: null,
  1840. object: object
  1841. } );
  1842. } else if ( object instanceof THREE.Mesh ) {
  1843. // Checking boundingSphere
  1844. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1845. // Checking distance to ray
  1846. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1847. if ( distance > scaledRadius) {
  1848. return intersects;
  1849. }
  1850. // Checking faces
  1851. var geometry = object.geometry;
  1852. var vertices = geometry.vertices;
  1853. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1854. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  1855. var side = object.material.side;
  1856. var a, b, c, d;
  1857. var precision = ray.precision;
  1858. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1859. originCopy.copy( ray.origin );
  1860. inverseMatrix.getInverse( object.matrixWorld );
  1861. localOriginCopy.copy( originCopy );
  1862. inverseMatrix.multiplyVector3( localOriginCopy );
  1863. localDirectionCopy.copy( ray.direction );
  1864. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1865. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1866. var face = geometry.faces[ f ];
  1867. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  1868. if ( material === undefined ) continue;
  1869. side = material.side;
  1870. vector.sub( face.centroid, localOriginCopy );
  1871. var normal = face.normal;
  1872. var dot = localDirectionCopy.dot( normal );
  1873. // bail if ray and plane are parallel
  1874. if ( Math.abs( dot ) < precision ) continue;
  1875. // calc distance to plane
  1876. var scalar = normal.dot( vector ) / dot;
  1877. // if negative distance, then plane is behind ray
  1878. if ( scalar < 0 ) continue;
  1879. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1880. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1881. if ( face instanceof THREE.Face3 ) {
  1882. a = vertices[ face.a ];
  1883. b = vertices[ face.b ];
  1884. c = vertices[ face.c ];
  1885. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1886. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1887. distance = originCopy.distanceTo( point );
  1888. if ( distance < ray.near || distance > ray.far ) continue;
  1889. intersects.push( {
  1890. distance: distance,
  1891. point: point,
  1892. face: face,
  1893. faceIndex: f,
  1894. object: object
  1895. } );
  1896. }
  1897. } else if ( face instanceof THREE.Face4 ) {
  1898. a = vertices[ face.a ];
  1899. b = vertices[ face.b ];
  1900. c = vertices[ face.c ];
  1901. d = vertices[ face.d ];
  1902. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1903. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1904. distance = originCopy.distanceTo( point );
  1905. if ( distance < ray.near || distance > ray.far ) continue;
  1906. intersects.push( {
  1907. distance: distance,
  1908. point: point,
  1909. face: face,
  1910. faceIndex: f,
  1911. object: object
  1912. } );
  1913. }
  1914. }
  1915. }
  1916. }
  1917. }
  1918. };
  1919. var intersectDescendants = function ( object, ray, intersects ) {
  1920. var descendants = object.getDescendants();
  1921. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1922. intersectObject( descendants[ i ], ray, intersects );
  1923. }
  1924. };
  1925. //
  1926. THREE.Ray.prototype.precision = 0.0001;
  1927. THREE.Ray.prototype.set = function ( origin, direction ) {
  1928. this.origin = origin;
  1929. this.direction = direction;
  1930. };
  1931. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1932. var intersects = [];
  1933. if ( recursive === true ) {
  1934. intersectDescendants( object, this, intersects );
  1935. }
  1936. intersectObject( object, this, intersects );
  1937. intersects.sort( descSort );
  1938. return intersects;
  1939. };
  1940. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1941. var intersects = [];
  1942. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1943. intersectObject( objects[ i ], this, intersects );
  1944. if ( recursive === true ) {
  1945. intersectDescendants( objects[ i ], this, intersects );
  1946. }
  1947. }
  1948. intersects.sort( descSort );
  1949. return intersects;
  1950. };
  1951. }( THREE ) );
  1952. /**
  1953. * @author mrdoob / http://mrdoob.com/
  1954. */
  1955. THREE.Rectangle = function () {
  1956. var _left = 0;
  1957. var _top = 0;
  1958. var _right = 0;
  1959. var _bottom = 0;
  1960. var _width = 0;
  1961. var _height = 0;
  1962. var _isEmpty = true;
  1963. function resize() {
  1964. _width = _right - _left;
  1965. _height = _bottom - _top;
  1966. }
  1967. this.getX = function () {
  1968. return _left;
  1969. };
  1970. this.getY = function () {
  1971. return _top;
  1972. };
  1973. this.getWidth = function () {
  1974. return _width;
  1975. };
  1976. this.getHeight = function () {
  1977. return _height;
  1978. };
  1979. this.getLeft = function() {
  1980. return _left;
  1981. };
  1982. this.getTop = function() {
  1983. return _top;
  1984. };
  1985. this.getRight = function() {
  1986. return _right;
  1987. };
  1988. this.getBottom = function() {
  1989. return _bottom;
  1990. };
  1991. this.set = function ( left, top, right, bottom ) {
  1992. _isEmpty = false;
  1993. _left = left; _top = top;
  1994. _right = right; _bottom = bottom;
  1995. resize();
  1996. };
  1997. this.addPoint = function ( x, y ) {
  1998. if ( _isEmpty === true ) {
  1999. _isEmpty = false;
  2000. _left = x; _top = y;
  2001. _right = x; _bottom = y;
  2002. resize();
  2003. } else {
  2004. _left = _left < x ? _left : x; // Math.min( _left, x );
  2005. _top = _top < y ? _top : y; // Math.min( _top, y );
  2006. _right = _right > x ? _right : x; // Math.max( _right, x );
  2007. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  2008. resize();
  2009. }
  2010. };
  2011. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  2012. if ( _isEmpty === true ) {
  2013. _isEmpty = false;
  2014. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  2015. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  2016. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  2017. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  2018. resize();
  2019. } else {
  2020. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  2021. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  2022. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  2023. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  2024. resize();
  2025. };
  2026. };
  2027. this.addRectangle = function ( r ) {
  2028. if ( _isEmpty === true ) {
  2029. _isEmpty = false;
  2030. _left = r.getLeft(); _top = r.getTop();
  2031. _right = r.getRight(); _bottom = r.getBottom();
  2032. resize();
  2033. } else {
  2034. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  2035. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  2036. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  2037. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  2038. resize();
  2039. }
  2040. };
  2041. this.inflate = function ( v ) {
  2042. _left -= v; _top -= v;
  2043. _right += v; _bottom += v;
  2044. resize();
  2045. };
  2046. this.minSelf = function ( r ) {
  2047. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  2048. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  2049. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  2050. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  2051. resize();
  2052. };
  2053. this.intersects = function ( r ) {
  2054. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  2055. if ( _right < r.getLeft() ) return false;
  2056. if ( _left > r.getRight() ) return false;
  2057. if ( _bottom < r.getTop() ) return false;
  2058. if ( _top > r.getBottom() ) return false;
  2059. return true;
  2060. };
  2061. this.empty = function () {
  2062. _isEmpty = true;
  2063. _left = 0; _top = 0;
  2064. _right = 0; _bottom = 0;
  2065. resize();
  2066. };
  2067. this.isEmpty = function () {
  2068. return _isEmpty;
  2069. };
  2070. };
  2071. /**
  2072. * @author alteredq / http://alteredqualia.com/
  2073. */
  2074. THREE.Math = {
  2075. // Clamp value to range <a, b>
  2076. clamp: function ( x, a, b ) {
  2077. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2078. },
  2079. // Clamp value to range <a, inf)
  2080. clampBottom: function ( x, a ) {
  2081. return x < a ? a : x;
  2082. },
  2083. // Linear mapping from range <a1, a2> to range <b1, b2>
  2084. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2085. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2086. },
  2087. // Random float from <0, 1> with 16 bits of randomness
  2088. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2089. random16: function () {
  2090. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2091. },
  2092. // Random integer from <low, high> interval
  2093. randInt: function ( low, high ) {
  2094. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2095. },
  2096. // Random float from <low, high> interval
  2097. randFloat: function ( low, high ) {
  2098. return low + Math.random() * ( high - low );
  2099. },
  2100. // Random float from <-range/2, range/2> interval
  2101. randFloatSpread: function ( range ) {
  2102. return range * ( 0.5 - Math.random() );
  2103. },
  2104. sign: function ( x ) {
  2105. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2106. }
  2107. };
  2108. /**
  2109. * @author mrdoob / http://mrdoob.com/
  2110. * @author mikael emtinger / http://gomo.se/
  2111. * @author alteredq / http://alteredqualia.com/
  2112. */
  2113. THREE.Object3D = function () {
  2114. THREE.Object3DLibrary.push( this );
  2115. this.id = THREE.Object3DIdCount ++;
  2116. this.name = '';
  2117. this.properties = {};
  2118. this.parent = undefined;
  2119. this.children = [];
  2120. this.up = new THREE.Vector3( 0, 1, 0 );
  2121. this.position = new THREE.Vector3();
  2122. this.rotation = new THREE.Vector3();
  2123. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2124. this.scale = new THREE.Vector3( 1, 1, 1 );
  2125. this.renderDepth = null;
  2126. this.rotationAutoUpdate = true;
  2127. this.matrix = new THREE.Matrix4();
  2128. this.matrixWorld = new THREE.Matrix4();
  2129. this.matrixRotationWorld = new THREE.Matrix4();
  2130. this.matrixAutoUpdate = true;
  2131. this.matrixWorldNeedsUpdate = true;
  2132. this.quaternion = new THREE.Quaternion();
  2133. this.useQuaternion = false;
  2134. this.boundRadius = 0.0;
  2135. this.boundRadiusScale = 1.0;
  2136. this.visible = true;
  2137. this.castShadow = false;
  2138. this.receiveShadow = false;
  2139. this.frustumCulled = true;
  2140. this._vector = new THREE.Vector3();
  2141. };
  2142. THREE.Object3D.prototype = {
  2143. constructor: THREE.Object3D,
  2144. applyMatrix: function ( matrix ) {
  2145. this.matrix.multiply( matrix, this.matrix );
  2146. this.scale.getScaleFromMatrix( this.matrix );
  2147. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2148. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2149. this.position.getPositionFromMatrix( this.matrix );
  2150. },
  2151. translate: function ( distance, axis ) {
  2152. this.matrix.rotateAxis( axis );
  2153. this.position.addSelf( axis.multiplyScalar( distance ) );
  2154. },
  2155. translateX: function ( distance ) {
  2156. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2157. },
  2158. translateY: function ( distance ) {
  2159. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2160. },
  2161. translateZ: function ( distance ) {
  2162. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2163. },
  2164. localToWorld: function ( vector ) {
  2165. return this.matrixWorld.multiplyVector3( vector );
  2166. },
  2167. worldToLocal: function ( vector ) {
  2168. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2169. },
  2170. lookAt: function ( vector ) {
  2171. // TODO: Add hierarchy support.
  2172. this.matrix.lookAt( vector, this.position, this.up );
  2173. if ( this.rotationAutoUpdate ) {
  2174. if ( this.useQuaternion === false ) {
  2175. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2176. } else {
  2177. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  2178. }
  2179. }
  2180. },
  2181. add: function ( object ) {
  2182. if ( object === this ) {
  2183. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2184. return;
  2185. }
  2186. if ( object instanceof THREE.Object3D ) {
  2187. if ( object.parent !== undefined ) {
  2188. object.parent.remove( object );
  2189. }
  2190. object.parent = this;
  2191. this.children.push( object );
  2192. // add to scene
  2193. var scene = this;
  2194. while ( scene.parent !== undefined ) {
  2195. scene = scene.parent;
  2196. }
  2197. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2198. scene.__addObject( object );
  2199. }
  2200. }
  2201. },
  2202. remove: function ( object ) {
  2203. var index = this.children.indexOf( object );
  2204. if ( index !== - 1 ) {
  2205. object.parent = undefined;
  2206. this.children.splice( index, 1 );
  2207. // remove from scene
  2208. var scene = this;
  2209. while ( scene.parent !== undefined ) {
  2210. scene = scene.parent;
  2211. }
  2212. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2213. scene.__removeObject( object );
  2214. }
  2215. }
  2216. },
  2217. traverse: function ( callback ) {
  2218. callback( this );
  2219. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2220. this.children[ i ].traverse( callback );
  2221. }
  2222. },
  2223. getChildByName: function ( name, recursive ) {
  2224. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2225. var child = this.children[ i ];
  2226. if ( child.name === name ) {
  2227. return child;
  2228. }
  2229. if ( recursive === true ) {
  2230. child = child.getChildByName( name, recursive );
  2231. if ( child !== undefined ) {
  2232. return child;
  2233. }
  2234. }
  2235. }
  2236. return undefined;
  2237. },
  2238. getDescendants: function ( array ) {
  2239. if ( array === undefined ) array = [];
  2240. Array.prototype.push.apply( array, this.children );
  2241. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2242. this.children[ i ].getDescendants( array );
  2243. }
  2244. return array;
  2245. },
  2246. updateMatrix: function () {
  2247. this.matrix.setPosition( this.position );
  2248. if ( this.useQuaternion === false ) {
  2249. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2250. } else {
  2251. this.matrix.setRotationFromQuaternion( this.quaternion );
  2252. }
  2253. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2254. this.matrix.scale( this.scale );
  2255. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2256. }
  2257. this.matrixWorldNeedsUpdate = true;
  2258. },
  2259. updateMatrixWorld: function ( force ) {
  2260. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2261. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2262. if ( this.parent === undefined ) {
  2263. this.matrixWorld.copy( this.matrix );
  2264. } else {
  2265. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2266. }
  2267. this.matrixWorldNeedsUpdate = false;
  2268. force = true;
  2269. }
  2270. // update children
  2271. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2272. this.children[ i ].updateMatrixWorld( force );
  2273. }
  2274. },
  2275. clone: function ( object ) {
  2276. if ( object === undefined ) object = new THREE.Object3D();
  2277. object.name = this.name;
  2278. object.up.copy( this.up );
  2279. object.position.copy( this.position );
  2280. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2281. object.eulerOrder = this.eulerOrder;
  2282. object.scale.copy( this.scale );
  2283. object.renderDepth = this.renderDepth;
  2284. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2285. object.matrix.copy( this.matrix );
  2286. object.matrixWorld.copy( this.matrixWorld );
  2287. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2288. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2289. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2290. object.quaternion.copy( this.quaternion );
  2291. object.useQuaternion = this.useQuaternion;
  2292. object.boundRadius = this.boundRadius;
  2293. object.boundRadiusScale = this.boundRadiusScale;
  2294. object.visible = this.visible;
  2295. object.castShadow = this.castShadow;
  2296. object.receiveShadow = this.receiveShadow;
  2297. object.frustumCulled = this.frustumCulled;
  2298. for ( var i = 0; i < this.children.length; i ++ ) {
  2299. var child = this.children[ i ];
  2300. object.add( child.clone() );
  2301. }
  2302. return object;
  2303. },
  2304. deallocate: function () {
  2305. var index = THREE.Object3DLibrary.indexOf( this );
  2306. if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
  2307. }
  2308. };
  2309. THREE.Object3D.__m1 = new THREE.Matrix4();
  2310. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2311. THREE.Object3DIdCount = 0;
  2312. THREE.Object3DLibrary = [];
  2313. /**
  2314. * @author mrdoob / http://mrdoob.com/
  2315. * @author supereggbert / http://www.paulbrunt.co.uk/
  2316. * @author julianwa / https://github.com/julianwa
  2317. */
  2318. THREE.Projector = function() {
  2319. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2320. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2321. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2322. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2323. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2324. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2325. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2326. _vector3 = new THREE.Vector3(),
  2327. _vector4 = new THREE.Vector4(),
  2328. _viewProjectionMatrix = new THREE.Matrix4(),
  2329. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2330. _normalMatrix = new THREE.Matrix3(),
  2331. _frustum = new THREE.Frustum(),
  2332. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2333. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2334. _face3VertexNormals;
  2335. this.projectVector = function ( vector, camera ) {
  2336. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2337. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2338. _viewProjectionMatrix.multiplyVector3( vector );
  2339. return vector;
  2340. };
  2341. this.unprojectVector = function ( vector, camera ) {
  2342. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2343. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2344. _viewProjectionMatrix.multiplyVector3( vector );
  2345. return vector;
  2346. };
  2347. this.pickingRay = function ( vector, camera ) {
  2348. var end, ray, t;
  2349. // set two vectors with opposing z values
  2350. vector.z = -1.0;
  2351. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2352. this.unprojectVector( vector, camera );
  2353. this.unprojectVector( end, camera );
  2354. // find direction from vector to end
  2355. end.subSelf( vector ).normalize();
  2356. return new THREE.Ray( vector, end );
  2357. };
  2358. var projectGraph = function ( root, sortObjects ) {
  2359. _objectCount = 0;
  2360. _renderData.objects.length = 0;
  2361. _renderData.sprites.length = 0;
  2362. _renderData.lights.length = 0;
  2363. var projectObject = function ( parent ) {
  2364. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  2365. var object = parent.children[ c ];
  2366. if ( object.visible === false ) continue;
  2367. if ( object instanceof THREE.Light ) {
  2368. _renderData.lights.push( object );
  2369. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  2370. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  2371. _object = getNextObjectInPool();
  2372. _object.object = object;
  2373. if ( object.renderDepth !== null ) {
  2374. _object.z = object.renderDepth;
  2375. } else {
  2376. _vector3.copy( object.matrixWorld.getPosition() );
  2377. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2378. _object.z = _vector3.z;
  2379. }
  2380. _renderData.objects.push( _object );
  2381. }
  2382. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2383. _object = getNextObjectInPool();
  2384. _object.object = object;
  2385. // TODO: Find an elegant and performant solution and remove this dupe code.
  2386. if ( object.renderDepth !== null ) {
  2387. _object.z = object.renderDepth;
  2388. } else {
  2389. _vector3.copy( object.matrixWorld.getPosition() );
  2390. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2391. _object.z = _vector3.z;
  2392. }
  2393. _renderData.sprites.push( _object );
  2394. } else {
  2395. _object = getNextObjectInPool();
  2396. _object.object = object;
  2397. if ( object.renderDepth !== null ) {
  2398. _object.z = object.renderDepth;
  2399. } else {
  2400. _vector3.copy( object.matrixWorld.getPosition() );
  2401. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2402. _object.z = _vector3.z;
  2403. }
  2404. _renderData.objects.push( _object );
  2405. }
  2406. projectObject( object );
  2407. }
  2408. };
  2409. projectObject( root );
  2410. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  2411. return _renderData;
  2412. };
  2413. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  2414. var near = camera.near, far = camera.far, visible = false,
  2415. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object, modelMatrix,
  2416. geometry, vertices, vertex, vertexPositionScreen,
  2417. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2418. v1, v2, v3, v4, isFaceMaterial, objectMaterials, material, side;
  2419. _face3Count = 0;
  2420. _face4Count = 0;
  2421. _lineCount = 0;
  2422. _particleCount = 0;
  2423. _renderData.elements.length = 0;
  2424. scene.updateMatrixWorld();
  2425. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2426. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2427. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2428. _frustum.setFromMatrix( _viewProjectionMatrix );
  2429. _renderData = projectGraph( scene, sortObjects );
  2430. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  2431. object = _renderData.objects[ o ].object;
  2432. modelMatrix = object.matrixWorld;
  2433. _vertexCount = 0;
  2434. if ( object instanceof THREE.Mesh ) {
  2435. geometry = object.geometry;
  2436. vertices = geometry.vertices;
  2437. faces = geometry.faces;
  2438. faceVertexUvs = geometry.faceVertexUvs;
  2439. _normalMatrix.getInverse( modelMatrix );
  2440. _normalMatrix.transpose();
  2441. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2442. objectMaterials = isFaceMaterial === true ? object.material : null;
  2443. side = object.material.side;
  2444. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2445. _vertex = getNextVertexInPool();
  2446. _vertex.positionWorld.copy( vertices[ v ] );
  2447. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2448. _vertex.positionScreen.copy( _vertex.positionWorld );
  2449. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2450. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2451. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2452. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2453. }
  2454. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2455. face = faces[ f ];
  2456. material = isFaceMaterial === true ? objectMaterials.materials[ face.materialIndex ] : object.material;
  2457. if ( material === undefined ) continue;
  2458. side = material.side;
  2459. if ( face instanceof THREE.Face3 ) {
  2460. v1 = _vertexPool[ face.a ];
  2461. v2 = _vertexPool[ face.b ];
  2462. v3 = _vertexPool[ face.c ];
  2463. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2464. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2465. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2466. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2467. _face = getNextFace3InPool();
  2468. _face.v1.copy( v1 );
  2469. _face.v2.copy( v2 );
  2470. _face.v3.copy( v3 );
  2471. } else {
  2472. continue;
  2473. }
  2474. } else {
  2475. continue;
  2476. }
  2477. } else if ( face instanceof THREE.Face4 ) {
  2478. v1 = _vertexPool[ face.a ];
  2479. v2 = _vertexPool[ face.b ];
  2480. v3 = _vertexPool[ face.c ];
  2481. v4 = _vertexPool[ face.d ];
  2482. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2483. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2484. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2485. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2486. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2487. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2488. _face = getNextFace4InPool();
  2489. _face.v1.copy( v1 );
  2490. _face.v2.copy( v2 );
  2491. _face.v3.copy( v3 );
  2492. _face.v4.copy( v4 );
  2493. } else {
  2494. continue;
  2495. }
  2496. } else {
  2497. continue;
  2498. }
  2499. }
  2500. _face.normalWorld.copy( face.normal );
  2501. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2502. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  2503. _face.centroidWorld.copy( face.centroid );
  2504. modelMatrix.multiplyVector3( _face.centroidWorld );
  2505. _face.centroidScreen.copy( _face.centroidWorld );
  2506. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2507. faceVertexNormals = face.vertexNormals;
  2508. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2509. normal = _face.vertexNormalsWorld[ n ];
  2510. normal.copy( faceVertexNormals[ n ] );
  2511. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2512. _normalMatrix.multiplyVector3( normal ).normalize();
  2513. }
  2514. _face.vertexNormalsLength = faceVertexNormals.length;
  2515. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2516. uvs = faceVertexUvs[ c ][ f ];
  2517. if ( uvs === undefined ) continue;
  2518. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2519. _face.uvs[ c ][ u ] = uvs[ u ];
  2520. }
  2521. }
  2522. _face.color = face.color;
  2523. _face.material = material;
  2524. _face.z = _face.centroidScreen.z;
  2525. _renderData.elements.push( _face );
  2526. }
  2527. } else if ( object instanceof THREE.Line ) {
  2528. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2529. vertices = object.geometry.vertices;
  2530. v1 = getNextVertexInPool();
  2531. v1.positionScreen.copy( vertices[ 0 ] );
  2532. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2533. // Handle LineStrip and LinePieces
  2534. var step = object.type === THREE.LinePieces ? 2 : 1;
  2535. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2536. v1 = getNextVertexInPool();
  2537. v1.positionScreen.copy( vertices[ v ] );
  2538. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2539. if ( ( v + 1 ) % step > 0 ) continue;
  2540. v2 = _vertexPool[ _vertexCount - 2 ];
  2541. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2542. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2543. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2544. // Perform the perspective divide
  2545. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2546. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2547. _line = getNextLineInPool();
  2548. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2549. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2550. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2551. _line.material = object.material;
  2552. _renderData.elements.push( _line );
  2553. }
  2554. }
  2555. }
  2556. }
  2557. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2558. object = _renderData.sprites[ o ].object;
  2559. modelMatrix = object.matrixWorld;
  2560. if ( object instanceof THREE.Particle ) {
  2561. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2562. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2563. _vector4.z /= _vector4.w;
  2564. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2565. _particle = getNextParticleInPool();
  2566. _particle.object = object;
  2567. _particle.x = _vector4.x / _vector4.w;
  2568. _particle.y = _vector4.y / _vector4.w;
  2569. _particle.z = _vector4.z;
  2570. _particle.rotation = object.rotation.z;
  2571. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2572. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2573. _particle.material = object.material;
  2574. _renderData.elements.push( _particle );
  2575. }
  2576. }
  2577. }
  2578. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  2579. return _renderData;
  2580. };
  2581. // Pools
  2582. function getNextObjectInPool() {
  2583. if ( _objectCount === _objectPoolLength ) {
  2584. var object = new THREE.RenderableObject();
  2585. _objectPool.push( object );
  2586. _objectPoolLength ++;
  2587. _objectCount ++;
  2588. return object;
  2589. }
  2590. return _objectPool[ _objectCount ++ ];
  2591. }
  2592. function getNextVertexInPool() {
  2593. if ( _vertexCount === _vertexPoolLength ) {
  2594. var vertex = new THREE.RenderableVertex();
  2595. _vertexPool.push( vertex );
  2596. _vertexPoolLength ++;
  2597. _vertexCount ++;
  2598. return vertex;
  2599. }
  2600. return _vertexPool[ _vertexCount ++ ];
  2601. }
  2602. function getNextFace3InPool() {
  2603. if ( _face3Count === _face3PoolLength ) {
  2604. var face = new THREE.RenderableFace3();
  2605. _face3Pool.push( face );
  2606. _face3PoolLength ++;
  2607. _face3Count ++;
  2608. return face;
  2609. }
  2610. return _face3Pool[ _face3Count ++ ];
  2611. }
  2612. function getNextFace4InPool() {
  2613. if ( _face4Count === _face4PoolLength ) {
  2614. var face = new THREE.RenderableFace4();
  2615. _face4Pool.push( face );
  2616. _face4PoolLength ++;
  2617. _face4Count ++;
  2618. return face;
  2619. }
  2620. return _face4Pool[ _face4Count ++ ];
  2621. }
  2622. function getNextLineInPool() {
  2623. if ( _lineCount === _linePoolLength ) {
  2624. var line = new THREE.RenderableLine();
  2625. _linePool.push( line );
  2626. _linePoolLength ++;
  2627. _lineCount ++
  2628. return line;
  2629. }
  2630. return _linePool[ _lineCount ++ ];
  2631. }
  2632. function getNextParticleInPool() {
  2633. if ( _particleCount === _particlePoolLength ) {
  2634. var particle = new THREE.RenderableParticle();
  2635. _particlePool.push( particle );
  2636. _particlePoolLength ++;
  2637. _particleCount ++
  2638. return particle;
  2639. }
  2640. return _particlePool[ _particleCount ++ ];
  2641. }
  2642. //
  2643. function painterSort( a, b ) {
  2644. return b.z - a.z;
  2645. }
  2646. function clipLine( s1, s2 ) {
  2647. var alpha1 = 0, alpha2 = 1,
  2648. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2649. // Z = -1 and Z = +1, respectively.
  2650. bc1near = s1.z + s1.w,
  2651. bc2near = s2.z + s2.w,
  2652. bc1far = - s1.z + s1.w,
  2653. bc2far = - s2.z + s2.w;
  2654. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2655. // Both vertices lie entirely within all clip planes.
  2656. return true;
  2657. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2658. // Both vertices lie entirely outside one of the clip planes.
  2659. return false;
  2660. } else {
  2661. // The line segment spans at least one clip plane.
  2662. if ( bc1near < 0 ) {
  2663. // v1 lies outside the near plane, v2 inside
  2664. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2665. } else if ( bc2near < 0 ) {
  2666. // v2 lies outside the near plane, v1 inside
  2667. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2668. }
  2669. if ( bc1far < 0 ) {
  2670. // v1 lies outside the far plane, v2 inside
  2671. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2672. } else if ( bc2far < 0 ) {
  2673. // v2 lies outside the far plane, v2 inside
  2674. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2675. }
  2676. if ( alpha2 < alpha1 ) {
  2677. // The line segment spans two boundaries, but is outside both of them.
  2678. // (This can't happen when we're only clipping against just near/far but good
  2679. // to leave the check here for future usage if other clip planes are added.)
  2680. return false;
  2681. } else {
  2682. // Update the s1 and s2 vertices to match the clipped line segment.
  2683. s1.lerpSelf( s2, alpha1 );
  2684. s2.lerpSelf( s1, 1 - alpha2 );
  2685. return true;
  2686. }
  2687. }
  2688. }
  2689. };
  2690. /**
  2691. * @author mikael emtinger / http://gomo.se/
  2692. * @author alteredq / http://alteredqualia.com/
  2693. * @author WestLangley / http://github.com/WestLangley
  2694. */
  2695. THREE.Quaternion = function( x, y, z, w ) {
  2696. this.x = x || 0;
  2697. this.y = y || 0;
  2698. this.z = z || 0;
  2699. this.w = ( w !== undefined ) ? w : 1;
  2700. };
  2701. THREE.Quaternion.prototype = {
  2702. constructor: THREE.Quaternion,
  2703. set: function ( x, y, z, w ) {
  2704. this.x = x;
  2705. this.y = y;
  2706. this.z = z;
  2707. this.w = w;
  2708. return this;
  2709. },
  2710. copy: function ( q ) {
  2711. this.x = q.x;
  2712. this.y = q.y;
  2713. this.z = q.z;
  2714. this.w = q.w;
  2715. return this;
  2716. },
  2717. setFromEuler: function ( v, order ) {
  2718. // http://www.mathworks.com/matlabcentral/fileexchange/
  2719. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2720. // content/SpinCalc.m
  2721. var c1 = Math.cos( v.x / 2 );
  2722. var c2 = Math.cos( v.y / 2 );
  2723. var c3 = Math.cos( v.z / 2 );
  2724. var s1 = Math.sin( v.x / 2 );
  2725. var s2 = Math.sin( v.y / 2 );
  2726. var s3 = Math.sin( v.z / 2 );
  2727. if ( order === undefined || order === 'XYZ' ) {
  2728. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2729. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2730. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2731. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2732. } else if ( order === 'YXZ' ) {
  2733. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2734. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2735. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2736. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2737. } else if ( order === 'ZXY' ) {
  2738. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2739. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2740. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2741. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2742. } else if ( order === 'ZYX' ) {
  2743. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2744. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2745. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2746. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2747. } else if ( order === 'YZX' ) {
  2748. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2749. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2750. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2751. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2752. } else if ( order === 'XZY' ) {
  2753. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2754. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2755. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2756. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2757. }
  2758. return this;
  2759. },
  2760. setFromAxisAngle: function ( axis, angle ) {
  2761. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2762. // axis have to be normalized
  2763. var halfAngle = angle / 2,
  2764. s = Math.sin( halfAngle );
  2765. this.x = axis.x * s;
  2766. this.y = axis.y * s;
  2767. this.z = axis.z * s;
  2768. this.w = Math.cos( halfAngle );
  2769. return this;
  2770. },
  2771. setFromRotationMatrix: function ( m ) {
  2772. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2773. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2774. var te = m.elements,
  2775. m11 = te[0], m12 = te[4], m13 = te[8],
  2776. m21 = te[1], m22 = te[5], m23 = te[9],
  2777. m31 = te[2], m32 = te[6], m33 = te[10],
  2778. trace = m11 + m22 + m33,
  2779. s;
  2780. if( trace > 0 ) {
  2781. s = 0.5 / Math.sqrt( trace + 1.0 );
  2782. this.w = 0.25 / s;
  2783. this.x = ( m32 - m23 ) * s;
  2784. this.y = ( m13 - m31 ) * s;
  2785. this.z = ( m21 - m12 ) * s;
  2786. } else if ( m11 > m22 && m11 > m33 ) {
  2787. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2788. this.w = (m32 - m23 ) / s;
  2789. this.x = 0.25 * s;
  2790. this.y = (m12 + m21 ) / s;
  2791. this.z = (m13 + m31 ) / s;
  2792. } else if (m22 > m33) {
  2793. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2794. this.w = (m13 - m31 ) / s;
  2795. this.x = (m12 + m21 ) / s;
  2796. this.y = 0.25 * s;
  2797. this.z = (m23 + m32 ) / s;
  2798. } else {
  2799. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2800. this.w = ( m21 - m12 ) / s;
  2801. this.x = ( m13 + m31 ) / s;
  2802. this.y = ( m23 + m32 ) / s;
  2803. this.z = 0.25 * s;
  2804. }
  2805. return this;
  2806. },
  2807. inverse: function () {
  2808. this.conjugate().normalize();
  2809. return this;
  2810. },
  2811. conjugate: function () {
  2812. this.x *= -1;
  2813. this.y *= -1;
  2814. this.z *= -1;
  2815. return this;
  2816. },
  2817. length: function () {
  2818. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2819. },
  2820. normalize: function () {
  2821. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2822. if ( l === 0 ) {
  2823. this.x = 0;
  2824. this.y = 0;
  2825. this.z = 0;
  2826. this.w = 1;
  2827. } else {
  2828. l = 1 / l;
  2829. this.x = this.x * l;
  2830. this.y = this.y * l;
  2831. this.z = this.z * l;
  2832. this.w = this.w * l;
  2833. }
  2834. return this;
  2835. },
  2836. multiply: function ( a, b ) {
  2837. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2838. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2839. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2840. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2841. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2842. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2843. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2844. return this;
  2845. },
  2846. multiplySelf: function ( b ) {
  2847. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2848. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2849. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2850. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2851. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2852. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2853. return this;
  2854. },
  2855. multiplyVector3: function ( vector, dest ) {
  2856. if ( !dest ) { dest = vector; }
  2857. var x = vector.x, y = vector.y, z = vector.z,
  2858. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2859. // calculate quat * vector
  2860. var ix = qw * x + qy * z - qz * y,
  2861. iy = qw * y + qz * x - qx * z,
  2862. iz = qw * z + qx * y - qy * x,
  2863. iw = -qx * x - qy * y - qz * z;
  2864. // calculate result * inverse quat
  2865. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2866. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2867. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2868. return dest;
  2869. },
  2870. slerpSelf: function ( qb, t ) {
  2871. var x = this.x, y = this.y, z = this.z, w = this.w;
  2872. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2873. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2874. if ( cosHalfTheta < 0 ) {
  2875. this.w = -qb.w;
  2876. this.x = -qb.x;
  2877. this.y = -qb.y;
  2878. this.z = -qb.z;
  2879. cosHalfTheta = -cosHalfTheta;
  2880. } else {
  2881. this.copy( qb );
  2882. }
  2883. if ( cosHalfTheta >= 1.0 ) {
  2884. this.w = w;
  2885. this.x = x;
  2886. this.y = y;
  2887. this.z = z;
  2888. return this;
  2889. }
  2890. var halfTheta = Math.acos( cosHalfTheta );
  2891. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2892. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2893. this.w = 0.5 * ( w + this.w );
  2894. this.x = 0.5 * ( x + this.x );
  2895. this.y = 0.5 * ( y + this.y );
  2896. this.z = 0.5 * ( z + this.z );
  2897. return this;
  2898. }
  2899. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2900. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2901. this.w = ( w * ratioA + this.w * ratioB );
  2902. this.x = ( x * ratioA + this.x * ratioB );
  2903. this.y = ( y * ratioA + this.y * ratioB );
  2904. this.z = ( z * ratioA + this.z * ratioB );
  2905. return this;
  2906. },
  2907. clone: function () {
  2908. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2909. }
  2910. }
  2911. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2912. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2913. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2914. if ( cosHalfTheta < 0 ) {
  2915. qm.w = -qb.w;
  2916. qm.x = -qb.x;
  2917. qm.y = -qb.y;
  2918. qm.z = -qb.z;
  2919. cosHalfTheta = -cosHalfTheta;
  2920. } else {
  2921. qm.copy( qb );
  2922. }
  2923. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2924. qm.w = qa.w;
  2925. qm.x = qa.x;
  2926. qm.y = qa.y;
  2927. qm.z = qa.z;
  2928. return qm;
  2929. }
  2930. var halfTheta = Math.acos( cosHalfTheta );
  2931. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2932. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2933. qm.w = 0.5 * ( qa.w + qm.w );
  2934. qm.x = 0.5 * ( qa.x + qm.x );
  2935. qm.y = 0.5 * ( qa.y + qm.y );
  2936. qm.z = 0.5 * ( qa.z + qm.z );
  2937. return qm;
  2938. }
  2939. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2940. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2941. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2942. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2943. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2944. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2945. return qm;
  2946. }
  2947. /**
  2948. * @author mrdoob / http://mrdoob.com/
  2949. */
  2950. THREE.Vertex = function ( v ) {
  2951. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2952. return v;
  2953. };
  2954. /**
  2955. * @author mrdoob / http://mrdoob.com/
  2956. * @author alteredq / http://alteredqualia.com/
  2957. */
  2958. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2959. this.a = a;
  2960. this.b = b;
  2961. this.c = c;
  2962. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2963. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2964. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2965. this.vertexColors = color instanceof Array ? color : [];
  2966. this.vertexTangents = [];
  2967. this.materialIndex = materialIndex;
  2968. this.centroid = new THREE.Vector3();
  2969. };
  2970. THREE.Face3.prototype = {
  2971. constructor: THREE.Face3,
  2972. clone: function () {
  2973. var face = new THREE.Face3( this.a, this.b, this.c );
  2974. face.normal.copy( this.normal );
  2975. face.color.copy( this.color );
  2976. face.centroid.copy( this.centroid );
  2977. face.materialIndex = this.materialIndex;
  2978. var i, il;
  2979. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2980. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2981. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2982. return face;
  2983. }
  2984. };
  2985. /**
  2986. * @author mrdoob / http://mrdoob.com/
  2987. * @author alteredq / http://alteredqualia.com/
  2988. */
  2989. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2990. this.a = a;
  2991. this.b = b;
  2992. this.c = c;
  2993. this.d = d;
  2994. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2995. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2996. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2997. this.vertexColors = color instanceof Array ? color : [];
  2998. this.vertexTangents = [];
  2999. this.materialIndex = materialIndex;
  3000. this.centroid = new THREE.Vector3();
  3001. };
  3002. THREE.Face4.prototype = {
  3003. constructor: THREE.Face4,
  3004. clone: function () {
  3005. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3006. face.normal.copy( this.normal );
  3007. face.color.copy( this.color );
  3008. face.centroid.copy( this.centroid );
  3009. face.materialIndex = this.materialIndex;
  3010. var i, il;
  3011. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3012. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3013. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3014. return face;
  3015. }
  3016. };
  3017. /**
  3018. * @author mrdoob / http://mrdoob.com/
  3019. */
  3020. THREE.UV = function ( u, v ) {
  3021. this.u = u || 0;
  3022. this.v = v || 0;
  3023. };
  3024. THREE.UV.prototype = {
  3025. constructor: THREE.UV,
  3026. set: function ( u, v ) {
  3027. this.u = u;
  3028. this.v = v;
  3029. return this;
  3030. },
  3031. copy: function ( uv ) {
  3032. this.u = uv.u;
  3033. this.v = uv.v;
  3034. return this;
  3035. },
  3036. lerpSelf: function ( uv, alpha ) {
  3037. this.u += ( uv.u - this.u ) * alpha;
  3038. this.v += ( uv.v - this.v ) * alpha;
  3039. return this;
  3040. },
  3041. clone: function () {
  3042. return new THREE.UV( this.u, this.v );
  3043. }
  3044. };
  3045. /**
  3046. * @author mrdoob / http://mrdoob.com/
  3047. * @author kile / http://kile.stravaganza.org/
  3048. * @author alteredq / http://alteredqualia.com/
  3049. * @author mikael emtinger / http://gomo.se/
  3050. * @author zz85 / http://www.lab4games.net/zz85/blog
  3051. */
  3052. THREE.Geometry = function () {
  3053. THREE.GeometryLibrary.push( this );
  3054. this.id = THREE.GeometryIdCount ++;
  3055. this.name = '';
  3056. this.vertices = [];
  3057. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3058. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3059. this.faces = [];
  3060. this.faceUvs = [[]];
  3061. this.faceVertexUvs = [[]];
  3062. this.morphTargets = [];
  3063. this.morphColors = [];
  3064. this.morphNormals = [];
  3065. this.skinWeights = [];
  3066. this.skinIndices = [];
  3067. this.lineDistances = [];
  3068. this.boundingBox = null;
  3069. this.boundingSphere = null;
  3070. this.hasTangents = false;
  3071. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3072. // update flags
  3073. this.verticesNeedUpdate = false;
  3074. this.elementsNeedUpdate = false;
  3075. this.uvsNeedUpdate = false;
  3076. this.normalsNeedUpdate = false;
  3077. this.tangentsNeedUpdate = false;
  3078. this.colorsNeedUpdate = false;
  3079. this.lineDistancesNeedUpdate = false;
  3080. this.buffersNeedUpdate = false;
  3081. };
  3082. THREE.Geometry.prototype = {
  3083. constructor : THREE.Geometry,
  3084. applyMatrix: function ( matrix ) {
  3085. var normalMatrix = new THREE.Matrix3();
  3086. normalMatrix.getInverse( matrix ).transpose();
  3087. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3088. var vertex = this.vertices[ i ];
  3089. matrix.multiplyVector3( vertex );
  3090. }
  3091. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3092. var face = this.faces[ i ];
  3093. normalMatrix.multiplyVector3( face.normal ).normalize();
  3094. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3095. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3096. }
  3097. matrix.multiplyVector3( face.centroid );
  3098. }
  3099. },
  3100. computeCentroids: function () {
  3101. var f, fl, face;
  3102. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3103. face = this.faces[ f ];
  3104. face.centroid.set( 0, 0, 0 );
  3105. if ( face instanceof THREE.Face3 ) {
  3106. face.centroid.addSelf( this.vertices[ face.a ] );
  3107. face.centroid.addSelf( this.vertices[ face.b ] );
  3108. face.centroid.addSelf( this.vertices[ face.c ] );
  3109. face.centroid.divideScalar( 3 );
  3110. } else if ( face instanceof THREE.Face4 ) {
  3111. face.centroid.addSelf( this.vertices[ face.a ] );
  3112. face.centroid.addSelf( this.vertices[ face.b ] );
  3113. face.centroid.addSelf( this.vertices[ face.c ] );
  3114. face.centroid.addSelf( this.vertices[ face.d ] );
  3115. face.centroid.divideScalar( 4 );
  3116. }
  3117. }
  3118. },
  3119. computeFaceNormals: function () {
  3120. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3121. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3122. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3123. face = this.faces[ f ];
  3124. vA = this.vertices[ face.a ];
  3125. vB = this.vertices[ face.b ];
  3126. vC = this.vertices[ face.c ];
  3127. cb.sub( vC, vB );
  3128. ab.sub( vA, vB );
  3129. cb.crossSelf( ab );
  3130. cb.normalize();
  3131. face.normal.copy( cb );
  3132. }
  3133. },
  3134. computeVertexNormals: function ( areaWeighted ) {
  3135. var v, vl, f, fl, face, vertices;
  3136. // create internal buffers for reuse when calling this method repeatedly
  3137. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3138. if ( this.__tmpVertices === undefined ) {
  3139. this.__tmpVertices = new Array( this.vertices.length );
  3140. vertices = this.__tmpVertices;
  3141. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3142. vertices[ v ] = new THREE.Vector3();
  3143. }
  3144. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3145. face = this.faces[ f ];
  3146. if ( face instanceof THREE.Face3 ) {
  3147. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3148. } else if ( face instanceof THREE.Face4 ) {
  3149. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3150. }
  3151. }
  3152. } else {
  3153. vertices = this.__tmpVertices;
  3154. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3155. vertices[ v ].set( 0, 0, 0 );
  3156. }
  3157. }
  3158. if ( areaWeighted ) {
  3159. // vertex normals weighted by triangle areas
  3160. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3161. var vA, vB, vC, vD;
  3162. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  3163. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  3164. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3165. face = this.faces[ f ];
  3166. if ( face instanceof THREE.Face3 ) {
  3167. vA = this.vertices[ face.a ];
  3168. vB = this.vertices[ face.b ];
  3169. vC = this.vertices[ face.c ];
  3170. cb.sub( vC, vB );
  3171. ab.sub( vA, vB );
  3172. cb.crossSelf( ab );
  3173. vertices[ face.a ].addSelf( cb );
  3174. vertices[ face.b ].addSelf( cb );
  3175. vertices[ face.c ].addSelf( cb );
  3176. } else if ( face instanceof THREE.Face4 ) {
  3177. vA = this.vertices[ face.a ];
  3178. vB = this.vertices[ face.b ];
  3179. vC = this.vertices[ face.c ];
  3180. vD = this.vertices[ face.d ];
  3181. // abd
  3182. db.sub( vD, vB );
  3183. ab.sub( vA, vB );
  3184. db.crossSelf( ab );
  3185. vertices[ face.a ].addSelf( db );
  3186. vertices[ face.b ].addSelf( db );
  3187. vertices[ face.d ].addSelf( db );
  3188. // bcd
  3189. dc.sub( vD, vC );
  3190. bc.sub( vB, vC );
  3191. dc.crossSelf( bc );
  3192. vertices[ face.b ].addSelf( dc );
  3193. vertices[ face.c ].addSelf( dc );
  3194. vertices[ face.d ].addSelf( dc );
  3195. }
  3196. }
  3197. } else {
  3198. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3199. face = this.faces[ f ];
  3200. if ( face instanceof THREE.Face3 ) {
  3201. vertices[ face.a ].addSelf( face.normal );
  3202. vertices[ face.b ].addSelf( face.normal );
  3203. vertices[ face.c ].addSelf( face.normal );
  3204. } else if ( face instanceof THREE.Face4 ) {
  3205. vertices[ face.a ].addSelf( face.normal );
  3206. vertices[ face.b ].addSelf( face.normal );
  3207. vertices[ face.c ].addSelf( face.normal );
  3208. vertices[ face.d ].addSelf( face.normal );
  3209. }
  3210. }
  3211. }
  3212. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3213. vertices[ v ].normalize();
  3214. }
  3215. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3216. face = this.faces[ f ];
  3217. if ( face instanceof THREE.Face3 ) {
  3218. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3219. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3220. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3221. } else if ( face instanceof THREE.Face4 ) {
  3222. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3223. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3224. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3225. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3226. }
  3227. }
  3228. },
  3229. computeMorphNormals: function () {
  3230. var i, il, f, fl, face;
  3231. // save original normals
  3232. // - create temp variables on first access
  3233. // otherwise just copy (for faster repeated calls)
  3234. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3235. face = this.faces[ f ];
  3236. if ( ! face.__originalFaceNormal ) {
  3237. face.__originalFaceNormal = face.normal.clone();
  3238. } else {
  3239. face.__originalFaceNormal.copy( face.normal );
  3240. }
  3241. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3242. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3243. if ( ! face.__originalVertexNormals[ i ] ) {
  3244. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3245. } else {
  3246. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3247. }
  3248. }
  3249. }
  3250. // use temp geometry to compute face and vertex normals for each morph
  3251. var tmpGeo = new THREE.Geometry();
  3252. tmpGeo.faces = this.faces;
  3253. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3254. // create on first access
  3255. if ( ! this.morphNormals[ i ] ) {
  3256. this.morphNormals[ i ] = {};
  3257. this.morphNormals[ i ].faceNormals = [];
  3258. this.morphNormals[ i ].vertexNormals = [];
  3259. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3260. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3261. var faceNormal, vertexNormals;
  3262. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3263. face = this.faces[ f ];
  3264. faceNormal = new THREE.Vector3();
  3265. if ( face instanceof THREE.Face3 ) {
  3266. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3267. } else {
  3268. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3269. }
  3270. dstNormalsFace.push( faceNormal );
  3271. dstNormalsVertex.push( vertexNormals );
  3272. }
  3273. }
  3274. var morphNormals = this.morphNormals[ i ];
  3275. // set vertices to morph target
  3276. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3277. // compute morph normals
  3278. tmpGeo.computeFaceNormals();
  3279. tmpGeo.computeVertexNormals();
  3280. // store morph normals
  3281. var faceNormal, vertexNormals;
  3282. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3283. face = this.faces[ f ];
  3284. faceNormal = morphNormals.faceNormals[ f ];
  3285. vertexNormals = morphNormals.vertexNormals[ f ];
  3286. faceNormal.copy( face.normal );
  3287. if ( face instanceof THREE.Face3 ) {
  3288. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3289. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3290. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3291. } else {
  3292. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3293. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3294. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3295. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3296. }
  3297. }
  3298. }
  3299. // restore original normals
  3300. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3301. face = this.faces[ f ];
  3302. face.normal = face.__originalFaceNormal;
  3303. face.vertexNormals = face.__originalVertexNormals;
  3304. }
  3305. },
  3306. computeTangents: function () {
  3307. // based on http://www.terathon.com/code/tangent.html
  3308. // tangents go to vertices
  3309. var f, fl, v, vl, i, il, vertexIndex,
  3310. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3311. x1, x2, y1, y2, z1, z2,
  3312. s1, s2, t1, t2, r, t, test,
  3313. tan1 = [], tan2 = [],
  3314. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3315. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3316. n = new THREE.Vector3(), w;
  3317. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3318. tan1[ v ] = new THREE.Vector3();
  3319. tan2[ v ] = new THREE.Vector3();
  3320. }
  3321. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3322. vA = context.vertices[ a ];
  3323. vB = context.vertices[ b ];
  3324. vC = context.vertices[ c ];
  3325. uvA = uv[ ua ];
  3326. uvB = uv[ ub ];
  3327. uvC = uv[ uc ];
  3328. x1 = vB.x - vA.x;
  3329. x2 = vC.x - vA.x;
  3330. y1 = vB.y - vA.y;
  3331. y2 = vC.y - vA.y;
  3332. z1 = vB.z - vA.z;
  3333. z2 = vC.z - vA.z;
  3334. s1 = uvB.u - uvA.u;
  3335. s2 = uvC.u - uvA.u;
  3336. t1 = uvB.v - uvA.v;
  3337. t2 = uvC.v - uvA.v;
  3338. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3339. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3340. ( t2 * y1 - t1 * y2 ) * r,
  3341. ( t2 * z1 - t1 * z2 ) * r );
  3342. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3343. ( s1 * y2 - s2 * y1 ) * r,
  3344. ( s1 * z2 - s2 * z1 ) * r );
  3345. tan1[ a ].addSelf( sdir );
  3346. tan1[ b ].addSelf( sdir );
  3347. tan1[ c ].addSelf( sdir );
  3348. tan2[ a ].addSelf( tdir );
  3349. tan2[ b ].addSelf( tdir );
  3350. tan2[ c ].addSelf( tdir );
  3351. }
  3352. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3353. face = this.faces[ f ];
  3354. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3355. if ( face instanceof THREE.Face3 ) {
  3356. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3357. } else if ( face instanceof THREE.Face4 ) {
  3358. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3359. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3360. }
  3361. }
  3362. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3363. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3364. face = this.faces[ f ];
  3365. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3366. n.copy( face.vertexNormals[ i ] );
  3367. vertexIndex = face[ faceIndex[ i ] ];
  3368. t = tan1[ vertexIndex ];
  3369. // Gram-Schmidt orthogonalize
  3370. tmp.copy( t );
  3371. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3372. // Calculate handedness
  3373. tmp2.cross( face.vertexNormals[ i ], t );
  3374. test = tmp2.dot( tan2[ vertexIndex ] );
  3375. w = (test < 0.0) ? -1.0 : 1.0;
  3376. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3377. }
  3378. }
  3379. this.hasTangents = true;
  3380. },
  3381. computeLineDistances: function ( ) {
  3382. var d = 0;
  3383. var vertices = this.vertices;
  3384. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3385. if ( i > 0 ) {
  3386. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  3387. }
  3388. this.lineDistances[ i ] = d;
  3389. }
  3390. },
  3391. computeBoundingBox: function () {
  3392. if ( ! this.boundingBox ) {
  3393. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3394. }
  3395. if ( this.vertices.length > 0 ) {
  3396. var position, firstPosition = this.vertices[ 0 ];
  3397. this.boundingBox.min.copy( firstPosition );
  3398. this.boundingBox.max.copy( firstPosition );
  3399. var min = this.boundingBox.min,
  3400. max = this.boundingBox.max;
  3401. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3402. position = this.vertices[ v ];
  3403. if ( position.x < min.x ) {
  3404. min.x = position.x;
  3405. } else if ( position.x > max.x ) {
  3406. max.x = position.x;
  3407. }
  3408. if ( position.y < min.y ) {
  3409. min.y = position.y;
  3410. } else if ( position.y > max.y ) {
  3411. max.y = position.y;
  3412. }
  3413. if ( position.z < min.z ) {
  3414. min.z = position.z;
  3415. } else if ( position.z > max.z ) {
  3416. max.z = position.z;
  3417. }
  3418. }
  3419. } else {
  3420. this.boundingBox.min.set( 0, 0, 0 );
  3421. this.boundingBox.max.set( 0, 0, 0 );
  3422. }
  3423. },
  3424. computeBoundingSphere: function () {
  3425. var maxRadiusSq = 0;
  3426. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3427. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3428. var radiusSq = this.vertices[ i ].lengthSq();
  3429. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3430. }
  3431. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3432. },
  3433. /*
  3434. * Checks for duplicate vertices with hashmap.
  3435. * Duplicated vertices are removed
  3436. * and faces' vertices are updated.
  3437. */
  3438. mergeVertices: function () {
  3439. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3440. var unique = [], changes = [];
  3441. var v, key;
  3442. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3443. var precision = Math.pow( 10, precisionPoints );
  3444. var i,il, face;
  3445. var abcd = 'abcd', o, k, j, jl, u;
  3446. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3447. v = this.vertices[ i ];
  3448. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3449. if ( verticesMap[ key ] === undefined ) {
  3450. verticesMap[ key ] = i;
  3451. unique.push( this.vertices[ i ] );
  3452. changes[ i ] = unique.length - 1;
  3453. } else {
  3454. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3455. changes[ i ] = changes[ verticesMap[ key ] ];
  3456. }
  3457. };
  3458. // Start to patch face indices
  3459. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3460. face = this.faces[ i ];
  3461. if ( face instanceof THREE.Face3 ) {
  3462. face.a = changes[ face.a ];
  3463. face.b = changes[ face.b ];
  3464. face.c = changes[ face.c ];
  3465. } else if ( face instanceof THREE.Face4 ) {
  3466. face.a = changes[ face.a ];
  3467. face.b = changes[ face.b ];
  3468. face.c = changes[ face.c ];
  3469. face.d = changes[ face.d ];
  3470. // check dups in (a, b, c, d) and convert to -> face3
  3471. o = [ face.a, face.b, face.c, face.d ];
  3472. for ( k = 3; k > 0; k -- ) {
  3473. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3474. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3475. o.splice( k, 1 );
  3476. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3477. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3478. u = this.faceVertexUvs[ j ][ i ];
  3479. if ( u ) u.splice( k, 1 );
  3480. }
  3481. this.faces[ i ].vertexColors = face.vertexColors;
  3482. break;
  3483. }
  3484. }
  3485. }
  3486. }
  3487. // Use unique set of vertices
  3488. var diff = this.vertices.length - unique.length;
  3489. this.vertices = unique;
  3490. return diff;
  3491. },
  3492. clone: function () {
  3493. var geometry = new THREE.Geometry();
  3494. var vertices = this.vertices;
  3495. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  3496. geometry.vertices.push( vertices[ i ].clone() );
  3497. }
  3498. var faces = this.faces;
  3499. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  3500. geometry.faces.push( faces[ i ].clone() );
  3501. }
  3502. var uvs = this.faceVertexUvs[ 0 ];
  3503. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  3504. var uv = uvs[ i ], uvCopy = [];
  3505. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  3506. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  3507. }
  3508. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  3509. }
  3510. return geometry;
  3511. },
  3512. deallocate: function () {
  3513. var index = THREE.GeometryLibrary.indexOf( this );
  3514. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3515. }
  3516. };
  3517. THREE.GeometryIdCount = 0;
  3518. THREE.GeometryLibrary = [];
  3519. /**
  3520. * @author alteredq / http://alteredqualia.com/
  3521. */
  3522. THREE.BufferGeometry = function () {
  3523. THREE.GeometryLibrary.push( this );
  3524. this.id = THREE.GeometryIdCount ++;
  3525. // attributes
  3526. this.attributes = {};
  3527. // attributes typed arrays are kept only if dynamic flag is set
  3528. this.dynamic = false;
  3529. // offsets for chunks when using indexed elements
  3530. this.offsets = [];
  3531. // boundings
  3532. this.boundingBox = null;
  3533. this.boundingSphere = null;
  3534. this.hasTangents = false;
  3535. // for compatibility
  3536. this.morphTargets = [];
  3537. };
  3538. THREE.BufferGeometry.prototype = {
  3539. constructor : THREE.BufferGeometry,
  3540. applyMatrix: function ( matrix ) {
  3541. var positionArray;
  3542. var normalArray;
  3543. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3544. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3545. if ( positionArray !== undefined ) {
  3546. matrix.multiplyVector3Array( positionArray );
  3547. this.verticesNeedUpdate = true;
  3548. }
  3549. if ( normalArray !== undefined ) {
  3550. var normalMatrix = new THREE.Matrix3();
  3551. normalMatrix.getInverse( matrix ).transpose();
  3552. normalMatrix.multiplyVector3Array( normalArray );
  3553. this.normalizeNormals();
  3554. this.normalsNeedUpdate = true;
  3555. }
  3556. },
  3557. computeBoundingBox: function () {
  3558. if ( ! this.boundingBox ) {
  3559. this.boundingBox = {
  3560. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3561. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3562. };
  3563. }
  3564. var positions = this.attributes[ "position" ].array;
  3565. if ( positions ) {
  3566. var bb = this.boundingBox;
  3567. var x, y, z;
  3568. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3569. x = positions[ i ];
  3570. y = positions[ i + 1 ];
  3571. z = positions[ i + 2 ];
  3572. // bounding box
  3573. if ( x < bb.min.x ) {
  3574. bb.min.x = x;
  3575. } else if ( x > bb.max.x ) {
  3576. bb.max.x = x;
  3577. }
  3578. if ( y < bb.min.y ) {
  3579. bb.min.y = y;
  3580. } else if ( y > bb.max.y ) {
  3581. bb.max.y = y;
  3582. }
  3583. if ( z < bb.min.z ) {
  3584. bb.min.z = z;
  3585. } else if ( z > bb.max.z ) {
  3586. bb.max.z = z;
  3587. }
  3588. }
  3589. }
  3590. if ( positions === undefined || positions.length === 0 ) {
  3591. this.boundingBox.min.set( 0, 0, 0 );
  3592. this.boundingBox.max.set( 0, 0, 0 );
  3593. }
  3594. },
  3595. computeBoundingSphere: function () {
  3596. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3597. var positions = this.attributes[ "position" ].array;
  3598. if ( positions ) {
  3599. var radiusSq, maxRadiusSq = 0;
  3600. var x, y, z;
  3601. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3602. x = positions[ i ];
  3603. y = positions[ i + 1 ];
  3604. z = positions[ i + 2 ];
  3605. radiusSq = x * x + y * y + z * z;
  3606. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3607. }
  3608. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3609. }
  3610. },
  3611. computeVertexNormals: function () {
  3612. if ( this.attributes[ "position" ] ) {
  3613. var i, il;
  3614. var j, jl;
  3615. var nVertexElements = this.attributes[ "position" ].array.length;
  3616. if ( this.attributes[ "normal" ] === undefined ) {
  3617. this.attributes[ "normal" ] = {
  3618. itemSize: 3,
  3619. array: new Float32Array( nVertexElements ),
  3620. numItems: nVertexElements
  3621. };
  3622. } else {
  3623. // reset existing normals to zero
  3624. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3625. this.attributes[ "normal" ].array[ i ] = 0;
  3626. }
  3627. }
  3628. var positions = this.attributes[ "position" ].array;
  3629. var normals = this.attributes[ "normal" ].array;
  3630. var vA, vB, vC, x, y, z,
  3631. pA = new THREE.Vector3(),
  3632. pB = new THREE.Vector3(),
  3633. pC = new THREE.Vector3(),
  3634. cb = new THREE.Vector3(),
  3635. ab = new THREE.Vector3();
  3636. // indexed elements
  3637. if ( this.attributes[ "index" ] ) {
  3638. var indices = this.attributes[ "index" ].array;
  3639. var offsets = this.offsets;
  3640. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3641. var start = offsets[ j ].start;
  3642. var count = offsets[ j ].count;
  3643. var index = offsets[ j ].index;
  3644. for ( i = start, il = start + count; i < il; i += 3 ) {
  3645. vA = index + indices[ i ];
  3646. vB = index + indices[ i + 1 ];
  3647. vC = index + indices[ i + 2 ];
  3648. x = positions[ vA * 3 ];
  3649. y = positions[ vA * 3 + 1 ];
  3650. z = positions[ vA * 3 + 2 ];
  3651. pA.set( x, y, z );
  3652. x = positions[ vB * 3 ];
  3653. y = positions[ vB * 3 + 1 ];
  3654. z = positions[ vB * 3 + 2 ];
  3655. pB.set( x, y, z );
  3656. x = positions[ vC * 3 ];
  3657. y = positions[ vC * 3 + 1 ];
  3658. z = positions[ vC * 3 + 2 ];
  3659. pC.set( x, y, z );
  3660. cb.sub( pC, pB );
  3661. ab.sub( pA, pB );
  3662. cb.crossSelf( ab );
  3663. normals[ vA * 3 ] += cb.x;
  3664. normals[ vA * 3 + 1 ] += cb.y;
  3665. normals[ vA * 3 + 2 ] += cb.z;
  3666. normals[ vB * 3 ] += cb.x;
  3667. normals[ vB * 3 + 1 ] += cb.y;
  3668. normals[ vB * 3 + 2 ] += cb.z;
  3669. normals[ vC * 3 ] += cb.x;
  3670. normals[ vC * 3 + 1 ] += cb.y;
  3671. normals[ vC * 3 + 2 ] += cb.z;
  3672. }
  3673. }
  3674. // non-indexed elements (unconnected triangle soup)
  3675. } else {
  3676. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  3677. x = positions[ i ];
  3678. y = positions[ i + 1 ];
  3679. z = positions[ i + 2 ];
  3680. pA.set( x, y, z );
  3681. x = positions[ i + 3 ];
  3682. y = positions[ i + 4 ];
  3683. z = positions[ i + 5 ];
  3684. pB.set( x, y, z );
  3685. x = positions[ i + 6 ];
  3686. y = positions[ i + 7 ];
  3687. z = positions[ i + 8 ];
  3688. pC.set( x, y, z );
  3689. cb.sub( pC, pB );
  3690. ab.sub( pA, pB );
  3691. cb.crossSelf( ab );
  3692. normals[ i ] = cb.x;
  3693. normals[ i + 1 ] = cb.y;
  3694. normals[ i + 2 ] = cb.z;
  3695. normals[ i + 3 ] = cb.x;
  3696. normals[ i + 4 ] = cb.y;
  3697. normals[ i + 5 ] = cb.z;
  3698. normals[ i + 6 ] = cb.x;
  3699. normals[ i + 7 ] = cb.y;
  3700. normals[ i + 8 ] = cb.z;
  3701. }
  3702. }
  3703. this.normalizeNormals();
  3704. this.normalsNeedUpdate = true;
  3705. }
  3706. },
  3707. normalizeNormals: function () {
  3708. var normals = this.attributes[ "normal" ].array;
  3709. var x, y, z, n;
  3710. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  3711. x = normals[ i ];
  3712. y = normals[ i + 1 ];
  3713. z = normals[ i + 2 ];
  3714. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3715. normals[ i ] *= n;
  3716. normals[ i + 1 ] *= n;
  3717. normals[ i + 2 ] *= n;
  3718. }
  3719. },
  3720. computeTangents: function () {
  3721. // based on http://www.terathon.com/code/tangent.html
  3722. // (per vertex tangents)
  3723. if ( this.attributes[ "index" ] === undefined ||
  3724. this.attributes[ "position" ] === undefined ||
  3725. this.attributes[ "normal" ] === undefined ||
  3726. this.attributes[ "uv" ] === undefined ) {
  3727. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3728. return;
  3729. }
  3730. var indices = this.attributes[ "index" ].array;
  3731. var positions = this.attributes[ "position" ].array;
  3732. var normals = this.attributes[ "normal" ].array;
  3733. var uvs = this.attributes[ "uv" ].array;
  3734. var nVertices = positions.length / 3;
  3735. if ( this.attributes[ "tangent" ] === undefined ) {
  3736. var nTangentElements = 4 * nVertices;
  3737. this.attributes[ "tangent" ] = {
  3738. itemSize: 4,
  3739. array: new Float32Array( nTangentElements ),
  3740. numItems: nTangentElements
  3741. };
  3742. }
  3743. var tangents = this.attributes[ "tangent" ].array;
  3744. var tan1 = [], tan2 = [];
  3745. for ( var k = 0; k < nVertices; k ++ ) {
  3746. tan1[ k ] = new THREE.Vector3();
  3747. tan2[ k ] = new THREE.Vector3();
  3748. }
  3749. var xA, yA, zA,
  3750. xB, yB, zB,
  3751. xC, yC, zC,
  3752. uA, vA,
  3753. uB, vB,
  3754. uC, vC,
  3755. x1, x2, y1, y2, z1, z2,
  3756. s1, s2, t1, t2, r;
  3757. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3758. function handleTriangle( a, b, c ) {
  3759. xA = positions[ a * 3 ];
  3760. yA = positions[ a * 3 + 1 ];
  3761. zA = positions[ a * 3 + 2 ];
  3762. xB = positions[ b * 3 ];
  3763. yB = positions[ b * 3 + 1 ];
  3764. zB = positions[ b * 3 + 2 ];
  3765. xC = positions[ c * 3 ];
  3766. yC = positions[ c * 3 + 1 ];
  3767. zC = positions[ c * 3 + 2 ];
  3768. uA = uvs[ a * 2 ];
  3769. vA = uvs[ a * 2 + 1 ];
  3770. uB = uvs[ b * 2 ];
  3771. vB = uvs[ b * 2 + 1 ];
  3772. uC = uvs[ c * 2 ];
  3773. vC = uvs[ c * 2 + 1 ];
  3774. x1 = xB - xA;
  3775. x2 = xC - xA;
  3776. y1 = yB - yA;
  3777. y2 = yC - yA;
  3778. z1 = zB - zA;
  3779. z2 = zC - zA;
  3780. s1 = uB - uA;
  3781. s2 = uC - uA;
  3782. t1 = vB - vA;
  3783. t2 = vC - vA;
  3784. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3785. sdir.set(
  3786. ( t2 * x1 - t1 * x2 ) * r,
  3787. ( t2 * y1 - t1 * y2 ) * r,
  3788. ( t2 * z1 - t1 * z2 ) * r
  3789. );
  3790. tdir.set(
  3791. ( s1 * x2 - s2 * x1 ) * r,
  3792. ( s1 * y2 - s2 * y1 ) * r,
  3793. ( s1 * z2 - s2 * z1 ) * r
  3794. );
  3795. tan1[ a ].addSelf( sdir );
  3796. tan1[ b ].addSelf( sdir );
  3797. tan1[ c ].addSelf( sdir );
  3798. tan2[ a ].addSelf( tdir );
  3799. tan2[ b ].addSelf( tdir );
  3800. tan2[ c ].addSelf( tdir );
  3801. }
  3802. var i, il;
  3803. var j, jl;
  3804. var iA, iB, iC;
  3805. var offsets = this.offsets;
  3806. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3807. var start = offsets[ j ].start;
  3808. var count = offsets[ j ].count;
  3809. var index = offsets[ j ].index;
  3810. for ( i = start, il = start + count; i < il; i += 3 ) {
  3811. iA = index + indices[ i ];
  3812. iB = index + indices[ i + 1 ];
  3813. iC = index + indices[ i + 2 ];
  3814. handleTriangle( iA, iB, iC );
  3815. }
  3816. }
  3817. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3818. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3819. var w, t, test;
  3820. var nx, ny, nz;
  3821. function handleVertex( v ) {
  3822. n.x = normals[ v * 3 ];
  3823. n.y = normals[ v * 3 + 1 ];
  3824. n.z = normals[ v * 3 + 2 ];
  3825. n2.copy( n );
  3826. t = tan1[ v ];
  3827. // Gram-Schmidt orthogonalize
  3828. tmp.copy( t );
  3829. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3830. // Calculate handedness
  3831. tmp2.cross( n2, t );
  3832. test = tmp2.dot( tan2[ v ] );
  3833. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3834. tangents[ v * 4 ] = tmp.x;
  3835. tangents[ v * 4 + 1 ] = tmp.y;
  3836. tangents[ v * 4 + 2 ] = tmp.z;
  3837. tangents[ v * 4 + 3 ] = w;
  3838. }
  3839. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3840. var start = offsets[ j ].start;
  3841. var count = offsets[ j ].count;
  3842. var index = offsets[ j ].index;
  3843. for ( i = start, il = start + count; i < il; i += 3 ) {
  3844. iA = index + indices[ i ];
  3845. iB = index + indices[ i + 1 ];
  3846. iC = index + indices[ i + 2 ];
  3847. handleVertex( iA );
  3848. handleVertex( iB );
  3849. handleVertex( iC );
  3850. }
  3851. }
  3852. this.hasTangents = true;
  3853. this.tangentsNeedUpdate = true;
  3854. },
  3855. deallocate: function () {
  3856. var index = THREE.GeometryLibrary.indexOf( this );
  3857. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3858. }
  3859. };
  3860. /**
  3861. * Spline from Tween.js, slightly optimized (and trashed)
  3862. * http://sole.github.com/tween.js/examples/05_spline.html
  3863. *
  3864. * @author mrdoob / http://mrdoob.com/
  3865. * @author alteredq / http://alteredqualia.com/
  3866. */
  3867. THREE.Spline = function ( points ) {
  3868. this.points = points;
  3869. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3870. point, intPoint, weight, w2, w3,
  3871. pa, pb, pc, pd;
  3872. this.initFromArray = function( a ) {
  3873. this.points = [];
  3874. for ( var i = 0; i < a.length; i++ ) {
  3875. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3876. }
  3877. };
  3878. this.getPoint = function ( k ) {
  3879. point = ( this.points.length - 1 ) * k;
  3880. intPoint = Math.floor( point );
  3881. weight = point - intPoint;
  3882. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3883. c[ 1 ] = intPoint;
  3884. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3885. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3886. pa = this.points[ c[ 0 ] ];
  3887. pb = this.points[ c[ 1 ] ];
  3888. pc = this.points[ c[ 2 ] ];
  3889. pd = this.points[ c[ 3 ] ];
  3890. w2 = weight * weight;
  3891. w3 = weight * w2;
  3892. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3893. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3894. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3895. return v3;
  3896. };
  3897. this.getControlPointsArray = function () {
  3898. var i, p, l = this.points.length,
  3899. coords = [];
  3900. for ( i = 0; i < l; i ++ ) {
  3901. p = this.points[ i ];
  3902. coords[ i ] = [ p.x, p.y, p.z ];
  3903. }
  3904. return coords;
  3905. };
  3906. // approximate length by summing linear segments
  3907. this.getLength = function ( nSubDivisions ) {
  3908. var i, index, nSamples, position,
  3909. point = 0, intPoint = 0, oldIntPoint = 0,
  3910. oldPosition = new THREE.Vector3(),
  3911. tmpVec = new THREE.Vector3(),
  3912. chunkLengths = [],
  3913. totalLength = 0;
  3914. // first point has 0 length
  3915. chunkLengths[ 0 ] = 0;
  3916. if ( !nSubDivisions ) nSubDivisions = 100;
  3917. nSamples = this.points.length * nSubDivisions;
  3918. oldPosition.copy( this.points[ 0 ] );
  3919. for ( i = 1; i < nSamples; i ++ ) {
  3920. index = i / nSamples;
  3921. position = this.getPoint( index );
  3922. tmpVec.copy( position );
  3923. totalLength += tmpVec.distanceTo( oldPosition );
  3924. oldPosition.copy( position );
  3925. point = ( this.points.length - 1 ) * index;
  3926. intPoint = Math.floor( point );
  3927. if ( intPoint != oldIntPoint ) {
  3928. chunkLengths[ intPoint ] = totalLength;
  3929. oldIntPoint = intPoint;
  3930. }
  3931. }
  3932. // last point ends with total length
  3933. chunkLengths[ chunkLengths.length ] = totalLength;
  3934. return { chunks: chunkLengths, total: totalLength };
  3935. };
  3936. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3937. var i, j,
  3938. index, indexCurrent, indexNext,
  3939. linearDistance, realDistance,
  3940. sampling, position,
  3941. newpoints = [],
  3942. tmpVec = new THREE.Vector3(),
  3943. sl = this.getLength();
  3944. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3945. for ( i = 1; i < this.points.length; i++ ) {
  3946. //tmpVec.copy( this.points[ i - 1 ] );
  3947. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3948. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3949. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3950. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3951. indexNext = i / ( this.points.length - 1 );
  3952. for ( j = 1; j < sampling - 1; j++ ) {
  3953. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3954. position = this.getPoint( index );
  3955. newpoints.push( tmpVec.copy( position ).clone() );
  3956. }
  3957. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3958. }
  3959. this.points = newpoints;
  3960. };
  3961. // Catmull-Rom
  3962. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3963. var v0 = ( p2 - p0 ) * 0.5,
  3964. v1 = ( p3 - p1 ) * 0.5;
  3965. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3966. };
  3967. };
  3968. /**
  3969. * @author mrdoob / http://mrdoob.com/
  3970. * @author mikael emtinger / http://gomo.se/
  3971. */
  3972. THREE.Camera = function () {
  3973. THREE.Object3D.call( this );
  3974. this.matrixWorldInverse = new THREE.Matrix4();
  3975. this.projectionMatrix = new THREE.Matrix4();
  3976. this.projectionMatrixInverse = new THREE.Matrix4();
  3977. };
  3978. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3979. THREE.Camera.prototype.lookAt = function ( vector ) {
  3980. // TODO: Add hierarchy support.
  3981. this.matrix.lookAt( this.position, vector, this.up );
  3982. if ( this.rotationAutoUpdate === true ) {
  3983. if ( this.useQuaternion === false ) {
  3984. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3985. } else {
  3986. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  3987. }
  3988. }
  3989. };
  3990. /**
  3991. * @author alteredq / http://alteredqualia.com/
  3992. */
  3993. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3994. THREE.Camera.call( this );
  3995. this.left = left;
  3996. this.right = right;
  3997. this.top = top;
  3998. this.bottom = bottom;
  3999. this.near = ( near !== undefined ) ? near : 0.1;
  4000. this.far = ( far !== undefined ) ? far : 2000;
  4001. this.updateProjectionMatrix();
  4002. };
  4003. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  4004. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  4005. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  4006. };
  4007. /**
  4008. * @author mrdoob / http://mrdoob.com/
  4009. * @author greggman / http://games.greggman.com/
  4010. * @author zz85 / http://www.lab4games.net/zz85/blog
  4011. */
  4012. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  4013. THREE.Camera.call( this );
  4014. this.fov = fov !== undefined ? fov : 50;
  4015. this.aspect = aspect !== undefined ? aspect : 1;
  4016. this.near = near !== undefined ? near : 0.1;
  4017. this.far = far !== undefined ? far : 2000;
  4018. this.updateProjectionMatrix();
  4019. };
  4020. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  4021. /**
  4022. * Uses Focal Length (in mm) to estimate and set FOV
  4023. * 35mm (fullframe) camera is used if frame size is not specified;
  4024. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  4025. */
  4026. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  4027. if ( frameHeight === undefined ) frameHeight = 24;
  4028. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  4029. this.updateProjectionMatrix();
  4030. }
  4031. /**
  4032. * Sets an offset in a larger frustum. This is useful for multi-window or
  4033. * multi-monitor/multi-machine setups.
  4034. *
  4035. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4036. * the monitors are in grid like this
  4037. *
  4038. * +---+---+---+
  4039. * | A | B | C |
  4040. * +---+---+---+
  4041. * | D | E | F |
  4042. * +---+---+---+
  4043. *
  4044. * then for each monitor you would call it like this
  4045. *
  4046. * var w = 1920;
  4047. * var h = 1080;
  4048. * var fullWidth = w * 3;
  4049. * var fullHeight = h * 2;
  4050. *
  4051. * --A--
  4052. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4053. * --B--
  4054. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4055. * --C--
  4056. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4057. * --D--
  4058. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4059. * --E--
  4060. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4061. * --F--
  4062. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4063. *
  4064. * Note there is no reason monitors have to be the same size or in a grid.
  4065. */
  4066. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4067. this.fullWidth = fullWidth;
  4068. this.fullHeight = fullHeight;
  4069. this.x = x;
  4070. this.y = y;
  4071. this.width = width;
  4072. this.height = height;
  4073. this.updateProjectionMatrix();
  4074. };
  4075. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4076. if ( this.fullWidth ) {
  4077. var aspect = this.fullWidth / this.fullHeight;
  4078. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4079. var bottom = -top;
  4080. var left = aspect * bottom;
  4081. var right = aspect * top;
  4082. var width = Math.abs( right - left );
  4083. var height = Math.abs( top - bottom );
  4084. this.projectionMatrix.makeFrustum(
  4085. left + this.x * width / this.fullWidth,
  4086. left + ( this.x + this.width ) * width / this.fullWidth,
  4087. top - ( this.y + this.height ) * height / this.fullHeight,
  4088. top - this.y * height / this.fullHeight,
  4089. this.near,
  4090. this.far
  4091. );
  4092. } else {
  4093. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4094. }
  4095. };
  4096. /**
  4097. * @author mrdoob / http://mrdoob.com/
  4098. * @author alteredq / http://alteredqualia.com/
  4099. */
  4100. THREE.Light = function ( hex ) {
  4101. THREE.Object3D.call( this );
  4102. this.color = new THREE.Color( hex );
  4103. };
  4104. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4105. /**
  4106. * @author mrdoob / http://mrdoob.com/
  4107. */
  4108. THREE.AmbientLight = function ( hex ) {
  4109. THREE.Light.call( this, hex );
  4110. };
  4111. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4112. /**
  4113. * @author mrdoob / http://mrdoob.com/
  4114. * @author alteredq / http://alteredqualia.com/
  4115. */
  4116. THREE.DirectionalLight = function ( hex, intensity ) {
  4117. THREE.Light.call( this, hex );
  4118. this.position = new THREE.Vector3( 0, 1, 0 );
  4119. this.target = new THREE.Object3D();
  4120. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4121. this.castShadow = false;
  4122. this.onlyShadow = false;
  4123. //
  4124. this.shadowCameraNear = 50;
  4125. this.shadowCameraFar = 5000;
  4126. this.shadowCameraLeft = -500;
  4127. this.shadowCameraRight = 500;
  4128. this.shadowCameraTop = 500;
  4129. this.shadowCameraBottom = -500;
  4130. this.shadowCameraVisible = false;
  4131. this.shadowBias = 0;
  4132. this.shadowDarkness = 0.5;
  4133. this.shadowMapWidth = 512;
  4134. this.shadowMapHeight = 512;
  4135. //
  4136. this.shadowCascade = false;
  4137. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4138. this.shadowCascadeCount = 2;
  4139. this.shadowCascadeBias = [ 0, 0, 0 ];
  4140. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4141. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4142. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4143. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4144. this.shadowCascadeArray = [];
  4145. //
  4146. this.shadowMap = null;
  4147. this.shadowMapSize = null;
  4148. this.shadowCamera = null;
  4149. this.shadowMatrix = null;
  4150. };
  4151. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4152. /**
  4153. * @author alteredq / http://alteredqualia.com/
  4154. */
  4155. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4156. THREE.Light.call( this, skyColorHex );
  4157. this.groundColor = new THREE.Color( groundColorHex );
  4158. this.position = new THREE.Vector3( 0, 100, 0 );
  4159. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4160. };
  4161. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4162. /**
  4163. * @author mrdoob / http://mrdoob.com/
  4164. */
  4165. THREE.PointLight = function ( hex, intensity, distance ) {
  4166. THREE.Light.call( this, hex );
  4167. this.position = new THREE.Vector3( 0, 0, 0 );
  4168. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4169. this.distance = ( distance !== undefined ) ? distance : 0;
  4170. };
  4171. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4172. /**
  4173. * @author alteredq / http://alteredqualia.com/
  4174. */
  4175. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4176. THREE.Light.call( this, hex );
  4177. this.position = new THREE.Vector3( 0, 1, 0 );
  4178. this.target = new THREE.Object3D();
  4179. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4180. this.distance = ( distance !== undefined ) ? distance : 0;
  4181. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4182. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4183. this.castShadow = false;
  4184. this.onlyShadow = false;
  4185. //
  4186. this.shadowCameraNear = 50;
  4187. this.shadowCameraFar = 5000;
  4188. this.shadowCameraFov = 50;
  4189. this.shadowCameraVisible = false;
  4190. this.shadowBias = 0;
  4191. this.shadowDarkness = 0.5;
  4192. this.shadowMapWidth = 512;
  4193. this.shadowMapHeight = 512;
  4194. //
  4195. this.shadowMap = null;
  4196. this.shadowMapSize = null;
  4197. this.shadowCamera = null;
  4198. this.shadowMatrix = null;
  4199. };
  4200. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4201. /**
  4202. * @author alteredq / http://alteredqualia.com/
  4203. */
  4204. THREE.Loader = function ( showStatus ) {
  4205. this.showStatus = showStatus;
  4206. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4207. this.onLoadStart = function () {};
  4208. this.onLoadProgress = function () {};
  4209. this.onLoadComplete = function () {};
  4210. };
  4211. THREE.Loader.prototype = {
  4212. constructor: THREE.Loader,
  4213. crossOrigin: 'anonymous',
  4214. addStatusElement: function () {
  4215. var e = document.createElement( "div" );
  4216. e.style.position = "absolute";
  4217. e.style.right = "0px";
  4218. e.style.top = "0px";
  4219. e.style.fontSize = "0.8em";
  4220. e.style.textAlign = "left";
  4221. e.style.background = "rgba(0,0,0,0.25)";
  4222. e.style.color = "#fff";
  4223. e.style.width = "120px";
  4224. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4225. e.style.zIndex = 1000;
  4226. e.innerHTML = "Loading ...";
  4227. return e;
  4228. },
  4229. updateProgress: function ( progress ) {
  4230. var message = "Loaded ";
  4231. if ( progress.total ) {
  4232. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4233. } else {
  4234. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4235. }
  4236. this.statusDomElement.innerHTML = message;
  4237. },
  4238. extractUrlBase: function ( url ) {
  4239. var parts = url.split( '/' );
  4240. parts.pop();
  4241. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4242. },
  4243. initMaterials: function ( materials, texturePath ) {
  4244. var array = [];
  4245. for ( var i = 0; i < materials.length; ++ i ) {
  4246. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4247. }
  4248. return array;
  4249. },
  4250. needsTangents: function ( materials ) {
  4251. for( var i = 0, il = materials.length; i < il; i ++ ) {
  4252. var m = materials[ i ];
  4253. if ( m instanceof THREE.ShaderMaterial ) return true;
  4254. }
  4255. return false;
  4256. },
  4257. createMaterial: function ( m, texturePath ) {
  4258. var _this = this;
  4259. function is_pow2( n ) {
  4260. var l = Math.log( n ) / Math.LN2;
  4261. return Math.floor( l ) == l;
  4262. }
  4263. function nearest_pow2( n ) {
  4264. var l = Math.log( n ) / Math.LN2;
  4265. return Math.pow( 2, Math.round( l ) );
  4266. }
  4267. function load_image( where, url ) {
  4268. var image = new Image();
  4269. image.onload = function () {
  4270. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4271. var width = nearest_pow2( this.width );
  4272. var height = nearest_pow2( this.height );
  4273. where.image.width = width;
  4274. where.image.height = height;
  4275. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4276. } else {
  4277. where.image = this;
  4278. }
  4279. where.needsUpdate = true;
  4280. };
  4281. image.crossOrigin = _this.crossOrigin;
  4282. image.src = url;
  4283. }
  4284. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4285. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4286. var fullPath = texturePath + "/" + sourceFile;
  4287. if ( isCompressed ) {
  4288. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4289. where[ name ] = texture;
  4290. } else {
  4291. var texture = document.createElement( 'canvas' );
  4292. where[ name ] = new THREE.Texture( texture );
  4293. }
  4294. where[ name ].sourceFile = sourceFile;
  4295. if( repeat ) {
  4296. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4297. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4298. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4299. }
  4300. if ( offset ) {
  4301. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4302. }
  4303. if ( wrap ) {
  4304. var wrapMap = {
  4305. "repeat": THREE.RepeatWrapping,
  4306. "mirror": THREE.MirroredRepeatWrapping
  4307. }
  4308. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4309. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4310. }
  4311. if ( anisotropy ) {
  4312. where[ name ].anisotropy = anisotropy;
  4313. }
  4314. if ( ! isCompressed ) {
  4315. load_image( where[ name ], fullPath );
  4316. }
  4317. }
  4318. function rgb2hex( rgb ) {
  4319. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4320. }
  4321. // defaults
  4322. var mtype = "MeshLambertMaterial";
  4323. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4324. // parameters from model file
  4325. if ( m.shading ) {
  4326. var shading = m.shading.toLowerCase();
  4327. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4328. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4329. }
  4330. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4331. mpars.blending = THREE[ m.blending ];
  4332. }
  4333. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4334. mpars.transparent = m.transparent;
  4335. }
  4336. if ( m.depthTest !== undefined ) {
  4337. mpars.depthTest = m.depthTest;
  4338. }
  4339. if ( m.depthWrite !== undefined ) {
  4340. mpars.depthWrite = m.depthWrite;
  4341. }
  4342. if ( m.visible !== undefined ) {
  4343. mpars.visible = m.visible;
  4344. }
  4345. if ( m.flipSided !== undefined ) {
  4346. mpars.side = THREE.BackSide;
  4347. }
  4348. if ( m.doubleSided !== undefined ) {
  4349. mpars.side = THREE.DoubleSide;
  4350. }
  4351. if ( m.wireframe !== undefined ) {
  4352. mpars.wireframe = m.wireframe;
  4353. }
  4354. if ( m.vertexColors !== undefined ) {
  4355. if ( m.vertexColors === "face" ) {
  4356. mpars.vertexColors = THREE.FaceColors;
  4357. } else if ( m.vertexColors ) {
  4358. mpars.vertexColors = THREE.VertexColors;
  4359. }
  4360. }
  4361. // colors
  4362. if ( m.colorDiffuse ) {
  4363. mpars.color = rgb2hex( m.colorDiffuse );
  4364. } else if ( m.DbgColor ) {
  4365. mpars.color = m.DbgColor;
  4366. }
  4367. if ( m.colorSpecular ) {
  4368. mpars.specular = rgb2hex( m.colorSpecular );
  4369. }
  4370. if ( m.colorAmbient ) {
  4371. mpars.ambient = rgb2hex( m.colorAmbient );
  4372. }
  4373. // modifiers
  4374. if ( m.transparency ) {
  4375. mpars.opacity = m.transparency;
  4376. }
  4377. if ( m.specularCoef ) {
  4378. mpars.shininess = m.specularCoef;
  4379. }
  4380. // textures
  4381. if ( m.mapDiffuse && texturePath ) {
  4382. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  4383. }
  4384. if ( m.mapLight && texturePath ) {
  4385. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  4386. }
  4387. if ( m.mapBump && texturePath ) {
  4388. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  4389. }
  4390. if ( m.mapNormal && texturePath ) {
  4391. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  4392. }
  4393. if ( m.mapSpecular && texturePath ) {
  4394. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  4395. }
  4396. //
  4397. if ( m.mapBumpScale ) {
  4398. mpars.bumpScale = m.mapBumpScale;
  4399. }
  4400. // special case for normal mapped material
  4401. if ( m.mapNormal ) {
  4402. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4403. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4404. uniforms[ "tNormal" ].value = mpars.normalMap;
  4405. if ( m.mapNormalFactor ) {
  4406. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  4407. }
  4408. if ( mpars.map ) {
  4409. uniforms[ "tDiffuse" ].value = mpars.map;
  4410. uniforms[ "enableDiffuse" ].value = true;
  4411. }
  4412. if ( mpars.specularMap ) {
  4413. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4414. uniforms[ "enableSpecular" ].value = true;
  4415. }
  4416. if ( mpars.lightMap ) {
  4417. uniforms[ "tAO" ].value = mpars.lightMap;
  4418. uniforms[ "enableAO" ].value = true;
  4419. }
  4420. // for the moment don't handle displacement texture
  4421. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4422. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4423. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4424. uniforms[ "uShininess" ].value = mpars.shininess;
  4425. if ( mpars.opacity !== undefined ) {
  4426. uniforms[ "uOpacity" ].value = mpars.opacity;
  4427. }
  4428. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4429. var material = new THREE.ShaderMaterial( parameters );
  4430. } else {
  4431. var material = new THREE[ mtype ]( mpars );
  4432. }
  4433. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4434. return material;
  4435. }
  4436. };
  4437. /**
  4438. * @author alteredq / http://alteredqualia.com/
  4439. */
  4440. THREE.BinaryLoader = function ( showStatus ) {
  4441. THREE.Loader.call( this, showStatus );
  4442. };
  4443. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4444. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4445. // - binary models consist of two files: JS and BIN
  4446. // - parameters
  4447. // - url (required)
  4448. // - callback (required)
  4449. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4450. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4451. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4452. // todo: unify load API to for easier SceneLoader use
  4453. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4454. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  4455. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4456. this.onLoadStart();
  4457. // #1 load JS part via web worker
  4458. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4459. };
  4460. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4461. var xhr = new XMLHttpRequest();
  4462. xhr.onreadystatechange = function () {
  4463. if ( xhr.readyState == 4 ) {
  4464. if ( xhr.status == 200 || xhr.status == 0 ) {
  4465. var json = JSON.parse( xhr.responseText );
  4466. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4467. } else {
  4468. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4469. }
  4470. }
  4471. };
  4472. xhr.open( "GET", url, true );
  4473. xhr.send( null );
  4474. };
  4475. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4476. var xhr = new XMLHttpRequest(),
  4477. url = binaryPath + "/" + json.buffers;
  4478. var length = 0;
  4479. xhr.onreadystatechange = function () {
  4480. if ( xhr.readyState == 4 ) {
  4481. if ( xhr.status == 200 || xhr.status == 0 ) {
  4482. var buffer = xhr.response;
  4483. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4484. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4485. } else {
  4486. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4487. }
  4488. } else if ( xhr.readyState == 3 ) {
  4489. if ( callbackProgress ) {
  4490. if ( length == 0 ) {
  4491. length = xhr.getResponseHeader( "Content-Length" );
  4492. }
  4493. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4494. }
  4495. } else if ( xhr.readyState == 2 ) {
  4496. length = xhr.getResponseHeader( "Content-Length" );
  4497. }
  4498. };
  4499. xhr.open( "GET", url, true );
  4500. xhr.responseType = "arraybuffer";
  4501. xhr.send( null );
  4502. };
  4503. // Binary AJAX parser
  4504. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  4505. var Model = function ( texturePath ) {
  4506. var scope = this,
  4507. currentOffset = 0,
  4508. md,
  4509. normals = [],
  4510. uvs = [],
  4511. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4512. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4513. tri_size, quad_size,
  4514. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4515. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4516. THREE.Geometry.call( this );
  4517. md = parseMetaData( data, currentOffset );
  4518. currentOffset += md.header_bytes;
  4519. /*
  4520. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4521. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4522. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4523. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4524. */
  4525. // buffers sizes
  4526. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4527. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4528. len_tri_flat = md.ntri_flat * ( tri_size );
  4529. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4530. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4531. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4532. len_quad_flat = md.nquad_flat * ( quad_size );
  4533. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4534. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4535. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4536. // read buffers
  4537. currentOffset += init_vertices( currentOffset );
  4538. currentOffset += init_normals( currentOffset );
  4539. currentOffset += handlePadding( md.nnormals * 3 );
  4540. currentOffset += init_uvs( currentOffset );
  4541. start_tri_flat = currentOffset;
  4542. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4543. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4544. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4545. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4546. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4547. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4548. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4549. // have to first process faces with uvs
  4550. // so that face and uv indices match
  4551. init_triangles_flat_uv( start_tri_flat_uv );
  4552. init_triangles_smooth_uv( start_tri_smooth_uv );
  4553. init_quads_flat_uv( start_quad_flat_uv );
  4554. init_quads_smooth_uv( start_quad_smooth_uv );
  4555. // now we can process untextured faces
  4556. init_triangles_flat( start_tri_flat );
  4557. init_triangles_smooth( start_tri_smooth );
  4558. init_quads_flat( start_quad_flat );
  4559. init_quads_smooth( start_quad_smooth );
  4560. this.computeCentroids();
  4561. this.computeFaceNormals();
  4562. function handlePadding( n ) {
  4563. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4564. };
  4565. function parseMetaData( data, offset ) {
  4566. var metaData = {
  4567. 'signature' :parseString( data, offset, 12 ),
  4568. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4569. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4570. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4571. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4572. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4573. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4574. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4575. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4576. 'nvertices' :parseUInt32( data, offset + 20 ),
  4577. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4578. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4579. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4580. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4581. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4582. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4583. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4584. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4585. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4586. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4587. };
  4588. /*
  4589. console.log( "signature: " + metaData.signature );
  4590. console.log( "header_bytes: " + metaData.header_bytes );
  4591. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4592. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4593. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4594. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4595. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4596. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4597. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4598. console.log( "nvertices: " + metaData.nvertices );
  4599. console.log( "nnormals: " + metaData.nnormals );
  4600. console.log( "nuvs: " + metaData.nuvs );
  4601. console.log( "ntri_flat: " + metaData.ntri_flat );
  4602. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4603. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4604. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4605. console.log( "nquad_flat: " + metaData.nquad_flat );
  4606. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4607. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4608. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4609. var total = metaData.header_bytes
  4610. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4611. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4612. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4613. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4614. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4615. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4616. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4617. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4618. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4619. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4620. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4621. console.log( "total bytes: " + total );
  4622. */
  4623. return metaData;
  4624. };
  4625. function parseString( data, offset, length ) {
  4626. var charArray = new Uint8Array( data, offset, length );
  4627. var text = "";
  4628. for ( var i = 0; i < length; i ++ ) {
  4629. text += String.fromCharCode( charArray[ offset + i ] );
  4630. }
  4631. return text;
  4632. };
  4633. function parseUChar8( data, offset ) {
  4634. var charArray = new Uint8Array( data, offset, 1 );
  4635. return charArray[ 0 ];
  4636. };
  4637. function parseUInt32( data, offset ) {
  4638. var intArray = new Uint32Array( data, offset, 1 );
  4639. return intArray[ 0 ];
  4640. };
  4641. function init_vertices( start ) {
  4642. var nElements = md.nvertices;
  4643. var coordArray = new Float32Array( data, start, nElements * 3 );
  4644. var i, x, y, z;
  4645. for( i = 0; i < nElements; i ++ ) {
  4646. x = coordArray[ i * 3 ];
  4647. y = coordArray[ i * 3 + 1 ];
  4648. z = coordArray[ i * 3 + 2 ];
  4649. vertex( scope, x, y, z );
  4650. }
  4651. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4652. };
  4653. function init_normals( start ) {
  4654. var nElements = md.nnormals;
  4655. if ( nElements ) {
  4656. var normalArray = new Int8Array( data, start, nElements * 3 );
  4657. var i, x, y, z;
  4658. for( i = 0; i < nElements; i ++ ) {
  4659. x = normalArray[ i * 3 ];
  4660. y = normalArray[ i * 3 + 1 ];
  4661. z = normalArray[ i * 3 + 2 ];
  4662. normals.push( x/127, y/127, z/127 );
  4663. }
  4664. }
  4665. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4666. };
  4667. function init_uvs( start ) {
  4668. var nElements = md.nuvs;
  4669. if ( nElements ) {
  4670. var uvArray = new Float32Array( data, start, nElements * 2 );
  4671. var i, u, v;
  4672. for( i = 0; i < nElements; i ++ ) {
  4673. u = uvArray[ i * 2 ];
  4674. v = uvArray[ i * 2 + 1 ];
  4675. uvs.push( u, v );
  4676. }
  4677. }
  4678. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4679. };
  4680. function init_uvs3( nElements, offset ) {
  4681. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4682. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4683. for( i = 0; i < nElements; i ++ ) {
  4684. uva = uvIndexBuffer[ i * 3 ];
  4685. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4686. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4687. u1 = uvs[ uva*2 ];
  4688. v1 = uvs[ uva*2 + 1 ];
  4689. u2 = uvs[ uvb*2 ];
  4690. v2 = uvs[ uvb*2 + 1 ];
  4691. u3 = uvs[ uvc*2 ];
  4692. v3 = uvs[ uvc*2 + 1 ];
  4693. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4694. }
  4695. };
  4696. function init_uvs4( nElements, offset ) {
  4697. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4698. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4699. for( i = 0; i < nElements; i ++ ) {
  4700. uva = uvIndexBuffer[ i * 4 ];
  4701. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4702. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4703. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4704. u1 = uvs[ uva*2 ];
  4705. v1 = uvs[ uva*2 + 1 ];
  4706. u2 = uvs[ uvb*2 ];
  4707. v2 = uvs[ uvb*2 + 1 ];
  4708. u3 = uvs[ uvc*2 ];
  4709. v3 = uvs[ uvc*2 + 1 ];
  4710. u4 = uvs[ uvd*2 ];
  4711. v4 = uvs[ uvd*2 + 1 ];
  4712. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4713. }
  4714. };
  4715. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4716. var i, a, b, c, m;
  4717. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4718. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4719. for( i = 0; i < nElements; i ++ ) {
  4720. a = vertexIndexBuffer[ i * 3 ];
  4721. b = vertexIndexBuffer[ i * 3 + 1 ];
  4722. c = vertexIndexBuffer[ i * 3 + 2 ];
  4723. m = materialIndexBuffer[ i ];
  4724. f3( scope, a, b, c, m );
  4725. }
  4726. };
  4727. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4728. var i, a, b, c, d, m;
  4729. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4730. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4731. for( i = 0; i < nElements; i ++ ) {
  4732. a = vertexIndexBuffer[ i * 4 ];
  4733. b = vertexIndexBuffer[ i * 4 + 1 ];
  4734. c = vertexIndexBuffer[ i * 4 + 2 ];
  4735. d = vertexIndexBuffer[ i * 4 + 3 ];
  4736. m = materialIndexBuffer[ i ];
  4737. f4( scope, a, b, c, d, m );
  4738. }
  4739. };
  4740. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4741. var i, a, b, c, m;
  4742. var na, nb, nc;
  4743. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4744. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4745. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4746. for( i = 0; i < nElements; i ++ ) {
  4747. a = vertexIndexBuffer[ i * 3 ];
  4748. b = vertexIndexBuffer[ i * 3 + 1 ];
  4749. c = vertexIndexBuffer[ i * 3 + 2 ];
  4750. na = normalIndexBuffer[ i * 3 ];
  4751. nb = normalIndexBuffer[ i * 3 + 1 ];
  4752. nc = normalIndexBuffer[ i * 3 + 2 ];
  4753. m = materialIndexBuffer[ i ];
  4754. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4755. }
  4756. };
  4757. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4758. var i, a, b, c, d, m;
  4759. var na, nb, nc, nd;
  4760. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4761. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4762. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4763. for( i = 0; i < nElements; i ++ ) {
  4764. a = vertexIndexBuffer[ i * 4 ];
  4765. b = vertexIndexBuffer[ i * 4 + 1 ];
  4766. c = vertexIndexBuffer[ i * 4 + 2 ];
  4767. d = vertexIndexBuffer[ i * 4 + 3 ];
  4768. na = normalIndexBuffer[ i * 4 ];
  4769. nb = normalIndexBuffer[ i * 4 + 1 ];
  4770. nc = normalIndexBuffer[ i * 4 + 2 ];
  4771. nd = normalIndexBuffer[ i * 4 + 3 ];
  4772. m = materialIndexBuffer[ i ];
  4773. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4774. }
  4775. };
  4776. function init_triangles_flat( start ) {
  4777. var nElements = md.ntri_flat;
  4778. if ( nElements ) {
  4779. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4780. init_faces3_flat( nElements, start, offsetMaterials );
  4781. }
  4782. };
  4783. function init_triangles_flat_uv( start ) {
  4784. var nElements = md.ntri_flat_uv;
  4785. if ( nElements ) {
  4786. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4787. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4788. init_faces3_flat( nElements, start, offsetMaterials );
  4789. init_uvs3( nElements, offsetUvs );
  4790. }
  4791. };
  4792. function init_triangles_smooth( start ) {
  4793. var nElements = md.ntri_smooth;
  4794. if ( nElements ) {
  4795. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4796. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4797. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4798. }
  4799. };
  4800. function init_triangles_smooth_uv( start ) {
  4801. var nElements = md.ntri_smooth_uv;
  4802. if ( nElements ) {
  4803. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4804. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4805. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4806. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4807. init_uvs3( nElements, offsetUvs );
  4808. }
  4809. };
  4810. function init_quads_flat( start ) {
  4811. var nElements = md.nquad_flat;
  4812. if ( nElements ) {
  4813. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4814. init_faces4_flat( nElements, start, offsetMaterials );
  4815. }
  4816. };
  4817. function init_quads_flat_uv( start ) {
  4818. var nElements = md.nquad_flat_uv;
  4819. if ( nElements ) {
  4820. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4821. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4822. init_faces4_flat( nElements, start, offsetMaterials );
  4823. init_uvs4( nElements, offsetUvs );
  4824. }
  4825. };
  4826. function init_quads_smooth( start ) {
  4827. var nElements = md.nquad_smooth;
  4828. if ( nElements ) {
  4829. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4830. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4831. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4832. }
  4833. };
  4834. function init_quads_smooth_uv( start ) {
  4835. var nElements = md.nquad_smooth_uv;
  4836. if ( nElements ) {
  4837. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4838. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4839. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4840. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4841. init_uvs4( nElements, offsetUvs );
  4842. }
  4843. };
  4844. };
  4845. function vertex ( scope, x, y, z ) {
  4846. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4847. };
  4848. function f3 ( scope, a, b, c, mi ) {
  4849. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4850. };
  4851. function f4 ( scope, a, b, c, d, mi ) {
  4852. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4853. };
  4854. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4855. var nax = normals[ na*3 ],
  4856. nay = normals[ na*3 + 1 ],
  4857. naz = normals[ na*3 + 2 ],
  4858. nbx = normals[ nb*3 ],
  4859. nby = normals[ nb*3 + 1 ],
  4860. nbz = normals[ nb*3 + 2 ],
  4861. ncx = normals[ nc*3 ],
  4862. ncy = normals[ nc*3 + 1 ],
  4863. ncz = normals[ nc*3 + 2 ];
  4864. scope.faces.push( new THREE.Face3( a, b, c,
  4865. [new THREE.Vector3( nax, nay, naz ),
  4866. new THREE.Vector3( nbx, nby, nbz ),
  4867. new THREE.Vector3( ncx, ncy, ncz )],
  4868. null,
  4869. mi ) );
  4870. };
  4871. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4872. var nax = normals[ na*3 ],
  4873. nay = normals[ na*3 + 1 ],
  4874. naz = normals[ na*3 + 2 ],
  4875. nbx = normals[ nb*3 ],
  4876. nby = normals[ nb*3 + 1 ],
  4877. nbz = normals[ nb*3 + 2 ],
  4878. ncx = normals[ nc*3 ],
  4879. ncy = normals[ nc*3 + 1 ],
  4880. ncz = normals[ nc*3 + 2 ],
  4881. ndx = normals[ nd*3 ],
  4882. ndy = normals[ nd*3 + 1 ],
  4883. ndz = normals[ nd*3 + 2 ];
  4884. scope.faces.push( new THREE.Face4( a, b, c, d,
  4885. [new THREE.Vector3( nax, nay, naz ),
  4886. new THREE.Vector3( nbx, nby, nbz ),
  4887. new THREE.Vector3( ncx, ncy, ncz ),
  4888. new THREE.Vector3( ndx, ndy, ndz )],
  4889. null,
  4890. mi ) );
  4891. };
  4892. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4893. where.push( [
  4894. new THREE.UV( u1, v1 ),
  4895. new THREE.UV( u2, v2 ),
  4896. new THREE.UV( u3, v3 )
  4897. ] );
  4898. };
  4899. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4900. where.push( [
  4901. new THREE.UV( u1, v1 ),
  4902. new THREE.UV( u2, v2 ),
  4903. new THREE.UV( u3, v3 ),
  4904. new THREE.UV( u4, v4 )
  4905. ] );
  4906. };
  4907. Model.prototype = Object.create( THREE.Geometry.prototype );
  4908. var geometry = new Model( texturePath );
  4909. var materials = this.initMaterials( jsonMaterials, texturePath );
  4910. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  4911. callback( geometry, materials );
  4912. };
  4913. /**
  4914. * @author mrdoob / http://mrdoob.com/
  4915. */
  4916. THREE.ImageLoader = function () {
  4917. THREE.EventTarget.call( this );
  4918. this.crossOrigin = null;
  4919. };
  4920. THREE.ImageLoader.prototype = {
  4921. constructor: THREE.ImageLoader,
  4922. load: function ( url, image ) {
  4923. var scope = this;
  4924. if ( image === undefined ) image = new Image();
  4925. image.addEventListener( 'load', function () {
  4926. scope.dispatchEvent( { type: 'load', content: image } );
  4927. }, false );
  4928. image.addEventListener( 'error', function () {
  4929. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4930. }, false );
  4931. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4932. image.src = url;
  4933. }
  4934. }
  4935. /**
  4936. * @author mrdoob / http://mrdoob.com/
  4937. * @author alteredq / http://alteredqualia.com/
  4938. */
  4939. THREE.JSONLoader = function ( showStatus ) {
  4940. THREE.Loader.call( this, showStatus );
  4941. this.withCredentials = false;
  4942. };
  4943. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4944. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4945. var scope = this;
  4946. // todo: unify load API to for easier SceneLoader use
  4947. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  4948. this.onLoadStart();
  4949. this.loadAjaxJSON( this, url, callback, texturePath );
  4950. };
  4951. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4952. var xhr = new XMLHttpRequest();
  4953. var length = 0;
  4954. xhr.withCredentials = this.withCredentials;
  4955. xhr.onreadystatechange = function () {
  4956. if ( xhr.readyState === xhr.DONE ) {
  4957. if ( xhr.status === 200 || xhr.status === 0 ) {
  4958. if ( xhr.responseText ) {
  4959. var json = JSON.parse( xhr.responseText );
  4960. context.createModel( json, callback, texturePath );
  4961. } else {
  4962. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4963. }
  4964. // in context of more complex asset initialization
  4965. // do not block on single failed file
  4966. // maybe should go even one more level up
  4967. context.onLoadComplete();
  4968. } else {
  4969. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4970. }
  4971. } else if ( xhr.readyState === xhr.LOADING ) {
  4972. if ( callbackProgress ) {
  4973. if ( length === 0 ) {
  4974. length = xhr.getResponseHeader( "Content-Length" );
  4975. }
  4976. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4977. }
  4978. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4979. length = xhr.getResponseHeader( "Content-Length" );
  4980. }
  4981. };
  4982. xhr.open( "GET", url, true );
  4983. xhr.send( null );
  4984. };
  4985. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4986. var scope = this,
  4987. geometry = new THREE.Geometry(),
  4988. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4989. parseModel( scale );
  4990. parseSkin();
  4991. parseMorphing( scale );
  4992. geometry.computeCentroids();
  4993. geometry.computeFaceNormals();
  4994. function parseModel( scale ) {
  4995. function isBitSet( value, position ) {
  4996. return value & ( 1 << position );
  4997. }
  4998. var i, j, fi,
  4999. offset, zLength, nVertices,
  5000. colorIndex, normalIndex, uvIndex, materialIndex,
  5001. type,
  5002. isQuad,
  5003. hasMaterial,
  5004. hasFaceUv, hasFaceVertexUv,
  5005. hasFaceNormal, hasFaceVertexNormal,
  5006. hasFaceColor, hasFaceVertexColor,
  5007. vertex, face, color, normal,
  5008. uvLayer, uvs, u, v,
  5009. faces = json.faces,
  5010. vertices = json.vertices,
  5011. normals = json.normals,
  5012. colors = json.colors,
  5013. nUvLayers = 0;
  5014. // disregard empty arrays
  5015. for ( i = 0; i < json.uvs.length; i++ ) {
  5016. if ( json.uvs[ i ].length ) nUvLayers ++;
  5017. }
  5018. for ( i = 0; i < nUvLayers; i++ ) {
  5019. geometry.faceUvs[ i ] = [];
  5020. geometry.faceVertexUvs[ i ] = [];
  5021. }
  5022. offset = 0;
  5023. zLength = vertices.length;
  5024. while ( offset < zLength ) {
  5025. vertex = new THREE.Vector3();
  5026. vertex.x = vertices[ offset ++ ] * scale;
  5027. vertex.y = vertices[ offset ++ ] * scale;
  5028. vertex.z = vertices[ offset ++ ] * scale;
  5029. geometry.vertices.push( vertex );
  5030. }
  5031. offset = 0;
  5032. zLength = faces.length;
  5033. while ( offset < zLength ) {
  5034. type = faces[ offset ++ ];
  5035. isQuad = isBitSet( type, 0 );
  5036. hasMaterial = isBitSet( type, 1 );
  5037. hasFaceUv = isBitSet( type, 2 );
  5038. hasFaceVertexUv = isBitSet( type, 3 );
  5039. hasFaceNormal = isBitSet( type, 4 );
  5040. hasFaceVertexNormal = isBitSet( type, 5 );
  5041. hasFaceColor = isBitSet( type, 6 );
  5042. hasFaceVertexColor = isBitSet( type, 7 );
  5043. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5044. if ( isQuad ) {
  5045. face = new THREE.Face4();
  5046. face.a = faces[ offset ++ ];
  5047. face.b = faces[ offset ++ ];
  5048. face.c = faces[ offset ++ ];
  5049. face.d = faces[ offset ++ ];
  5050. nVertices = 4;
  5051. } else {
  5052. face = new THREE.Face3();
  5053. face.a = faces[ offset ++ ];
  5054. face.b = faces[ offset ++ ];
  5055. face.c = faces[ offset ++ ];
  5056. nVertices = 3;
  5057. }
  5058. if ( hasMaterial ) {
  5059. materialIndex = faces[ offset ++ ];
  5060. face.materialIndex = materialIndex;
  5061. }
  5062. // to get face <=> uv index correspondence
  5063. fi = geometry.faces.length;
  5064. if ( hasFaceUv ) {
  5065. for ( i = 0; i < nUvLayers; i++ ) {
  5066. uvLayer = json.uvs[ i ];
  5067. uvIndex = faces[ offset ++ ];
  5068. u = uvLayer[ uvIndex * 2 ];
  5069. v = uvLayer[ uvIndex * 2 + 1 ];
  5070. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5071. }
  5072. }
  5073. if ( hasFaceVertexUv ) {
  5074. for ( i = 0; i < nUvLayers; i++ ) {
  5075. uvLayer = json.uvs[ i ];
  5076. uvs = [];
  5077. for ( j = 0; j < nVertices; j ++ ) {
  5078. uvIndex = faces[ offset ++ ];
  5079. u = uvLayer[ uvIndex * 2 ];
  5080. v = uvLayer[ uvIndex * 2 + 1 ];
  5081. uvs[ j ] = new THREE.UV( u, v );
  5082. }
  5083. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5084. }
  5085. }
  5086. if ( hasFaceNormal ) {
  5087. normalIndex = faces[ offset ++ ] * 3;
  5088. normal = new THREE.Vector3();
  5089. normal.x = normals[ normalIndex ++ ];
  5090. normal.y = normals[ normalIndex ++ ];
  5091. normal.z = normals[ normalIndex ];
  5092. face.normal = normal;
  5093. }
  5094. if ( hasFaceVertexNormal ) {
  5095. for ( i = 0; i < nVertices; i++ ) {
  5096. normalIndex = faces[ offset ++ ] * 3;
  5097. normal = new THREE.Vector3();
  5098. normal.x = normals[ normalIndex ++ ];
  5099. normal.y = normals[ normalIndex ++ ];
  5100. normal.z = normals[ normalIndex ];
  5101. face.vertexNormals.push( normal );
  5102. }
  5103. }
  5104. if ( hasFaceColor ) {
  5105. colorIndex = faces[ offset ++ ];
  5106. color = new THREE.Color( colors[ colorIndex ] );
  5107. face.color = color;
  5108. }
  5109. if ( hasFaceVertexColor ) {
  5110. for ( i = 0; i < nVertices; i++ ) {
  5111. colorIndex = faces[ offset ++ ];
  5112. color = new THREE.Color( colors[ colorIndex ] );
  5113. face.vertexColors.push( color );
  5114. }
  5115. }
  5116. geometry.faces.push( face );
  5117. }
  5118. };
  5119. function parseSkin() {
  5120. var i, l, x, y, z, w, a, b, c, d;
  5121. if ( json.skinWeights ) {
  5122. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5123. x = json.skinWeights[ i ];
  5124. y = json.skinWeights[ i + 1 ];
  5125. z = 0;
  5126. w = 0;
  5127. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5128. }
  5129. }
  5130. if ( json.skinIndices ) {
  5131. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5132. a = json.skinIndices[ i ];
  5133. b = json.skinIndices[ i + 1 ];
  5134. c = 0;
  5135. d = 0;
  5136. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5137. }
  5138. }
  5139. geometry.bones = json.bones;
  5140. geometry.animation = json.animation;
  5141. };
  5142. function parseMorphing( scale ) {
  5143. if ( json.morphTargets !== undefined ) {
  5144. var i, l, v, vl, dstVertices, srcVertices;
  5145. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5146. geometry.morphTargets[ i ] = {};
  5147. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5148. geometry.morphTargets[ i ].vertices = [];
  5149. dstVertices = geometry.morphTargets[ i ].vertices;
  5150. srcVertices = json.morphTargets [ i ].vertices;
  5151. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5152. var vertex = new THREE.Vector3();
  5153. vertex.x = srcVertices[ v ] * scale;
  5154. vertex.y = srcVertices[ v + 1 ] * scale;
  5155. vertex.z = srcVertices[ v + 2 ] * scale;
  5156. dstVertices.push( vertex );
  5157. }
  5158. }
  5159. }
  5160. if ( json.morphColors !== undefined ) {
  5161. var i, l, c, cl, dstColors, srcColors, color;
  5162. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5163. geometry.morphColors[ i ] = {};
  5164. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5165. geometry.morphColors[ i ].colors = [];
  5166. dstColors = geometry.morphColors[ i ].colors;
  5167. srcColors = json.morphColors [ i ].colors;
  5168. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5169. color = new THREE.Color( 0xffaa00 );
  5170. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5171. dstColors.push( color );
  5172. }
  5173. }
  5174. }
  5175. };
  5176. var materials = this.initMaterials( json.materials, texturePath );
  5177. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5178. callback( geometry, materials );
  5179. };
  5180. /**
  5181. * @author mrdoob / http://mrdoob.com/
  5182. */
  5183. THREE.LoadingMonitor = function () {
  5184. THREE.EventTarget.call( this );
  5185. var scope = this;
  5186. var loaded = 0;
  5187. var total = 0;
  5188. var onLoad = function ( event ) {
  5189. loaded ++;
  5190. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5191. if ( loaded === total ) {
  5192. scope.dispatchEvent( { type: 'load' } );
  5193. }
  5194. };
  5195. this.add = function ( loader ) {
  5196. total ++;
  5197. loader.addEventListener( 'load', onLoad, false );
  5198. };
  5199. };
  5200. /**
  5201. * @author alteredq / http://alteredqualia.com/
  5202. */
  5203. THREE.SceneLoader = function () {
  5204. this.onLoadStart = function () {};
  5205. this.onLoadProgress = function() {};
  5206. this.onLoadComplete = function () {};
  5207. this.callbackSync = function () {};
  5208. this.callbackProgress = function () {};
  5209. this.geometryHandlerMap = {};
  5210. this.hierarchyHandlerMap = {};
  5211. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5212. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5213. };
  5214. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5215. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5216. var scope = this;
  5217. var xhr = new XMLHttpRequest();
  5218. xhr.onreadystatechange = function () {
  5219. if ( xhr.readyState === 4 ) {
  5220. if ( xhr.status === 200 || xhr.status === 0 ) {
  5221. var json = JSON.parse( xhr.responseText );
  5222. scope.parse( json, callbackFinished, url );
  5223. } else {
  5224. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5225. }
  5226. }
  5227. };
  5228. xhr.open( "GET", url, true );
  5229. xhr.send( null );
  5230. };
  5231. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5232. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5233. };
  5234. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5235. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5236. };
  5237. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5238. var scope = this;
  5239. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5240. var dg, dm, dc, df, dt,
  5241. g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5242. geometry, material, camera, fog,
  5243. texture, images,
  5244. light, hex, intensity,
  5245. counter_models, counter_textures,
  5246. total_models, total_textures,
  5247. result;
  5248. var target_array = [];
  5249. var data = json;
  5250. // async geometry loaders
  5251. for ( var typeID in this.geometryHandlerMap ) {
  5252. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5253. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5254. }
  5255. // async hierachy loaders
  5256. for ( var typeID in this.hierarchyHandlerMap ) {
  5257. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5258. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5259. }
  5260. counter_models = 0;
  5261. counter_textures = 0;
  5262. result = {
  5263. scene: new THREE.Scene(),
  5264. geometries: {},
  5265. face_materials: {},
  5266. materials: {},
  5267. textures: {},
  5268. objects: {},
  5269. cameras: {},
  5270. lights: {},
  5271. fogs: {},
  5272. empties: {}
  5273. };
  5274. if ( data.transform ) {
  5275. var position = data.transform.position,
  5276. rotation = data.transform.rotation,
  5277. scale = data.transform.scale;
  5278. if ( position )
  5279. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5280. if ( rotation )
  5281. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5282. if ( scale )
  5283. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5284. if ( position || rotation || scale ) {
  5285. result.scene.updateMatrix();
  5286. result.scene.updateMatrixWorld();
  5287. }
  5288. }
  5289. function get_url( source_url, url_type ) {
  5290. if ( url_type == "relativeToHTML" ) {
  5291. return source_url;
  5292. } else {
  5293. return urlBase + "/" + source_url;
  5294. }
  5295. };
  5296. // toplevel loader function, delegates to handle_children
  5297. function handle_objects() {
  5298. handle_children( result.scene, data.objects );
  5299. }
  5300. // handle all the children from the loaded json and attach them to given parent
  5301. function handle_children( parent, children ) {
  5302. for ( var dd in children ) {
  5303. // check by id if child has already been handled,
  5304. // if not, create new object
  5305. if ( result.objects[ dd ] === undefined ) {
  5306. var o = children[ dd ];
  5307. var object = null;
  5308. // meshes
  5309. if ( o.type && ( o.type in scope.hierarchyHandlerMap ) && o.loading === undefined ) {
  5310. var loaderParameters = {};
  5311. for ( var parType in g ) {
  5312. if ( parType !== "type" && parType !== "url" ) {
  5313. loaderParameters[ parType ] = g[ parType ];
  5314. }
  5315. }
  5316. material = result.materials[ o.material ];
  5317. o.loading = true;
  5318. var loader = scope.hierarchyHandlerMap[ o.type ][ "loaderObject" ];
  5319. // OBJLoader
  5320. if ( loader.addEventListener ) {
  5321. loader.addEventListener( 'load', create_callback_hierachy( dd, parent, material, o ) );
  5322. loader.load( get_url( o.url, data.urlBaseType ) );
  5323. } else {
  5324. // ColladaLoader
  5325. if ( loader.options ) {
  5326. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ) );
  5327. // UTF8Loader
  5328. } else {
  5329. loader.load( get_url( o.url, data.urlBaseType ), create_callback_hierachy( dd, parent, material, o ), loaderParameters );
  5330. }
  5331. }
  5332. } else if ( o.geometry !== undefined ) {
  5333. geometry = result.geometries[ o.geometry ];
  5334. // geometry already loaded
  5335. if ( geometry ) {
  5336. var needsTangents = false;
  5337. material = result.materials[ o.material ];
  5338. needsTangents = material instanceof THREE.ShaderMaterial;
  5339. p = o.position;
  5340. r = o.rotation;
  5341. q = o.quaternion;
  5342. s = o.scale;
  5343. m = o.matrix;
  5344. // turn off quaternions, for the moment
  5345. q = 0;
  5346. // use materials from the model file
  5347. // if there is no material specified in the object
  5348. if ( ! o.material ) {
  5349. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5350. }
  5351. // use materials from the model file
  5352. // if there is just empty face material
  5353. // (must create new material as each model has its own face material)
  5354. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  5355. material = new THREE.MeshFaceMaterial( result.face_materials[ o.geometry ] );
  5356. }
  5357. if ( material instanceof THREE.MeshFaceMaterial ) {
  5358. for ( var i = 0; i < material.materials.length; i ++ ) {
  5359. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  5360. }
  5361. }
  5362. if ( needsTangents ) {
  5363. geometry.computeTangents();
  5364. }
  5365. if ( o.skin ) {
  5366. object = new THREE.SkinnedMesh( geometry, material );
  5367. } else if ( o.morph ) {
  5368. object = new THREE.MorphAnimMesh( geometry, material );
  5369. if ( o.duration !== undefined ) {
  5370. object.duration = o.duration;
  5371. }
  5372. if ( o.time !== undefined ) {
  5373. object.time = o.time;
  5374. }
  5375. if ( o.mirroredLoop !== undefined ) {
  5376. object.mirroredLoop = o.mirroredLoop;
  5377. }
  5378. if ( material.morphNormals ) {
  5379. geometry.computeMorphNormals();
  5380. }
  5381. } else {
  5382. object = new THREE.Mesh( geometry, material );
  5383. }
  5384. object.name = dd;
  5385. if ( m ) {
  5386. object.matrixAutoUpdate = false;
  5387. object.matrix.set(
  5388. m[0], m[1], m[2], m[3],
  5389. m[4], m[5], m[6], m[7],
  5390. m[8], m[9], m[10], m[11],
  5391. m[12], m[13], m[14], m[15]
  5392. );
  5393. } else {
  5394. object.position.set( p[0], p[1], p[2] );
  5395. if ( q ) {
  5396. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5397. object.useQuaternion = true;
  5398. } else {
  5399. object.rotation.set( r[0], r[1], r[2] );
  5400. }
  5401. object.scale.set( s[0], s[1], s[2] );
  5402. }
  5403. object.visible = o.visible;
  5404. object.castShadow = o.castShadow;
  5405. object.receiveShadow = o.receiveShadow;
  5406. parent.add( object );
  5407. result.objects[ dd ] = object;
  5408. }
  5409. // lights
  5410. } else if ( o.type === "DirectionalLight" || o.type === "PointLight" || o.type === "AmbientLight" ) {
  5411. hex = ( o.color !== undefined ) ? o.color : 0xffffff;
  5412. intensity = ( o.intensity !== undefined ) ? o.intensity : 1;
  5413. if ( o.type === "DirectionalLight" ) {
  5414. p = o.direction;
  5415. light = new THREE.DirectionalLight( hex, intensity );
  5416. light.position.set( p[0], p[1], p[2] );
  5417. if ( o.target ) {
  5418. target_array.push( { "object": light, "targetName" : o.target } );
  5419. // kill existing default target
  5420. // otherwise it gets added to scene when parent gets added
  5421. light.target = null;
  5422. }
  5423. } else if ( o.type === "PointLight" ) {
  5424. p = o.position;
  5425. d = o.distance;
  5426. light = new THREE.PointLight( hex, intensity, d );
  5427. light.position.set( p[0], p[1], p[2] );
  5428. } else if ( o.type === "AmbientLight" ) {
  5429. light = new THREE.AmbientLight( hex );
  5430. }
  5431. parent.add( light );
  5432. light.name = dd;
  5433. result.lights[ dd ] = light;
  5434. result.objects[ dd ] = light;
  5435. // cameras
  5436. } else if ( o.type === "PerspectiveCamera" || o.type === "OrthographicCamera" ) {
  5437. if ( o.type === "PerspectiveCamera" ) {
  5438. camera = new THREE.PerspectiveCamera( o.fov, o.aspect, o.near, o.far );
  5439. } else if ( o.type === "OrthographicCamera" ) {
  5440. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5441. }
  5442. p = o.position;
  5443. camera.position.set( p[0], p[1], p[2] );
  5444. parent.add( camera );
  5445. camera.name = dd;
  5446. result.cameras[ dd ] = camera;
  5447. result.objects[ dd ] = camera;
  5448. // pure Object3D
  5449. } else {
  5450. p = o.position;
  5451. r = o.rotation;
  5452. q = o.quaternion;
  5453. s = o.scale;
  5454. // turn off quaternions, for the moment
  5455. q = 0;
  5456. object = new THREE.Object3D();
  5457. object.name = dd;
  5458. object.position.set( p[0], p[1], p[2] );
  5459. if ( q ) {
  5460. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5461. object.useQuaternion = true;
  5462. } else {
  5463. object.rotation.set( r[0], r[1], r[2] );
  5464. }
  5465. object.scale.set( s[0], s[1], s[2] );
  5466. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5467. parent.add( object );
  5468. result.objects[ dd ] = object;
  5469. result.empties[ dd ] = object;
  5470. }
  5471. if ( object ) {
  5472. if ( o.properties !== undefined ) {
  5473. for ( var key in o.properties ) {
  5474. var value = o.properties[ key ];
  5475. object.properties[ key ] = value;
  5476. }
  5477. }
  5478. if ( o.children !== undefined ) {
  5479. handle_children( object, o.children );
  5480. }
  5481. }
  5482. }
  5483. }
  5484. };
  5485. function handle_mesh( geo, mat, id ) {
  5486. result.geometries[ id ] = geo;
  5487. result.face_materials[ id ] = mat;
  5488. handle_objects();
  5489. };
  5490. function handle_hierarchy( node, id, parent, material, o ) {
  5491. var p = o.position;
  5492. var r = o.rotation;
  5493. var q = o.quaternion;
  5494. var s = o.scale;
  5495. node.position.set( p[0], p[1], p[2] );
  5496. if ( q ) {
  5497. node.quaternion.set( q[0], q[1], q[2], q[3] );
  5498. node.useQuaternion = true;
  5499. } else {
  5500. node.rotation.set( r[0], r[1], r[2] );
  5501. }
  5502. node.scale.set( s[0], s[1], s[2] );
  5503. if ( material ) {
  5504. node.traverse( function ( child ) {
  5505. child.material = material;
  5506. } );
  5507. }
  5508. parent.add( node );
  5509. result.objects[ id ] = node;
  5510. handle_objects();
  5511. };
  5512. function create_callback_geometry( id ) {
  5513. return function( geo, mat ) {
  5514. handle_mesh( geo, mat, id );
  5515. counter_models -= 1;
  5516. scope.onLoadComplete();
  5517. async_callback_gate();
  5518. }
  5519. };
  5520. function create_callback_hierachy( id, parent, material, obj ) {
  5521. return function( event ) {
  5522. var result;
  5523. // loaders which use EventTarget
  5524. if ( event.content ) {
  5525. result = event.content;
  5526. // ColladaLoader
  5527. } else if ( event.dae ) {
  5528. result = event.scene;
  5529. // UTF8Loader
  5530. } else {
  5531. result = event;
  5532. }
  5533. handle_hierarchy( result, id, parent, material, obj );
  5534. counter_models -= 1;
  5535. scope.onLoadComplete();
  5536. async_callback_gate();
  5537. }
  5538. };
  5539. function create_callback_embed( id ) {
  5540. return function( geo, mat ) {
  5541. result.geometries[ id ] = geo;
  5542. result.face_materials[ id ] = mat;
  5543. }
  5544. };
  5545. function async_callback_gate() {
  5546. var progress = {
  5547. totalModels : total_models,
  5548. totalTextures : total_textures,
  5549. loadedModels : total_models - counter_models,
  5550. loadedTextures : total_textures - counter_textures
  5551. };
  5552. scope.callbackProgress( progress, result );
  5553. scope.onLoadProgress();
  5554. if ( counter_models === 0 && counter_textures === 0 ) {
  5555. finalize();
  5556. callbackFinished( result );
  5557. }
  5558. };
  5559. function finalize() {
  5560. // take care of targets which could be asynchronously loaded objects
  5561. for ( var i = 0; i < target_array.length; i ++ ) {
  5562. var ta = target_array[ i ];
  5563. var target = result.objects[ ta.targetName ];
  5564. if ( target ) {
  5565. ta.object.target = target;
  5566. } else {
  5567. // if there was error and target of specified name doesn't exist in the scene file
  5568. // create instead dummy target
  5569. // (target must be added to scene explicitly as parent is already added)
  5570. ta.object.target = new THREE.Object3D();
  5571. result.scene.add( ta.object.target );
  5572. }
  5573. ta.object.target.properties.targetInverse = ta.object;
  5574. }
  5575. };
  5576. var callbackTexture = function ( count ) {
  5577. counter_textures -= count;
  5578. async_callback_gate();
  5579. scope.onLoadComplete();
  5580. };
  5581. // must use this instead of just directly calling callbackTexture
  5582. // because of closure in the calling context loop
  5583. var generateTextureCallback = function ( count ) {
  5584. return function() {
  5585. callbackTexture( count );
  5586. };
  5587. };
  5588. // first go synchronous elements
  5589. // fogs
  5590. for ( df in data.fogs ) {
  5591. f = data.fogs[ df ];
  5592. if ( f.type === "linear" ) {
  5593. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5594. } else if ( f.type === "exp2" ) {
  5595. fog = new THREE.FogExp2( 0x000000, f.density );
  5596. }
  5597. c = f.color;
  5598. fog.color.setRGB( c[0], c[1], c[2] );
  5599. result.fogs[ df ] = fog;
  5600. }
  5601. // now come potentially asynchronous elements
  5602. // geometries
  5603. // count how many geometries will be loaded asynchronously
  5604. for ( dg in data.geometries ) {
  5605. g = data.geometries[ dg ];
  5606. if ( g.type in this.geometryHandlerMap ) {
  5607. counter_models += 1;
  5608. scope.onLoadStart();
  5609. }
  5610. }
  5611. // count how many hierarchies will be loaded asynchronously
  5612. for ( var dd in data.objects ) {
  5613. var o = data.objects[ dd ];
  5614. if ( o.type && ( o.type in this.hierarchyHandlerMap ) ) {
  5615. counter_models += 1;
  5616. scope.onLoadStart();
  5617. }
  5618. }
  5619. total_models = counter_models;
  5620. for ( dg in data.geometries ) {
  5621. g = data.geometries[ dg ];
  5622. if ( g.type === "cube" ) {
  5623. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.widthSegments, g.heightSegments, g.depthSegments );
  5624. result.geometries[ dg ] = geometry;
  5625. } else if ( g.type === "plane" ) {
  5626. geometry = new THREE.PlaneGeometry( g.width, g.height, g.widthSegments, g.heightSegments );
  5627. result.geometries[ dg ] = geometry;
  5628. } else if ( g.type === "sphere" ) {
  5629. geometry = new THREE.SphereGeometry( g.radius, g.widthSegments, g.heightSegments );
  5630. result.geometries[ dg ] = geometry;
  5631. } else if ( g.type === "cylinder" ) {
  5632. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5633. result.geometries[ dg ] = geometry;
  5634. } else if ( g.type === "torus" ) {
  5635. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5636. result.geometries[ dg ] = geometry;
  5637. } else if ( g.type === "icosahedron" ) {
  5638. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5639. result.geometries[ dg ] = geometry;
  5640. } else if ( g.type in this.geometryHandlerMap ) {
  5641. var loaderParameters = {};
  5642. for ( var parType in g ) {
  5643. if ( parType !== "type" && parType !== "url" ) {
  5644. loaderParameters[ parType ] = g[ parType ];
  5645. }
  5646. }
  5647. var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
  5648. loader.load( get_url( g.url, data.urlBaseType ), create_callback_geometry( dg ), loaderParameters );
  5649. } else if ( g.type === "embedded" ) {
  5650. var modelJson = data.embeds[ g.id ],
  5651. texture_path = "";
  5652. // pass metadata along to jsonLoader so it knows the format version
  5653. modelJson.metadata = data.metadata;
  5654. if ( modelJson ) {
  5655. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  5656. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5657. }
  5658. }
  5659. }
  5660. // textures
  5661. // count how many textures will be loaded asynchronously
  5662. for ( dt in data.textures ) {
  5663. tt = data.textures[ dt ];
  5664. if ( tt.url instanceof Array ) {
  5665. counter_textures += tt.url.length;
  5666. for( var n = 0; n < tt.url.length; n ++ ) {
  5667. scope.onLoadStart();
  5668. }
  5669. } else {
  5670. counter_textures += 1;
  5671. scope.onLoadStart();
  5672. }
  5673. }
  5674. total_textures = counter_textures;
  5675. for ( dt in data.textures ) {
  5676. tt = data.textures[ dt ];
  5677. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5678. tt.mapping = new THREE[ tt.mapping ]();
  5679. }
  5680. if ( tt.url instanceof Array ) {
  5681. var count = tt.url.length;
  5682. var url_array = [];
  5683. for( var i = 0; i < count; i ++ ) {
  5684. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5685. }
  5686. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  5687. if ( isCompressed ) {
  5688. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5689. } else {
  5690. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5691. }
  5692. } else {
  5693. var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
  5694. var fullUrl = get_url( tt.url, data.urlBaseType );
  5695. var textureCallback = generateTextureCallback( 1 );
  5696. if ( isCompressed ) {
  5697. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
  5698. } else {
  5699. texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
  5700. }
  5701. if ( THREE[ tt.minFilter ] !== undefined )
  5702. texture.minFilter = THREE[ tt.minFilter ];
  5703. if ( THREE[ tt.magFilter ] !== undefined )
  5704. texture.magFilter = THREE[ tt.magFilter ];
  5705. if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
  5706. if ( tt.repeat ) {
  5707. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5708. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5709. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5710. }
  5711. if ( tt.offset ) {
  5712. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5713. }
  5714. // handle wrap after repeat so that default repeat can be overriden
  5715. if ( tt.wrap ) {
  5716. var wrapMap = {
  5717. "repeat" : THREE.RepeatWrapping,
  5718. "mirror" : THREE.MirroredRepeatWrapping
  5719. }
  5720. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5721. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5722. }
  5723. }
  5724. result.textures[ dt ] = texture;
  5725. }
  5726. // materials
  5727. for ( dm in data.materials ) {
  5728. m = data.materials[ dm ];
  5729. for ( pp in m.parameters ) {
  5730. if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
  5731. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5732. } else if ( pp === "shading" ) {
  5733. m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5734. } else if ( pp === "side" ) {
  5735. if ( m.parameters[ pp ] == "double" ) {
  5736. m.parameters[ pp ] = THREE.DoubleSide;
  5737. } else if ( m.parameters[ pp ] == "back" ) {
  5738. m.parameters[ pp ] = THREE.BackSide;
  5739. } else {
  5740. m.parameters[ pp ] = THREE.FrontSide;
  5741. }
  5742. } else if ( pp === "blending" ) {
  5743. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5744. } else if ( pp === "combine" ) {
  5745. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5746. } else if ( pp === "vertexColors" ) {
  5747. if ( m.parameters[ pp ] == "face" ) {
  5748. m.parameters[ pp ] = THREE.FaceColors;
  5749. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5750. } else if ( m.parameters[ pp ] ) {
  5751. m.parameters[ pp ] = THREE.VertexColors;
  5752. }
  5753. } else if ( pp === "wrapRGB" ) {
  5754. var v3 = m.parameters[ pp ];
  5755. m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  5756. }
  5757. }
  5758. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5759. m.parameters.transparent = true;
  5760. }
  5761. if ( m.parameters.normalMap ) {
  5762. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5763. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5764. var diffuse = m.parameters.color;
  5765. var specular = m.parameters.specular;
  5766. var ambient = m.parameters.ambient;
  5767. var shininess = m.parameters.shininess;
  5768. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  5769. if ( m.parameters.normalScale ) {
  5770. uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
  5771. }
  5772. if ( m.parameters.map ) {
  5773. uniforms[ "tDiffuse" ].value = m.parameters.map;
  5774. uniforms[ "enableDiffuse" ].value = true;
  5775. }
  5776. if ( m.parameters.envMap ) {
  5777. uniforms[ "tCube" ].value = m.parameters.envMap;
  5778. uniforms[ "enableReflection" ].value = true;
  5779. uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
  5780. }
  5781. if ( m.parameters.lightMap ) {
  5782. uniforms[ "tAO" ].value = m.parameters.lightMap;
  5783. uniforms[ "enableAO" ].value = true;
  5784. }
  5785. if ( m.parameters.specularMap ) {
  5786. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  5787. uniforms[ "enableSpecular" ].value = true;
  5788. }
  5789. if ( m.parameters.displacementMap ) {
  5790. uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
  5791. uniforms[ "enableDisplacement" ].value = true;
  5792. uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
  5793. uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
  5794. }
  5795. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5796. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5797. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5798. uniforms[ "uShininess" ].value = shininess;
  5799. if ( m.parameters.opacity ) {
  5800. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5801. }
  5802. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5803. material = new THREE.ShaderMaterial( parameters );
  5804. } else {
  5805. material = new THREE[ m.type ]( m.parameters );
  5806. }
  5807. result.materials[ dm ] = material;
  5808. }
  5809. // second pass through all materials to initialize MeshFaceMaterials
  5810. // that could be referring to other materials out of order
  5811. for ( dm in data.materials ) {
  5812. m = data.materials[ dm ];
  5813. if ( m.parameters.materials ) {
  5814. var materialArray = [];
  5815. for ( var i = 0; i < m.parameters.materials.length; i ++ ) {
  5816. var label = m.parameters.materials[ i ];
  5817. materialArray.push( result.materials[ label ] );
  5818. }
  5819. result.materials[ dm ].materials = materialArray;
  5820. }
  5821. }
  5822. // objects ( synchronous init of procedural primitives )
  5823. handle_objects();
  5824. // defaults
  5825. if ( result.cameras && data.defaults.camera ) {
  5826. result.currentCamera = result.cameras[ data.defaults.camera ];
  5827. }
  5828. if ( result.fogs && data.defaults.fog ) {
  5829. result.scene.fog = result.fogs[ data.defaults.fog ];
  5830. }
  5831. c = data.defaults.bgcolor;
  5832. result.bgColor = new THREE.Color();
  5833. result.bgColor.setRGB( c[0], c[1], c[2] );
  5834. result.bgColorAlpha = data.defaults.bgalpha;
  5835. // synchronous callback
  5836. scope.callbackSync( result );
  5837. // just in case there are no async elements
  5838. async_callback_gate();
  5839. };
  5840. /**
  5841. * @author mrdoob / http://mrdoob.com/
  5842. */
  5843. THREE.TextureLoader = function () {
  5844. THREE.EventTarget.call( this );
  5845. this.crossOrigin = null;
  5846. };
  5847. THREE.TextureLoader.prototype = {
  5848. constructor: THREE.TextureLoader,
  5849. load: function ( url ) {
  5850. var scope = this;
  5851. var image = new Image();
  5852. image.addEventListener( 'load', function () {
  5853. var texture = new THREE.Texture( image );
  5854. texture.needsUpdate = true;
  5855. scope.dispatchEvent( { type: 'load', content: texture } );
  5856. }, false );
  5857. image.addEventListener( 'error', function () {
  5858. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5859. }, false );
  5860. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5861. image.src = url;
  5862. }
  5863. }
  5864. /**
  5865. * @author mrdoob / http://mrdoob.com/
  5866. * @author alteredq / http://alteredqualia.com/
  5867. */
  5868. THREE.Material = function () {
  5869. THREE.MaterialLibrary.push( this );
  5870. this.id = THREE.MaterialIdCount ++;
  5871. this.name = '';
  5872. this.side = THREE.FrontSide;
  5873. this.opacity = 1;
  5874. this.transparent = false;
  5875. this.blending = THREE.NormalBlending;
  5876. this.blendSrc = THREE.SrcAlphaFactor;
  5877. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5878. this.blendEquation = THREE.AddEquation;
  5879. this.depthTest = true;
  5880. this.depthWrite = true;
  5881. this.polygonOffset = false;
  5882. this.polygonOffsetFactor = 0;
  5883. this.polygonOffsetUnits = 0;
  5884. this.alphaTest = 0;
  5885. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5886. this.visible = true;
  5887. this.needsUpdate = true;
  5888. };
  5889. THREE.Material.prototype.setValues = function ( values ) {
  5890. if ( values === undefined ) return;
  5891. for ( var key in values ) {
  5892. var newValue = values[ key ];
  5893. if ( newValue === undefined ) {
  5894. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5895. continue;
  5896. }
  5897. if ( key in this ) {
  5898. var currentValue = this[ key ];
  5899. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5900. currentValue.copy( newValue );
  5901. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5902. currentValue.setHex( newValue );
  5903. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5904. currentValue.copy( newValue );
  5905. } else {
  5906. this[ key ] = newValue;
  5907. }
  5908. }
  5909. }
  5910. };
  5911. THREE.Material.prototype.clone = function ( material ) {
  5912. if ( material === undefined ) material = new THREE.Material();
  5913. material.name = this.name;
  5914. material.side = this.side;
  5915. material.opacity = this.opacity;
  5916. material.transparent = this.transparent;
  5917. material.blending = this.blending;
  5918. material.blendSrc = this.blendSrc;
  5919. material.blendDst = this.blendDst;
  5920. material.blendEquation = this.blendEquation;
  5921. material.depthTest = this.depthTest;
  5922. material.depthWrite = this.depthWrite;
  5923. material.polygonOffset = this.polygonOffset;
  5924. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5925. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5926. material.alphaTest = this.alphaTest;
  5927. material.overdraw = this.overdraw;
  5928. material.visible = this.visible;
  5929. return material;
  5930. };
  5931. THREE.Material.prototype.deallocate = function () {
  5932. var index = THREE.MaterialLibrary.indexOf( this );
  5933. if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
  5934. };
  5935. THREE.MaterialIdCount = 0;
  5936. THREE.MaterialLibrary = [];
  5937. /**
  5938. * @author mrdoob / http://mrdoob.com/
  5939. * @author alteredq / http://alteredqualia.com/
  5940. *
  5941. * parameters = {
  5942. * color: <hex>,
  5943. * opacity: <float>,
  5944. *
  5945. * blending: THREE.NormalBlending,
  5946. * depthTest: <bool>,
  5947. * depthWrite: <bool>,
  5948. *
  5949. * linewidth: <float>,
  5950. * linecap: "round",
  5951. * linejoin: "round",
  5952. *
  5953. * vertexColors: <bool>
  5954. *
  5955. * fog: <bool>
  5956. * }
  5957. */
  5958. THREE.LineBasicMaterial = function ( parameters ) {
  5959. THREE.Material.call( this );
  5960. this.color = new THREE.Color( 0xffffff );
  5961. this.linewidth = 1;
  5962. this.linecap = 'round';
  5963. this.linejoin = 'round';
  5964. this.vertexColors = false;
  5965. this.fog = true;
  5966. this.setValues( parameters );
  5967. };
  5968. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  5969. THREE.LineBasicMaterial.prototype.clone = function () {
  5970. var material = new THREE.LineBasicMaterial();
  5971. THREE.Material.prototype.clone.call( this, material );
  5972. material.color.copy( this.color );
  5973. material.linewidth = this.linewidth;
  5974. material.linecap = this.linecap;
  5975. material.linejoin = this.linejoin;
  5976. material.vertexColors = this.vertexColors;
  5977. material.fog = this.fog;
  5978. return material;
  5979. };
  5980. /**
  5981. * @author alteredq / http://alteredqualia.com/
  5982. *
  5983. * parameters = {
  5984. * color: <hex>,
  5985. * opacity: <float>,
  5986. *
  5987. * blending: THREE.NormalBlending,
  5988. * depthTest: <bool>,
  5989. * depthWrite: <bool>,
  5990. *
  5991. * linewidth: <float>,
  5992. *
  5993. * scale: <float>,
  5994. * dashSize: <float>,
  5995. * gapSize: <float>,
  5996. *
  5997. * vertexColors: <bool>
  5998. *
  5999. * fog: <bool>
  6000. * }
  6001. */
  6002. THREE.LineDashedMaterial = function ( parameters ) {
  6003. THREE.Material.call( this );
  6004. this.color = new THREE.Color( 0xffffff );
  6005. this.linewidth = 1;
  6006. this.scale = 1;
  6007. this.dashSize = 3;
  6008. this.gapSize = 1;
  6009. this.vertexColors = false;
  6010. this.fog = true;
  6011. this.setValues( parameters );
  6012. };
  6013. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6014. THREE.LineDashedMaterial.prototype.clone = function () {
  6015. var material = new THREE.LineDashedMaterial();
  6016. THREE.Material.prototype.clone.call( this, material );
  6017. material.color.copy( this.color );
  6018. material.linewidth = this.linewidth;
  6019. material.scale = this.scale;
  6020. material.dashSize = this.dashSize;
  6021. material.gapSize = this.gapSize;
  6022. material.vertexColors = this.vertexColors;
  6023. material.fog = this.fog;
  6024. return material;
  6025. };
  6026. /**
  6027. * @author mrdoob / http://mrdoob.com/
  6028. * @author alteredq / http://alteredqualia.com/
  6029. *
  6030. * parameters = {
  6031. * color: <hex>,
  6032. * opacity: <float>,
  6033. * map: new THREE.Texture( <Image> ),
  6034. *
  6035. * lightMap: new THREE.Texture( <Image> ),
  6036. *
  6037. * specularMap: new THREE.Texture( <Image> ),
  6038. *
  6039. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6040. * combine: THREE.Multiply,
  6041. * reflectivity: <float>,
  6042. * refractionRatio: <float>,
  6043. *
  6044. * shading: THREE.SmoothShading,
  6045. * blending: THREE.NormalBlending,
  6046. * depthTest: <bool>,
  6047. * depthWrite: <bool>,
  6048. *
  6049. * wireframe: <boolean>,
  6050. * wireframeLinewidth: <float>,
  6051. *
  6052. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6053. *
  6054. * skinning: <bool>,
  6055. * morphTargets: <bool>,
  6056. *
  6057. * fog: <bool>
  6058. * }
  6059. */
  6060. THREE.MeshBasicMaterial = function ( parameters ) {
  6061. THREE.Material.call( this );
  6062. this.color = new THREE.Color( 0xffffff ); // emissive
  6063. this.map = null;
  6064. this.lightMap = null;
  6065. this.specularMap = null;
  6066. this.envMap = null;
  6067. this.combine = THREE.MultiplyOperation;
  6068. this.reflectivity = 1;
  6069. this.refractionRatio = 0.98;
  6070. this.fog = true;
  6071. this.shading = THREE.SmoothShading;
  6072. this.wireframe = false;
  6073. this.wireframeLinewidth = 1;
  6074. this.wireframeLinecap = 'round';
  6075. this.wireframeLinejoin = 'round';
  6076. this.vertexColors = THREE.NoColors;
  6077. this.skinning = false;
  6078. this.morphTargets = false;
  6079. this.setValues( parameters );
  6080. };
  6081. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6082. THREE.MeshBasicMaterial.prototype.clone = function () {
  6083. var material = new THREE.MeshBasicMaterial();
  6084. THREE.Material.prototype.clone.call( this, material );
  6085. material.color.copy( this.color );
  6086. material.map = this.map;
  6087. material.lightMap = this.lightMap;
  6088. material.specularMap = this.specularMap;
  6089. material.envMap = this.envMap;
  6090. material.combine = this.combine;
  6091. material.reflectivity = this.reflectivity;
  6092. material.refractionRatio = this.refractionRatio;
  6093. material.fog = this.fog;
  6094. material.shading = this.shading;
  6095. material.wireframe = this.wireframe;
  6096. material.wireframeLinewidth = this.wireframeLinewidth;
  6097. material.wireframeLinecap = this.wireframeLinecap;
  6098. material.wireframeLinejoin = this.wireframeLinejoin;
  6099. material.vertexColors = this.vertexColors;
  6100. material.skinning = this.skinning;
  6101. material.morphTargets = this.morphTargets;
  6102. return material;
  6103. };
  6104. /**
  6105. * @author mrdoob / http://mrdoob.com/
  6106. * @author alteredq / http://alteredqualia.com/
  6107. *
  6108. * parameters = {
  6109. * color: <hex>,
  6110. * ambient: <hex>,
  6111. * emissive: <hex>,
  6112. * opacity: <float>,
  6113. *
  6114. * map: new THREE.Texture( <Image> ),
  6115. *
  6116. * lightMap: new THREE.Texture( <Image> ),
  6117. *
  6118. * specularMap: new THREE.Texture( <Image> ),
  6119. *
  6120. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6121. * combine: THREE.Multiply,
  6122. * reflectivity: <float>,
  6123. * refractionRatio: <float>,
  6124. *
  6125. * shading: THREE.SmoothShading,
  6126. * blending: THREE.NormalBlending,
  6127. * depthTest: <bool>,
  6128. * depthWrite: <bool>,
  6129. *
  6130. * wireframe: <boolean>,
  6131. * wireframeLinewidth: <float>,
  6132. *
  6133. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6134. *
  6135. * skinning: <bool>,
  6136. * morphTargets: <bool>,
  6137. * morphNormals: <bool>,
  6138. *
  6139. * fog: <bool>
  6140. * }
  6141. */
  6142. THREE.MeshLambertMaterial = function ( parameters ) {
  6143. THREE.Material.call( this );
  6144. this.color = new THREE.Color( 0xffffff ); // diffuse
  6145. this.ambient = new THREE.Color( 0xffffff );
  6146. this.emissive = new THREE.Color( 0x000000 );
  6147. this.wrapAround = false;
  6148. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6149. this.map = null;
  6150. this.lightMap = null;
  6151. this.specularMap = null;
  6152. this.envMap = null;
  6153. this.combine = THREE.MultiplyOperation;
  6154. this.reflectivity = 1;
  6155. this.refractionRatio = 0.98;
  6156. this.fog = true;
  6157. this.shading = THREE.SmoothShading;
  6158. this.wireframe = false;
  6159. this.wireframeLinewidth = 1;
  6160. this.wireframeLinecap = 'round';
  6161. this.wireframeLinejoin = 'round';
  6162. this.vertexColors = THREE.NoColors;
  6163. this.skinning = false;
  6164. this.morphTargets = false;
  6165. this.morphNormals = false;
  6166. this.setValues( parameters );
  6167. };
  6168. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6169. THREE.MeshLambertMaterial.prototype.clone = function () {
  6170. var material = new THREE.MeshLambertMaterial();
  6171. THREE.Material.prototype.clone.call( this, material );
  6172. material.color.copy( this.color );
  6173. material.ambient.copy( this.ambient );
  6174. material.emissive.copy( this.emissive );
  6175. material.wrapAround = this.wrapAround;
  6176. material.wrapRGB.copy( this.wrapRGB );
  6177. material.map = this.map;
  6178. material.lightMap = this.lightMap;
  6179. material.specularMap = this.specularMap;
  6180. material.envMap = this.envMap;
  6181. material.combine = this.combine;
  6182. material.reflectivity = this.reflectivity;
  6183. material.refractionRatio = this.refractionRatio;
  6184. material.fog = this.fog;
  6185. material.shading = this.shading;
  6186. material.wireframe = this.wireframe;
  6187. material.wireframeLinewidth = this.wireframeLinewidth;
  6188. material.wireframeLinecap = this.wireframeLinecap;
  6189. material.wireframeLinejoin = this.wireframeLinejoin;
  6190. material.vertexColors = this.vertexColors;
  6191. material.skinning = this.skinning;
  6192. material.morphTargets = this.morphTargets;
  6193. material.morphNormals = this.morphNormals;
  6194. return material;
  6195. };
  6196. /**
  6197. * @author mrdoob / http://mrdoob.com/
  6198. * @author alteredq / http://alteredqualia.com/
  6199. *
  6200. * parameters = {
  6201. * color: <hex>,
  6202. * ambient: <hex>,
  6203. * emissive: <hex>,
  6204. * specular: <hex>,
  6205. * shininess: <float>,
  6206. * opacity: <float>,
  6207. *
  6208. * map: new THREE.Texture( <Image> ),
  6209. *
  6210. * lightMap: new THREE.Texture( <Image> ),
  6211. *
  6212. * bumpMap: new THREE.Texture( <Image> ),
  6213. * bumpScale: <float>,
  6214. *
  6215. * normalMap: new THREE.Texture( <Image> ),
  6216. * normalScale: <Vector2>,
  6217. *
  6218. * specularMap: new THREE.Texture( <Image> ),
  6219. *
  6220. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6221. * combine: THREE.Multiply,
  6222. * reflectivity: <float>,
  6223. * refractionRatio: <float>,
  6224. *
  6225. * shading: THREE.SmoothShading,
  6226. * blending: THREE.NormalBlending,
  6227. * depthTest: <bool>,
  6228. * depthWrite: <bool>,
  6229. *
  6230. * wireframe: <boolean>,
  6231. * wireframeLinewidth: <float>,
  6232. *
  6233. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6234. *
  6235. * skinning: <bool>,
  6236. * morphTargets: <bool>,
  6237. * morphNormals: <bool>,
  6238. *
  6239. * fog: <bool>
  6240. * }
  6241. */
  6242. THREE.MeshPhongMaterial = function ( parameters ) {
  6243. THREE.Material.call( this );
  6244. this.color = new THREE.Color( 0xffffff ); // diffuse
  6245. this.ambient = new THREE.Color( 0xffffff );
  6246. this.emissive = new THREE.Color( 0x000000 );
  6247. this.specular = new THREE.Color( 0x111111 );
  6248. this.shininess = 30;
  6249. this.metal = false;
  6250. this.perPixel = true;
  6251. this.wrapAround = false;
  6252. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6253. this.map = null;
  6254. this.lightMap = null;
  6255. this.bumpMap = null;
  6256. this.bumpScale = 1;
  6257. this.normalMap = null;
  6258. this.normalScale = new THREE.Vector2( 1, 1 );
  6259. this.specularMap = null;
  6260. this.envMap = null;
  6261. this.combine = THREE.MultiplyOperation;
  6262. this.reflectivity = 1;
  6263. this.refractionRatio = 0.98;
  6264. this.fog = true;
  6265. this.shading = THREE.SmoothShading;
  6266. this.wireframe = false;
  6267. this.wireframeLinewidth = 1;
  6268. this.wireframeLinecap = 'round';
  6269. this.wireframeLinejoin = 'round';
  6270. this.vertexColors = THREE.NoColors;
  6271. this.skinning = false;
  6272. this.morphTargets = false;
  6273. this.morphNormals = false;
  6274. this.setValues( parameters );
  6275. };
  6276. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6277. THREE.MeshPhongMaterial.prototype.clone = function () {
  6278. var material = new THREE.MeshPhongMaterial();
  6279. THREE.Material.prototype.clone.call( this, material );
  6280. material.color.copy( this.color );
  6281. material.ambient.copy( this.ambient );
  6282. material.emissive.copy( this.emissive );
  6283. material.specular.copy( this.specular );
  6284. material.shininess = this.shininess;
  6285. material.metal = this.metal;
  6286. material.perPixel = this.perPixel;
  6287. material.wrapAround = this.wrapAround;
  6288. material.wrapRGB.copy( this.wrapRGB );
  6289. material.map = this.map;
  6290. material.lightMap = this.lightMap;
  6291. material.bumpMap = this.bumpMap;
  6292. material.bumpScale = this.bumpScale;
  6293. material.normalMap = this.normalMap;
  6294. material.normalScale.copy( this.normalScale );
  6295. material.specularMap = this.specularMap;
  6296. material.envMap = this.envMap;
  6297. material.combine = this.combine;
  6298. material.reflectivity = this.reflectivity;
  6299. material.refractionRatio = this.refractionRatio;
  6300. material.fog = this.fog;
  6301. material.shading = this.shading;
  6302. material.wireframe = this.wireframe;
  6303. material.wireframeLinewidth = this.wireframeLinewidth;
  6304. material.wireframeLinecap = this.wireframeLinecap;
  6305. material.wireframeLinejoin = this.wireframeLinejoin;
  6306. material.vertexColors = this.vertexColors;
  6307. material.skinning = this.skinning;
  6308. material.morphTargets = this.morphTargets;
  6309. material.morphNormals = this.morphNormals;
  6310. return material;
  6311. };
  6312. /**
  6313. * @author mrdoob / http://mrdoob.com/
  6314. * @author alteredq / http://alteredqualia.com/
  6315. *
  6316. * parameters = {
  6317. * opacity: <float>,
  6318. *
  6319. * blending: THREE.NormalBlending,
  6320. * depthTest: <bool>,
  6321. * depthWrite: <bool>,
  6322. *
  6323. * wireframe: <boolean>,
  6324. * wireframeLinewidth: <float>
  6325. * }
  6326. */
  6327. THREE.MeshDepthMaterial = function ( parameters ) {
  6328. THREE.Material.call( this );
  6329. this.wireframe = false;
  6330. this.wireframeLinewidth = 1;
  6331. this.setValues( parameters );
  6332. };
  6333. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6334. THREE.MeshDepthMaterial.prototype.clone = function () {
  6335. var material = new THREE.LineBasicMaterial();
  6336. THREE.Material.prototype.clone.call( this, material );
  6337. material.wireframe = this.wireframe;
  6338. material.wireframeLinewidth = this.wireframeLinewidth;
  6339. return material;
  6340. };
  6341. /**
  6342. * @author mrdoob / http://mrdoob.com/
  6343. *
  6344. * parameters = {
  6345. * opacity: <float>,
  6346. *
  6347. * shading: THREE.FlatShading,
  6348. * blending: THREE.NormalBlending,
  6349. * depthTest: <bool>,
  6350. * depthWrite: <bool>,
  6351. *
  6352. * wireframe: <boolean>,
  6353. * wireframeLinewidth: <float>
  6354. * }
  6355. */
  6356. THREE.MeshNormalMaterial = function ( parameters ) {
  6357. THREE.Material.call( this, parameters );
  6358. this.shading = THREE.FlatShading;
  6359. this.wireframe = false;
  6360. this.wireframeLinewidth = 1;
  6361. this.setValues( parameters );
  6362. };
  6363. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6364. THREE.MeshNormalMaterial.prototype.clone = function () {
  6365. var material = new THREE.MeshNormalMaterial();
  6366. THREE.Material.prototype.clone.call( this, material );
  6367. material.shading = this.shading;
  6368. material.wireframe = this.wireframe;
  6369. material.wireframeLinewidth = this.wireframeLinewidth;
  6370. return material;
  6371. };
  6372. /**
  6373. * @author mrdoob / http://mrdoob.com/
  6374. */
  6375. THREE.MeshFaceMaterial = function ( materials ) {
  6376. this.materials = materials instanceof Array ? materials : [];
  6377. };
  6378. THREE.MeshFaceMaterial.prototype.clone = function () {
  6379. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  6380. };
  6381. /**
  6382. * @author mrdoob / http://mrdoob.com/
  6383. * @author alteredq / http://alteredqualia.com/
  6384. *
  6385. * parameters = {
  6386. * color: <hex>,
  6387. * opacity: <float>,
  6388. * map: new THREE.Texture( <Image> ),
  6389. *
  6390. * size: <float>,
  6391. *
  6392. * blending: THREE.NormalBlending,
  6393. * depthTest: <bool>,
  6394. * depthWrite: <bool>,
  6395. *
  6396. * vertexColors: <bool>,
  6397. *
  6398. * fog: <bool>
  6399. * }
  6400. */
  6401. THREE.ParticleBasicMaterial = function ( parameters ) {
  6402. THREE.Material.call( this );
  6403. this.color = new THREE.Color( 0xffffff );
  6404. this.map = null;
  6405. this.size = 1;
  6406. this.sizeAttenuation = true;
  6407. this.vertexColors = false;
  6408. this.fog = true;
  6409. this.setValues( parameters );
  6410. };
  6411. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6412. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6413. var material = new THREE.ParticleBasicMaterial();
  6414. THREE.Material.prototype.clone.call( this, material );
  6415. material.color.copy( this.color );
  6416. material.map = this.map;
  6417. material.size = this.size;
  6418. material.sizeAttenuation = this.sizeAttenuation;
  6419. material.vertexColors = this.vertexColors;
  6420. material.fog = this.fog;
  6421. return material;
  6422. };
  6423. /**
  6424. * @author mrdoob / http://mrdoob.com/
  6425. *
  6426. * parameters = {
  6427. * color: <hex>,
  6428. * program: <function>,
  6429. * opacity: <float>,
  6430. * blending: THREE.NormalBlending
  6431. * }
  6432. */
  6433. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6434. THREE.Material.call( this );
  6435. this.color = new THREE.Color( 0xffffff );
  6436. this.program = function ( context, color ) {};
  6437. this.setValues( parameters );
  6438. };
  6439. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6440. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6441. var material = new THREE.ParticleCanvasMaterial();
  6442. THREE.Material.prototype.clone.call( this, material );
  6443. material.color.copy( this.color );
  6444. material.program = this.program;
  6445. return material;
  6446. };
  6447. /**
  6448. * @author mrdoob / http://mrdoob.com/
  6449. */
  6450. THREE.ParticleDOMMaterial = function ( element ) {
  6451. this.element = element;
  6452. };
  6453. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6454. return new THREE.ParticleDOMMaterial( this.element );
  6455. };
  6456. /**
  6457. * @author alteredq / http://alteredqualia.com/
  6458. *
  6459. * parameters = {
  6460. * fragmentShader: <string>,
  6461. * vertexShader: <string>,
  6462. *
  6463. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6464. *
  6465. * defines: { "label" : "value" },
  6466. *
  6467. * shading: THREE.SmoothShading,
  6468. * blending: THREE.NormalBlending,
  6469. * depthTest: <bool>,
  6470. * depthWrite: <bool>,
  6471. *
  6472. * wireframe: <boolean>,
  6473. * wireframeLinewidth: <float>,
  6474. *
  6475. * lights: <bool>,
  6476. *
  6477. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6478. *
  6479. * skinning: <bool>,
  6480. * morphTargets: <bool>,
  6481. * morphNormals: <bool>,
  6482. *
  6483. * fog: <bool>
  6484. * }
  6485. */
  6486. THREE.ShaderMaterial = function ( parameters ) {
  6487. THREE.Material.call( this );
  6488. this.fragmentShader = "void main() {}";
  6489. this.vertexShader = "void main() {}";
  6490. this.uniforms = {};
  6491. this.defines = {};
  6492. this.attributes = null;
  6493. this.shading = THREE.SmoothShading;
  6494. this.wireframe = false;
  6495. this.wireframeLinewidth = 1;
  6496. this.fog = false; // set to use scene fog
  6497. this.lights = false; // set to use scene lights
  6498. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6499. this.skinning = false; // set to use skinning attribute streams
  6500. this.morphTargets = false; // set to use morph targets
  6501. this.morphNormals = false; // set to use morph normals
  6502. this.setValues( parameters );
  6503. };
  6504. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6505. THREE.ShaderMaterial.prototype.clone = function () {
  6506. var material = new THREE.ShaderMaterial();
  6507. THREE.Material.prototype.clone.call( this, material );
  6508. material.fragmentShader = this.fragmentShader;
  6509. material.vertexShader = this.vertexShader;
  6510. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  6511. material.attributes = this.attributes;
  6512. material.defines = this.defines;
  6513. material.shading = this.shading;
  6514. material.wireframe = this.wireframe;
  6515. material.wireframeLinewidth = this.wireframeLinewidth;
  6516. material.fog = this.fog;
  6517. material.lights = this.lights;
  6518. material.vertexColors = this.vertexColors;
  6519. material.skinning = this.skinning;
  6520. material.morphTargets = this.morphTargets;
  6521. material.morphNormals = this.morphNormals;
  6522. return material;
  6523. };
  6524. /**
  6525. * @author alteredq / http://alteredqualia.com/
  6526. *
  6527. * parameters = {
  6528. * color: <hex>,
  6529. * opacity: <float>,
  6530. * map: new THREE.Texture( <Image> ),
  6531. *
  6532. * blending: THREE.NormalBlending,
  6533. * depthTest: <bool>,
  6534. * depthWrite: <bool>,
  6535. *
  6536. * useScreenCoordinates: <bool>,
  6537. * sizeAttenuation: <bool>,
  6538. * scaleByViewport: <bool>,
  6539. * alignment: THREE.SpriteAlignment.center,
  6540. *
  6541. * uvOffset: new THREE.Vector2(),
  6542. * uvScale: new THREE.Vector2(),
  6543. *
  6544. * fog: <bool>
  6545. * }
  6546. */
  6547. THREE.SpriteMaterial = function ( parameters ) {
  6548. THREE.Material.call( this );
  6549. // defaults
  6550. this.color = new THREE.Color( 0xffffff );
  6551. this.map = new THREE.Texture();
  6552. this.useScreenCoordinates = true;
  6553. this.depthTest = !this.useScreenCoordinates;
  6554. this.sizeAttenuation = !this.useScreenCoordinates;
  6555. this.scaleByViewport = !this.sizeAttenuation;
  6556. this.alignment = THREE.SpriteAlignment.center.clone();
  6557. this.fog = false;
  6558. this.uvOffset = new THREE.Vector2( 0, 0 );
  6559. this.uvScale = new THREE.Vector2( 1, 1 );
  6560. // set parameters
  6561. this.setValues( parameters );
  6562. // override coupled defaults if not specified explicitly by parameters
  6563. parameters = parameters || {};
  6564. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  6565. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  6566. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  6567. };
  6568. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  6569. THREE.SpriteMaterial.prototype.clone = function () {
  6570. var material = new THREE.SpriteMaterial();
  6571. THREE.Material.prototype.clone.call( this, material );
  6572. material.color.copy( this.color );
  6573. material.map = this.map;
  6574. material.useScreenCoordinates = this.useScreenCoordinates;
  6575. material.sizeAttenuation = this.sizeAttenuation;
  6576. material.scaleByViewport = this.scaleByViewport;
  6577. material.alignment.copy( this.alignment );
  6578. material.uvOffset.copy( this.uvOffset );
  6579. material.uvScale.copy( this.uvScale );
  6580. material.fog = this.fog;
  6581. return material;
  6582. };
  6583. // Alignment enums
  6584. THREE.SpriteAlignment = {};
  6585. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  6586. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  6587. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  6588. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  6589. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  6590. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  6591. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  6592. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  6593. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  6594. /**
  6595. * @author mrdoob / http://mrdoob.com/
  6596. * @author alteredq / http://alteredqualia.com/
  6597. * @author szimek / https://github.com/szimek/
  6598. */
  6599. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6600. THREE.TextureLibrary.push( this );
  6601. this.id = THREE.TextureIdCount ++;
  6602. this.name = '';
  6603. this.image = image;
  6604. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6605. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6606. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6607. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6608. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6609. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6610. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6611. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6612. this.offset = new THREE.Vector2( 0, 0 );
  6613. this.repeat = new THREE.Vector2( 1, 1 );
  6614. this.generateMipmaps = true;
  6615. this.premultiplyAlpha = false;
  6616. this.flipY = true;
  6617. this.needsUpdate = false;
  6618. this.onUpdate = null;
  6619. };
  6620. THREE.Texture.prototype = {
  6621. constructor: THREE.Texture,
  6622. clone: function () {
  6623. var texture = new THREE.Texture();
  6624. texture.image = this.image;
  6625. texture.mapping = this.mapping;
  6626. texture.wrapS = this.wrapS;
  6627. texture.wrapT = this.wrapT;
  6628. texture.magFilter = this.magFilter;
  6629. texture.minFilter = this.minFilter;
  6630. texture.anisotropy = this.anisotropy;
  6631. texture.format = this.format;
  6632. texture.type = this.type;
  6633. texture.offset.copy( this.offset );
  6634. texture.repeat.copy( this.repeat );
  6635. texture.generateMipmaps = this.generateMipmaps;
  6636. texture.premultiplyAlpha = this.premultiplyAlpha;
  6637. texture.flipY = this.flipY;
  6638. return texture;
  6639. },
  6640. deallocate: function () {
  6641. var index = THREE.TextureLibrary.indexOf( this );
  6642. if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
  6643. }
  6644. };
  6645. THREE.TextureIdCount = 0;
  6646. THREE.TextureLibrary = [];
  6647. /**
  6648. * @author alteredq / http://alteredqualia.com/
  6649. */
  6650. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  6651. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  6652. this.image = { width: width, height: height };
  6653. this.mipmaps = mipmaps;
  6654. };
  6655. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  6656. THREE.CompressedTexture.prototype.clone = function () {
  6657. var texture = new THREE.CompressedTexture();
  6658. texture.image = this.image;
  6659. texture.mipmaps = this.mipmaps;
  6660. texture.format = this.format;
  6661. texture.type = this.type;
  6662. texture.mapping = this.mapping;
  6663. texture.wrapS = this.wrapS;
  6664. texture.wrapT = this.wrapT;
  6665. texture.magFilter = this.magFilter;
  6666. texture.minFilter = this.minFilter;
  6667. texture.anisotropy = this.anisotropy;
  6668. texture.offset.copy( this.offset );
  6669. texture.repeat.copy( this.repeat );
  6670. return texture;
  6671. };
  6672. /**
  6673. * @author alteredq / http://alteredqualia.com/
  6674. */
  6675. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  6676. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  6677. this.image = { data: data, width: width, height: height };
  6678. };
  6679. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6680. THREE.DataTexture.prototype.clone = function () {
  6681. var clonedTexture = new THREE.DataTexture( this.image.data, this.image.width, this.image.height, this.format, this.type, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter, this.anisotropy );
  6682. clonedTexture.offset.copy( this.offset );
  6683. clonedTexture.repeat.copy( this.repeat );
  6684. return clonedTexture;
  6685. };
  6686. /**
  6687. * @author mrdoob / http://mrdoob.com/
  6688. */
  6689. THREE.Particle = function ( material ) {
  6690. THREE.Object3D.call( this );
  6691. this.material = material;
  6692. };
  6693. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6694. THREE.Particle.prototype.clone = function ( object ) {
  6695. if ( object === undefined ) object = new THREE.Particle( this.material );
  6696. THREE.Object3D.prototype.clone.call( this, object );
  6697. return object;
  6698. };
  6699. /**
  6700. * @author alteredq / http://alteredqualia.com/
  6701. */
  6702. THREE.ParticleSystem = function ( geometry, material ) {
  6703. THREE.Object3D.call( this );
  6704. this.geometry = geometry;
  6705. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6706. this.sortParticles = false;
  6707. if ( this.geometry ) {
  6708. // calc bound radius
  6709. if( this.geometry.boundingSphere === null ) {
  6710. this.geometry.computeBoundingSphere();
  6711. }
  6712. this.boundRadius = geometry.boundingSphere.radius;
  6713. }
  6714. this.frustumCulled = false;
  6715. };
  6716. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6717. THREE.ParticleSystem.prototype.clone = function ( object ) {
  6718. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  6719. object.sortParticles = this.sortParticles;
  6720. THREE.Object3D.prototype.clone.call( this, object );
  6721. return object;
  6722. };
  6723. /**
  6724. * @author mrdoob / http://mrdoob.com/
  6725. */
  6726. THREE.Line = function ( geometry, material, type ) {
  6727. THREE.Object3D.call( this );
  6728. this.geometry = geometry;
  6729. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6730. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6731. if ( this.geometry ) {
  6732. if ( ! this.geometry.boundingSphere ) {
  6733. this.geometry.computeBoundingSphere();
  6734. }
  6735. }
  6736. };
  6737. THREE.LineStrip = 0;
  6738. THREE.LinePieces = 1;
  6739. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6740. THREE.Line.prototype.clone = function ( object ) {
  6741. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  6742. THREE.Object3D.prototype.clone.call( this, object );
  6743. return object;
  6744. };
  6745. /**
  6746. * @author mrdoob / http://mrdoob.com/
  6747. * @author alteredq / http://alteredqualia.com/
  6748. * @author mikael emtinger / http://gomo.se/
  6749. */
  6750. THREE.Mesh = function ( geometry, material ) {
  6751. THREE.Object3D.call( this );
  6752. this.geometry = geometry;
  6753. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6754. if ( this.geometry ) {
  6755. // calc bound radius
  6756. if ( this.geometry.boundingSphere === null ) {
  6757. this.geometry.computeBoundingSphere();
  6758. }
  6759. this.boundRadius = geometry.boundingSphere.radius;
  6760. // setup morph targets
  6761. if ( this.geometry.morphTargets.length ) {
  6762. this.morphTargetBase = -1;
  6763. this.morphTargetForcedOrder = [];
  6764. this.morphTargetInfluences = [];
  6765. this.morphTargetDictionary = {};
  6766. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6767. this.morphTargetInfluences.push( 0 );
  6768. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6769. }
  6770. }
  6771. }
  6772. }
  6773. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6774. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  6775. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6776. return this.morphTargetDictionary[ name ];
  6777. }
  6778. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6779. return 0;
  6780. };
  6781. THREE.Mesh.prototype.clone = function ( object ) {
  6782. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  6783. THREE.Object3D.prototype.clone.call( this, object );
  6784. return object;
  6785. };
  6786. /**
  6787. * @author mikael emtinger / http://gomo.se/
  6788. * @author alteredq / http://alteredqualia.com/
  6789. */
  6790. THREE.Bone = function( belongsToSkin ) {
  6791. THREE.Object3D.call( this );
  6792. this.skin = belongsToSkin;
  6793. this.skinMatrix = new THREE.Matrix4();
  6794. };
  6795. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6796. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6797. // update local
  6798. if ( this.matrixAutoUpdate ) {
  6799. forceUpdate |= this.updateMatrix();
  6800. }
  6801. // update skin matrix
  6802. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6803. if( parentSkinMatrix ) {
  6804. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6805. } else {
  6806. this.skinMatrix.copy( this.matrix );
  6807. }
  6808. this.matrixWorldNeedsUpdate = false;
  6809. forceUpdate = true;
  6810. }
  6811. // update children
  6812. var child, i, l = this.children.length;
  6813. for ( i = 0; i < l; i ++ ) {
  6814. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6815. }
  6816. };
  6817. /**
  6818. * @author mikael emtinger / http://gomo.se/
  6819. * @author alteredq / http://alteredqualia.com/
  6820. */
  6821. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6822. THREE.Mesh.call( this, geometry, material );
  6823. //
  6824. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6825. // init bones
  6826. this.identityMatrix = new THREE.Matrix4();
  6827. this.bones = [];
  6828. this.boneMatrices = [];
  6829. var b, bone, gbone, p, q, s;
  6830. if ( this.geometry && this.geometry.bones !== undefined ) {
  6831. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6832. gbone = this.geometry.bones[ b ];
  6833. p = gbone.pos;
  6834. q = gbone.rotq;
  6835. s = gbone.scl;
  6836. bone = this.addBone();
  6837. bone.name = gbone.name;
  6838. bone.position.set( p[0], p[1], p[2] );
  6839. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6840. bone.useQuaternion = true;
  6841. if ( s !== undefined ) {
  6842. bone.scale.set( s[0], s[1], s[2] );
  6843. } else {
  6844. bone.scale.set( 1, 1, 1 );
  6845. }
  6846. }
  6847. for ( b = 0; b < this.bones.length; b ++ ) {
  6848. gbone = this.geometry.bones[ b ];
  6849. bone = this.bones[ b ];
  6850. if ( gbone.parent === -1 ) {
  6851. this.add( bone );
  6852. } else {
  6853. this.bones[ gbone.parent ].add( bone );
  6854. }
  6855. }
  6856. //
  6857. var nBones = this.bones.length;
  6858. if ( this.useVertexTexture ) {
  6859. // layout (1 matrix = 4 pixels)
  6860. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6861. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6862. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6863. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6864. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6865. var size;
  6866. if ( nBones > 256 )
  6867. size = 64;
  6868. else if ( nBones > 64 )
  6869. size = 32;
  6870. else if ( nBones > 16 )
  6871. size = 16;
  6872. else
  6873. size = 8;
  6874. this.boneTextureWidth = size;
  6875. this.boneTextureHeight = size;
  6876. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6877. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6878. this.boneTexture.minFilter = THREE.NearestFilter;
  6879. this.boneTexture.magFilter = THREE.NearestFilter;
  6880. this.boneTexture.generateMipmaps = false;
  6881. this.boneTexture.flipY = false;
  6882. } else {
  6883. this.boneMatrices = new Float32Array( 16 * nBones );
  6884. }
  6885. this.pose();
  6886. }
  6887. };
  6888. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6889. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6890. if ( bone === undefined ) {
  6891. bone = new THREE.Bone( this );
  6892. }
  6893. this.bones.push( bone );
  6894. return bone;
  6895. };
  6896. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6897. this.matrixAutoUpdate && this.updateMatrix();
  6898. // update matrixWorld
  6899. if ( this.matrixWorldNeedsUpdate || force ) {
  6900. if ( this.parent ) {
  6901. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6902. } else {
  6903. this.matrixWorld.copy( this.matrix );
  6904. }
  6905. this.matrixWorldNeedsUpdate = false;
  6906. force = true;
  6907. }
  6908. // update children
  6909. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6910. var child = this.children[ i ];
  6911. if ( child instanceof THREE.Bone ) {
  6912. child.update( this.identityMatrix, false );
  6913. } else {
  6914. child.updateMatrixWorld( true );
  6915. }
  6916. }
  6917. // make a snapshot of the bones' rest position
  6918. if ( this.boneInverses == undefined ) {
  6919. this.boneInverses = [];
  6920. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6921. var inverse = new THREE.Matrix4();
  6922. inverse.getInverse( this.bones[ b ].skinMatrix );
  6923. this.boneInverses.push( inverse );
  6924. }
  6925. }
  6926. // flatten bone matrices to array
  6927. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6928. // compute the offset between the current and the original transform;
  6929. //TODO: we could get rid of this multiplication step if the skinMatrix
  6930. // was already representing the offset; however, this requires some
  6931. // major changes to the animation system
  6932. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6933. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6934. }
  6935. if ( this.useVertexTexture ) {
  6936. this.boneTexture.needsUpdate = true;
  6937. }
  6938. };
  6939. THREE.SkinnedMesh.prototype.pose = function() {
  6940. this.updateMatrixWorld( true );
  6941. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6942. // normalize weights
  6943. var sw = this.geometry.skinWeights[ i ];
  6944. var scale = 1.0 / sw.lengthManhattan();
  6945. if ( scale !== Infinity ) {
  6946. sw.multiplyScalar( scale );
  6947. } else {
  6948. sw.set( 1 ); // this will be normalized by the shader anyway
  6949. }
  6950. }
  6951. };
  6952. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  6953. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  6954. THREE.Mesh.prototype.clone.call( this, object );
  6955. return object;
  6956. };
  6957. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6958. /**
  6959. * @author alteredq / http://alteredqualia.com/
  6960. */
  6961. THREE.MorphAnimMesh = function ( geometry, material ) {
  6962. THREE.Mesh.call( this, geometry, material );
  6963. // API
  6964. this.duration = 1000; // milliseconds
  6965. this.mirroredLoop = false;
  6966. this.time = 0;
  6967. // internals
  6968. this.lastKeyframe = 0;
  6969. this.currentKeyframe = 0;
  6970. this.direction = 1;
  6971. this.directionBackwards = false;
  6972. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6973. };
  6974. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6975. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6976. this.startKeyframe = start;
  6977. this.endKeyframe = end;
  6978. this.length = this.endKeyframe - this.startKeyframe + 1;
  6979. };
  6980. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6981. this.direction = 1;
  6982. this.directionBackwards = false;
  6983. };
  6984. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6985. this.direction = -1;
  6986. this.directionBackwards = true;
  6987. };
  6988. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6989. var geometry = this.geometry;
  6990. if ( ! geometry.animations ) geometry.animations = {};
  6991. var firstAnimation, animations = geometry.animations;
  6992. var pattern = /([a-z]+)(\d+)/;
  6993. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6994. var morph = geometry.morphTargets[ i ];
  6995. var parts = morph.name.match( pattern );
  6996. if ( parts && parts.length > 1 ) {
  6997. var label = parts[ 1 ];
  6998. var num = parts[ 2 ];
  6999. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7000. var animation = animations[ label ];
  7001. if ( i < animation.start ) animation.start = i;
  7002. if ( i > animation.end ) animation.end = i;
  7003. if ( ! firstAnimation ) firstAnimation = label;
  7004. }
  7005. }
  7006. geometry.firstAnimation = firstAnimation;
  7007. };
  7008. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7009. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7010. this.geometry.animations[ label ] = { start: start, end: end };
  7011. };
  7012. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7013. var animation = this.geometry.animations[ label ];
  7014. if ( animation ) {
  7015. this.setFrameRange( animation.start, animation.end );
  7016. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7017. this.time = 0;
  7018. } else {
  7019. console.warn( "animation[" + label + "] undefined" );
  7020. }
  7021. };
  7022. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7023. var frameTime = this.duration / this.length;
  7024. this.time += this.direction * delta;
  7025. if ( this.mirroredLoop ) {
  7026. if ( this.time > this.duration || this.time < 0 ) {
  7027. this.direction *= -1;
  7028. if ( this.time > this.duration ) {
  7029. this.time = this.duration;
  7030. this.directionBackwards = true;
  7031. }
  7032. if ( this.time < 0 ) {
  7033. this.time = 0;
  7034. this.directionBackwards = false;
  7035. }
  7036. }
  7037. } else {
  7038. this.time = this.time % this.duration;
  7039. if ( this.time < 0 ) this.time += this.duration;
  7040. }
  7041. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7042. if ( keyframe !== this.currentKeyframe ) {
  7043. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7044. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7045. this.morphTargetInfluences[ keyframe ] = 0;
  7046. this.lastKeyframe = this.currentKeyframe;
  7047. this.currentKeyframe = keyframe;
  7048. }
  7049. var mix = ( this.time % frameTime ) / frameTime;
  7050. if ( this.directionBackwards ) {
  7051. mix = 1 - mix;
  7052. }
  7053. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7054. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7055. };
  7056. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7057. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7058. object.duration = this.duration;
  7059. object.mirroredLoop = this.mirroredLoop;
  7060. object.time = this.time;
  7061. object.lastKeyframe = this.lastKeyframe;
  7062. object.currentKeyframe = this.currentKeyframe;
  7063. object.direction = this.direction;
  7064. object.directionBackwards = this.directionBackwards;
  7065. THREE.Mesh.prototype.clone.call( this, object );
  7066. return object;
  7067. };
  7068. /**
  7069. * @author alteredq / http://alteredqualia.com/
  7070. */
  7071. THREE.Ribbon = function ( geometry, material ) {
  7072. THREE.Object3D.call( this );
  7073. this.geometry = geometry;
  7074. this.material = material;
  7075. };
  7076. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7077. THREE.Ribbon.prototype.clone = function ( object ) {
  7078. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7079. THREE.Object3D.prototype.clone.call( this, object );
  7080. return object;
  7081. };
  7082. /**
  7083. * @author mikael emtinger / http://gomo.se/
  7084. * @author alteredq / http://alteredqualia.com/
  7085. * @author mrdoob / http://mrdoob.com/
  7086. */
  7087. THREE.LOD = function () {
  7088. THREE.Object3D.call( this );
  7089. this.LODs = [];
  7090. };
  7091. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7092. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7093. if ( visibleAtDistance === undefined ) {
  7094. visibleAtDistance = 0;
  7095. }
  7096. visibleAtDistance = Math.abs( visibleAtDistance );
  7097. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7098. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7099. break;
  7100. }
  7101. }
  7102. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7103. this.add( object3D );
  7104. };
  7105. THREE.LOD.prototype.update = function ( camera ) {
  7106. if ( this.LODs.length > 1 ) {
  7107. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7108. var inverse = camera.matrixWorldInverse;
  7109. var distance = -( inverse.elements[2] * this.matrixWorld.elements[12] + inverse.elements[6] * this.matrixWorld.elements[13] + inverse.elements[10] * this.matrixWorld.elements[14] + inverse.elements[14] );
  7110. this.LODs[ 0 ].object3D.visible = true;
  7111. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7112. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7113. this.LODs[ l - 1 ].object3D.visible = false;
  7114. this.LODs[ l ].object3D.visible = true;
  7115. } else {
  7116. break;
  7117. }
  7118. }
  7119. for( ; l < this.LODs.length; l ++ ) {
  7120. this.LODs[ l ].object3D.visible = false;
  7121. }
  7122. }
  7123. };
  7124. THREE.LOD.prototype.clone = function () {
  7125. // TODO
  7126. };
  7127. /**
  7128. * @author mikael emtinger / http://gomo.se/
  7129. * @author alteredq / http://alteredqualia.com/
  7130. */
  7131. THREE.Sprite = function ( material ) {
  7132. THREE.Object3D.call( this );
  7133. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7134. this.rotation3d = this.rotation;
  7135. this.rotation = 0;
  7136. };
  7137. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7138. /*
  7139. * Custom update matrix
  7140. */
  7141. THREE.Sprite.prototype.updateMatrix = function () {
  7142. this.matrix.setPosition( this.position );
  7143. this.rotation3d.set( 0, 0, this.rotation );
  7144. this.matrix.setRotationFromEuler( this.rotation3d );
  7145. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7146. this.matrix.scale( this.scale );
  7147. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7148. }
  7149. this.matrixWorldNeedsUpdate = true;
  7150. };
  7151. THREE.Sprite.prototype.clone = function ( object ) {
  7152. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7153. THREE.Object3D.prototype.clone.call( this, object );
  7154. return object;
  7155. };
  7156. /**
  7157. * @author mrdoob / http://mrdoob.com/
  7158. */
  7159. THREE.Scene = function () {
  7160. THREE.Object3D.call( this );
  7161. this.fog = null;
  7162. this.overrideMaterial = null;
  7163. this.matrixAutoUpdate = false;
  7164. this.__objects = [];
  7165. this.__lights = [];
  7166. this.__objectsAdded = [];
  7167. this.__objectsRemoved = [];
  7168. };
  7169. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7170. THREE.Scene.prototype.__addObject = function ( object ) {
  7171. if ( object instanceof THREE.Light ) {
  7172. if ( this.__lights.indexOf( object ) === - 1 ) {
  7173. this.__lights.push( object );
  7174. }
  7175. if ( object.target && object.target.parent === undefined ) {
  7176. this.add( object.target );
  7177. }
  7178. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7179. if ( this.__objects.indexOf( object ) === - 1 ) {
  7180. this.__objects.push( object );
  7181. this.__objectsAdded.push( object );
  7182. // check if previously removed
  7183. var i = this.__objectsRemoved.indexOf( object );
  7184. if ( i !== -1 ) {
  7185. this.__objectsRemoved.splice( i, 1 );
  7186. }
  7187. }
  7188. }
  7189. for ( var c = 0; c < object.children.length; c ++ ) {
  7190. this.__addObject( object.children[ c ] );
  7191. }
  7192. };
  7193. THREE.Scene.prototype.__removeObject = function ( object ) {
  7194. if ( object instanceof THREE.Light ) {
  7195. var i = this.__lights.indexOf( object );
  7196. if ( i !== -1 ) {
  7197. this.__lights.splice( i, 1 );
  7198. }
  7199. } else if ( !( object instanceof THREE.Camera ) ) {
  7200. var i = this.__objects.indexOf( object );
  7201. if( i !== -1 ) {
  7202. this.__objects.splice( i, 1 );
  7203. this.__objectsRemoved.push( object );
  7204. // check if previously added
  7205. var ai = this.__objectsAdded.indexOf( object );
  7206. if ( ai !== -1 ) {
  7207. this.__objectsAdded.splice( ai, 1 );
  7208. }
  7209. }
  7210. }
  7211. for ( var c = 0; c < object.children.length; c ++ ) {
  7212. this.__removeObject( object.children[ c ] );
  7213. }
  7214. };
  7215. /**
  7216. * @author mrdoob / http://mrdoob.com/
  7217. * @author alteredq / http://alteredqualia.com/
  7218. */
  7219. THREE.Fog = function ( hex, near, far ) {
  7220. this.name = '';
  7221. this.color = new THREE.Color( hex );
  7222. this.near = ( near !== undefined ) ? near : 1;
  7223. this.far = ( far !== undefined ) ? far : 1000;
  7224. };
  7225. THREE.Fog.prototype.clone = function () {
  7226. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7227. };
  7228. /**
  7229. * @author mrdoob / http://mrdoob.com/
  7230. * @author alteredq / http://alteredqualia.com/
  7231. */
  7232. THREE.FogExp2 = function ( hex, density ) {
  7233. this.name = '';
  7234. this.color = new THREE.Color( hex );
  7235. this.density = ( density !== undefined ) ? density : 0.00025;
  7236. };
  7237. THREE.FogExp2.prototype.clone = function () {
  7238. return new THREE.FogExp2( this.color.getHex(), this.density );
  7239. };
  7240. /**
  7241. * @author mrdoob / http://mrdoob.com/
  7242. */
  7243. THREE.CanvasRenderer = function ( parameters ) {
  7244. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7245. parameters = parameters || {};
  7246. var _this = this,
  7247. _renderData, _elements, _lights,
  7248. _projector = new THREE.Projector(),
  7249. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7250. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7251. _context = _canvas.getContext( '2d' ),
  7252. _clearColor = new THREE.Color( 0x000000 ),
  7253. _clearOpacity = 0,
  7254. _contextGlobalAlpha = 1,
  7255. _contextGlobalCompositeOperation = 0,
  7256. _contextStrokeStyle = null,
  7257. _contextFillStyle = null,
  7258. _contextLineWidth = null,
  7259. _contextLineCap = null,
  7260. _contextLineJoin = null,
  7261. _v1, _v2, _v3, _v4,
  7262. _v5 = new THREE.RenderableVertex(),
  7263. _v6 = new THREE.RenderableVertex(),
  7264. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7265. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7266. _color = new THREE.Color(),
  7267. _color1 = new THREE.Color(),
  7268. _color2 = new THREE.Color(),
  7269. _color3 = new THREE.Color(),
  7270. _color4 = new THREE.Color(),
  7271. _diffuseColor = new THREE.Color(),
  7272. _emissiveColor = new THREE.Color(),
  7273. _patterns = {}, _imagedatas = {},
  7274. _near, _far,
  7275. _image, _uvs,
  7276. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7277. _clipRect = new THREE.Rectangle(),
  7278. _clearRect = new THREE.Rectangle(),
  7279. _bboxRect = new THREE.Rectangle(),
  7280. _enableLighting = false,
  7281. _ambientLight = new THREE.Color(),
  7282. _directionalLights = new THREE.Color(),
  7283. _pointLights = new THREE.Color(),
  7284. _pi2 = Math.PI * 2,
  7285. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7286. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7287. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7288. _pixelMap = document.createElement( 'canvas' );
  7289. _pixelMap.width = _pixelMap.height = 2;
  7290. _pixelMapContext = _pixelMap.getContext( '2d' );
  7291. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7292. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7293. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7294. _pixelMapData = _pixelMapImage.data;
  7295. _gradientMap = document.createElement( 'canvas' );
  7296. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7297. _gradientMapContext = _gradientMap.getContext( '2d' );
  7298. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7299. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7300. _gradientMapQuality --; // Fix UVs
  7301. this.domElement = _canvas;
  7302. this.autoClear = true;
  7303. this.sortObjects = true;
  7304. this.sortElements = true;
  7305. this.info = {
  7306. render: {
  7307. vertices: 0,
  7308. faces: 0
  7309. }
  7310. }
  7311. this.setSize = function ( width, height ) {
  7312. _canvasWidth = width;
  7313. _canvasHeight = height;
  7314. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7315. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7316. _canvas.width = _canvasWidth;
  7317. _canvas.height = _canvasHeight;
  7318. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7319. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7320. _contextGlobalAlpha = 1;
  7321. _contextGlobalCompositeOperation = 0;
  7322. _contextStrokeStyle = null;
  7323. _contextFillStyle = null;
  7324. _contextLineWidth = null;
  7325. _contextLineCap = null;
  7326. _contextLineJoin = null;
  7327. };
  7328. this.setClearColor = function ( color, opacity ) {
  7329. _clearColor.copy( color );
  7330. _clearOpacity = opacity !== undefined ? opacity : 1;
  7331. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7332. };
  7333. this.setClearColorHex = function ( hex, opacity ) {
  7334. _clearColor.setHex( hex );
  7335. _clearOpacity = opacity !== undefined ? opacity : 1;
  7336. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7337. };
  7338. this.getMaxAnisotropy = function () {
  7339. return 0;
  7340. };
  7341. this.clear = function () {
  7342. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7343. if ( _clearRect.isEmpty() === false ) {
  7344. _clearRect.minSelf( _clipRect );
  7345. _clearRect.inflate( 2 );
  7346. if ( _clearOpacity < 1 ) {
  7347. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7348. }
  7349. if ( _clearOpacity > 0 ) {
  7350. setBlending( THREE.NormalBlending );
  7351. setOpacity( 1 );
  7352. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7353. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7354. }
  7355. _clearRect.empty();
  7356. }
  7357. };
  7358. this.render = function ( scene, camera ) {
  7359. if ( camera instanceof THREE.Camera === false ) {
  7360. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7361. return;
  7362. }
  7363. var e, el, element, material;
  7364. this.autoClear === true
  7365. ? this.clear()
  7366. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7367. _this.info.render.vertices = 0;
  7368. _this.info.render.faces = 0;
  7369. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7370. _elements = _renderData.elements;
  7371. _lights = _renderData.lights;
  7372. /* DEBUG
  7373. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7374. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7375. */
  7376. _enableLighting = _lights.length > 0;
  7377. if ( _enableLighting === true ) {
  7378. calculateLights();
  7379. }
  7380. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7381. element = _elements[ e ];
  7382. material = element.material;
  7383. if ( material === undefined || material.visible === false ) continue;
  7384. _bboxRect.empty();
  7385. if ( element instanceof THREE.RenderableParticle ) {
  7386. _v1 = element;
  7387. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7388. renderParticle( _v1, element, material, scene );
  7389. } else if ( element instanceof THREE.RenderableLine ) {
  7390. _v1 = element.v1; _v2 = element.v2;
  7391. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7392. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7393. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7394. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7395. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7396. renderLine( _v1, _v2, element, material, scene );
  7397. }
  7398. } else if ( element instanceof THREE.RenderableFace3 ) {
  7399. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7400. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7401. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7402. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7403. if ( material.overdraw === true ) {
  7404. expand( _v1.positionScreen, _v2.positionScreen );
  7405. expand( _v2.positionScreen, _v3.positionScreen );
  7406. expand( _v3.positionScreen, _v1.positionScreen );
  7407. }
  7408. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7409. _v2.positionScreen.x, _v2.positionScreen.y,
  7410. _v3.positionScreen.x, _v3.positionScreen.y );
  7411. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7412. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7413. }
  7414. } else if ( element instanceof THREE.RenderableFace4 ) {
  7415. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7416. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7417. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7418. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7419. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7420. _v5.positionScreen.copy( _v2.positionScreen );
  7421. _v6.positionScreen.copy( _v4.positionScreen );
  7422. if ( material.overdraw === true ) {
  7423. expand( _v1.positionScreen, _v2.positionScreen );
  7424. expand( _v2.positionScreen, _v4.positionScreen );
  7425. expand( _v4.positionScreen, _v1.positionScreen );
  7426. expand( _v3.positionScreen, _v5.positionScreen );
  7427. expand( _v3.positionScreen, _v6.positionScreen );
  7428. }
  7429. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7430. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7431. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7432. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7433. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7434. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7435. }
  7436. }
  7437. /* DEBUG
  7438. _context.lineWidth = 1;
  7439. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7440. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7441. */
  7442. _clearRect.addRectangle( _bboxRect );
  7443. }
  7444. /* DEBUG
  7445. _context.lineWidth = 1;
  7446. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7447. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7448. */
  7449. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7450. //
  7451. function calculateLights() {
  7452. _ambientLight.setRGB( 0, 0, 0 );
  7453. _directionalLights.setRGB( 0, 0, 0 );
  7454. _pointLights.setRGB( 0, 0, 0 );
  7455. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7456. var light = _lights[ l ];
  7457. var lightColor = light.color;
  7458. if ( light instanceof THREE.AmbientLight ) {
  7459. _ambientLight.r += lightColor.r;
  7460. _ambientLight.g += lightColor.g;
  7461. _ambientLight.b += lightColor.b;
  7462. } else if ( light instanceof THREE.DirectionalLight ) {
  7463. // for particles
  7464. _directionalLights.r += lightColor.r;
  7465. _directionalLights.g += lightColor.g;
  7466. _directionalLights.b += lightColor.b;
  7467. } else if ( light instanceof THREE.PointLight ) {
  7468. // for particles
  7469. _pointLights.r += lightColor.r;
  7470. _pointLights.g += lightColor.g;
  7471. _pointLights.b += lightColor.b;
  7472. }
  7473. }
  7474. }
  7475. function calculateLight( position, normal, color ) {
  7476. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7477. var light = _lights[ l ];
  7478. var lightColor = light.color;
  7479. if ( light instanceof THREE.DirectionalLight ) {
  7480. var lightPosition = light.matrixWorld.getPosition().normalize();
  7481. var amount = normal.dot( lightPosition );
  7482. if ( amount <= 0 ) continue;
  7483. amount *= light.intensity;
  7484. color.r += lightColor.r * amount;
  7485. color.g += lightColor.g * amount;
  7486. color.b += lightColor.b * amount;
  7487. } else if ( light instanceof THREE.PointLight ) {
  7488. var lightPosition = light.matrixWorld.getPosition();
  7489. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7490. if ( amount <= 0 ) continue;
  7491. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7492. if ( amount == 0 ) continue;
  7493. amount *= light.intensity;
  7494. color.r += lightColor.r * amount;
  7495. color.g += lightColor.g * amount;
  7496. color.b += lightColor.b * amount;
  7497. }
  7498. }
  7499. }
  7500. function renderParticle( v1, element, material, scene ) {
  7501. setOpacity( material.opacity );
  7502. setBlending( material.blending );
  7503. var width, height, scaleX, scaleY,
  7504. bitmap, bitmapWidth, bitmapHeight;
  7505. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7506. if ( material.map === null ) {
  7507. scaleX = element.object.scale.x;
  7508. scaleY = element.object.scale.y;
  7509. // TODO: Be able to disable this
  7510. scaleX *= element.scale.x * _canvasWidthHalf;
  7511. scaleY *= element.scale.y * _canvasHeightHalf;
  7512. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7513. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7514. return;
  7515. }
  7516. setFillStyle( material.color.getContextStyle() );
  7517. _context.save();
  7518. _context.translate( v1.x, v1.y );
  7519. _context.rotate( - element.rotation );
  7520. _context.scale( scaleX, scaleY );
  7521. _context.fillRect( -1, -1, 2, 2 );
  7522. _context.restore();
  7523. } else {
  7524. bitmap = material.map.image;
  7525. bitmapWidth = bitmap.width >> 1;
  7526. bitmapHeight = bitmap.height >> 1;
  7527. scaleX = element.scale.x * _canvasWidthHalf;
  7528. scaleY = element.scale.y * _canvasHeightHalf;
  7529. width = scaleX * bitmapWidth;
  7530. height = scaleY * bitmapHeight;
  7531. // TODO: Rotations break this...
  7532. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7533. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7534. return;
  7535. }
  7536. _context.save();
  7537. _context.translate( v1.x, v1.y );
  7538. _context.rotate( - element.rotation );
  7539. _context.scale( scaleX, - scaleY );
  7540. _context.translate( - bitmapWidth, - bitmapHeight );
  7541. _context.drawImage( bitmap, 0, 0 );
  7542. _context.restore();
  7543. }
  7544. /* DEBUG
  7545. setStrokeStyle( 'rgb(255,255,0)' );
  7546. _context.beginPath();
  7547. _context.moveTo( v1.x - 10, v1.y );
  7548. _context.lineTo( v1.x + 10, v1.y );
  7549. _context.moveTo( v1.x, v1.y - 10 );
  7550. _context.lineTo( v1.x, v1.y + 10 );
  7551. _context.stroke();
  7552. */
  7553. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7554. width = element.scale.x * _canvasWidthHalf;
  7555. height = element.scale.y * _canvasHeightHalf;
  7556. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7557. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7558. return;
  7559. }
  7560. setStrokeStyle( material.color.getContextStyle() );
  7561. setFillStyle( material.color.getContextStyle() );
  7562. _context.save();
  7563. _context.translate( v1.x, v1.y );
  7564. _context.rotate( - element.rotation );
  7565. _context.scale( width, height );
  7566. material.program( _context );
  7567. _context.restore();
  7568. }
  7569. }
  7570. function renderLine( v1, v2, element, material, scene ) {
  7571. setOpacity( material.opacity );
  7572. setBlending( material.blending );
  7573. _context.beginPath();
  7574. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7575. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7576. if ( material instanceof THREE.LineBasicMaterial ) {
  7577. setLineWidth( material.linewidth );
  7578. setLineCap( material.linecap );
  7579. setLineJoin( material.linejoin );
  7580. setStrokeStyle( material.color.getContextStyle() );
  7581. _context.stroke();
  7582. _bboxRect.inflate( material.linewidth * 2 );
  7583. }
  7584. }
  7585. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7586. _this.info.render.vertices += 3;
  7587. _this.info.render.faces ++;
  7588. setOpacity( material.opacity );
  7589. setBlending( material.blending );
  7590. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7591. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7592. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7593. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7594. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  7595. _diffuseColor.copy( material.color );
  7596. _emissiveColor.copy( material.emissive );
  7597. if ( material.vertexColors === THREE.FaceColors ) {
  7598. _diffuseColor.r *= element.color.r;
  7599. _diffuseColor.g *= element.color.g;
  7600. _diffuseColor.b *= element.color.b;
  7601. }
  7602. if ( _enableLighting === true ) {
  7603. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7604. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7605. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7606. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7607. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7608. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7609. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7610. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7611. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7612. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7613. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7614. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7615. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7616. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7617. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7618. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7619. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7620. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7621. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7622. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7623. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7624. } else {
  7625. _color.r = _ambientLight.r;
  7626. _color.g = _ambientLight.g;
  7627. _color.b = _ambientLight.b;
  7628. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7629. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7630. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7631. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7632. material.wireframe === true
  7633. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7634. : fillPath( _color );
  7635. }
  7636. } else {
  7637. material.wireframe === true
  7638. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7639. : fillPath( material.color );
  7640. }
  7641. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7642. if ( material.map !== null ) {
  7643. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7644. _uvs = element.uvs[ 0 ];
  7645. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uvs[ uv1 ].u, _uvs[ uv1 ].v, _uvs[ uv2 ].u, _uvs[ uv2 ].v, _uvs[ uv3 ].u, _uvs[ uv3 ].v, material.map );
  7646. }
  7647. } else if ( material.envMap !== null ) {
  7648. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7649. var cameraMatrix = camera.matrixWorldInverse;
  7650. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7651. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7652. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7653. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7654. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7655. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7656. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7657. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7658. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7659. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7660. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7661. }*/
  7662. } else {
  7663. _color.copy( material.color );
  7664. if ( material.vertexColors === THREE.FaceColors ) {
  7665. _color.r *= element.color.r;
  7666. _color.g *= element.color.g;
  7667. _color.b *= element.color.b;
  7668. }
  7669. material.wireframe === true
  7670. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7671. : fillPath( _color );
  7672. }
  7673. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7674. _near = camera.near;
  7675. _far = camera.far;
  7676. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7677. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7678. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7679. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7680. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7681. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7682. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7683. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7684. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7685. _color.r = normalToComponent( element.normalWorld.x );
  7686. _color.g = normalToComponent( element.normalWorld.y );
  7687. _color.b = normalToComponent( element.normalWorld.z );
  7688. material.wireframe === true
  7689. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7690. : fillPath( _color );
  7691. }
  7692. }
  7693. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7694. _this.info.render.vertices += 4;
  7695. _this.info.render.faces ++;
  7696. setOpacity( material.opacity );
  7697. setBlending( material.blending );
  7698. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7699. // Let renderFace3() handle this
  7700. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7701. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7702. return;
  7703. }
  7704. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7705. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7706. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7707. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7708. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7709. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7710. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7711. _diffuseColor.copy( material.color );
  7712. _emissiveColor.copy( material.emissive );
  7713. if ( material.vertexColors === THREE.FaceColors ) {
  7714. _diffuseColor.r *= element.color.r;
  7715. _diffuseColor.g *= element.color.g;
  7716. _diffuseColor.b *= element.color.b;
  7717. }
  7718. if ( _enableLighting === true ) {
  7719. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7720. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7721. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7722. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7723. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7724. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7725. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7726. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7727. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7728. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7729. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7730. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7731. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7732. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7733. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7734. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7735. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7736. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  7737. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  7738. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  7739. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7740. // TODO: UVs are incorrect, v4->v3?
  7741. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7742. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7743. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7744. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7745. } else {
  7746. _color.r = _ambientLight.r;
  7747. _color.g = _ambientLight.g;
  7748. _color.b = _ambientLight.b;
  7749. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7750. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7751. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7752. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7753. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7754. material.wireframe === true
  7755. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7756. : fillPath( _color );
  7757. }
  7758. } else {
  7759. _color.r = _diffuseColor.r + _emissiveColor.r;
  7760. _color.g = _diffuseColor.g + _emissiveColor.g;
  7761. _color.b = _diffuseColor.b + _emissiveColor.b;
  7762. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7763. material.wireframe === true
  7764. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7765. : fillPath( _color );
  7766. }
  7767. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  7768. _color.copy( material.color );
  7769. if ( material.vertexColors === THREE.FaceColors ) {
  7770. _color.r *= element.color.r;
  7771. _color.g *= element.color.g;
  7772. _color.b *= element.color.b;
  7773. }
  7774. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7775. material.wireframe === true
  7776. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7777. : fillPath( _color );
  7778. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7779. _color.r = normalToComponent( element.normalWorld.x );
  7780. _color.g = normalToComponent( element.normalWorld.y );
  7781. _color.b = normalToComponent( element.normalWorld.z );
  7782. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7783. material.wireframe === true
  7784. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7785. : fillPath( _color );
  7786. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7787. _near = camera.near;
  7788. _far = camera.far;
  7789. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7790. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7791. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7792. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7793. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7794. // TODO: UVs are incorrect, v4->v3?
  7795. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7796. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7797. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7798. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7799. }
  7800. }
  7801. //
  7802. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7803. _context.beginPath();
  7804. _context.moveTo( x0, y0 );
  7805. _context.lineTo( x1, y1 );
  7806. _context.lineTo( x2, y2 );
  7807. _context.closePath();
  7808. }
  7809. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7810. _context.beginPath();
  7811. _context.moveTo( x0, y0 );
  7812. _context.lineTo( x1, y1 );
  7813. _context.lineTo( x2, y2 );
  7814. _context.lineTo( x3, y3 );
  7815. _context.closePath();
  7816. }
  7817. function strokePath( color, linewidth, linecap, linejoin ) {
  7818. setLineWidth( linewidth );
  7819. setLineCap( linecap );
  7820. setLineJoin( linejoin );
  7821. setStrokeStyle( color.getContextStyle() );
  7822. _context.stroke();
  7823. _bboxRect.inflate( linewidth * 2 );
  7824. }
  7825. function fillPath( color ) {
  7826. setFillStyle( color.getContextStyle() );
  7827. _context.fill();
  7828. }
  7829. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7830. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  7831. if ( texture.needsUpdate === true ) {
  7832. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7833. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7834. _patterns[ texture.id ] = _context.createPattern(
  7835. texture.image, repeatX === true && repeatY === true
  7836. ? 'repeat'
  7837. : repeatX === true && repeatY === false
  7838. ? 'repeat-x'
  7839. : repeatX === false && repeatY === true
  7840. ? 'repeat-y'
  7841. : 'no-repeat'
  7842. );
  7843. texture.needsUpdate = false;
  7844. }
  7845. _patterns[ texture.id ] === undefined
  7846. ? setFillStyle( 'rgba(0,0,0,1)' )
  7847. : setFillStyle( _patterns[ texture.id ] );
  7848. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7849. var a, b, c, d, e, f, det, idet,
  7850. offsetX = texture.offset.x / texture.repeat.x,
  7851. offsetY = texture.offset.y / texture.repeat.y,
  7852. width = texture.image.width * texture.repeat.x,
  7853. height = texture.image.height * texture.repeat.y;
  7854. u0 = ( u0 + offsetX ) * width;
  7855. v0 = ( 1.0 - v0 + offsetY ) * height;
  7856. u1 = ( u1 + offsetX ) * width;
  7857. v1 = ( 1.0 - v1 + offsetY ) * height;
  7858. u2 = ( u2 + offsetX ) * width;
  7859. v2 = ( 1.0 - v2 + offsetY ) * height;
  7860. x1 -= x0; y1 -= y0;
  7861. x2 -= x0; y2 -= y0;
  7862. u1 -= u0; v1 -= v0;
  7863. u2 -= u0; v2 -= v0;
  7864. det = u1 * v2 - u2 * v1;
  7865. if ( det === 0 ) {
  7866. if ( _imagedatas[ texture.id ] === undefined ) {
  7867. var canvas = document.createElement( 'canvas' )
  7868. canvas.width = texture.image.width;
  7869. canvas.height = texture.image.height;
  7870. var context = canvas.getContext( '2d' );
  7871. context.drawImage( texture.image, 0, 0 );
  7872. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7873. }
  7874. var data = _imagedatas[ texture.id ];
  7875. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7876. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7877. fillPath( _color );
  7878. return;
  7879. }
  7880. idet = 1 / det;
  7881. a = ( v2 * x1 - v1 * x2 ) * idet;
  7882. b = ( v2 * y1 - v1 * y2 ) * idet;
  7883. c = ( u1 * x2 - u2 * x1 ) * idet;
  7884. d = ( u1 * y2 - u2 * y1 ) * idet;
  7885. e = x0 - a * u0 - c * v0;
  7886. f = y0 - b * u0 - d * v0;
  7887. _context.save();
  7888. _context.transform( a, b, c, d, e, f );
  7889. _context.fill();
  7890. _context.restore();
  7891. }
  7892. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7893. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7894. var a, b, c, d, e, f, det, idet,
  7895. width = image.width - 1,
  7896. height = image.height - 1;
  7897. u0 *= width; v0 *= height;
  7898. u1 *= width; v1 *= height;
  7899. u2 *= width; v2 *= height;
  7900. x1 -= x0; y1 -= y0;
  7901. x2 -= x0; y2 -= y0;
  7902. u1 -= u0; v1 -= v0;
  7903. u2 -= u0; v2 -= v0;
  7904. det = u1 * v2 - u2 * v1;
  7905. idet = 1 / det;
  7906. a = ( v2 * x1 - v1 * x2 ) * idet;
  7907. b = ( v2 * y1 - v1 * y2 ) * idet;
  7908. c = ( u1 * x2 - u2 * x1 ) * idet;
  7909. d = ( u1 * y2 - u2 * y1 ) * idet;
  7910. e = x0 - a * u0 - c * v0;
  7911. f = y0 - b * u0 - d * v0;
  7912. _context.save();
  7913. _context.transform( a, b, c, d, e, f );
  7914. _context.clip();
  7915. _context.drawImage( image, 0, 0 );
  7916. _context.restore();
  7917. }
  7918. function getGradientTexture( color1, color2, color3, color4 ) {
  7919. // http://mrdoob.com/blog/post/710
  7920. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  7921. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  7922. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  7923. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  7924. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  7925. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  7926. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  7927. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  7928. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  7929. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  7930. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  7931. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  7932. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7933. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7934. return _gradientMap;
  7935. }
  7936. function smoothstep( value, min, max ) {
  7937. var x = ( value - min ) / ( max - min );
  7938. return x * x * ( 3 - 2 * x );
  7939. }
  7940. function normalToComponent( normal ) {
  7941. var component = ( normal + 1 ) * 0.5;
  7942. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7943. }
  7944. // Hide anti-alias gaps
  7945. function expand( v1, v2 ) {
  7946. var x = v2.x - v1.x, y = v2.y - v1.y,
  7947. det = x * x + y * y, idet;
  7948. if ( det === 0 ) return;
  7949. idet = 1 / Math.sqrt( det );
  7950. x *= idet; y *= idet;
  7951. v2.x += x; v2.y += y;
  7952. v1.x -= x; v1.y -= y;
  7953. }
  7954. };
  7955. // Context cached methods.
  7956. function setOpacity( value ) {
  7957. if ( _contextGlobalAlpha !== value ) {
  7958. _context.globalAlpha = value;
  7959. _contextGlobalAlpha = value;
  7960. }
  7961. }
  7962. function setBlending( value ) {
  7963. if ( _contextGlobalCompositeOperation !== value ) {
  7964. if ( value === THREE.NormalBlending ) {
  7965. _context.globalCompositeOperation = 'source-over';
  7966. } else if ( value === THREE.AdditiveBlending ) {
  7967. _context.globalCompositeOperation = 'lighter';
  7968. } else if ( value === THREE.SubtractiveBlending ) {
  7969. _context.globalCompositeOperation = 'darker';
  7970. }
  7971. _contextGlobalCompositeOperation = value;
  7972. }
  7973. }
  7974. function setLineWidth( value ) {
  7975. if ( _contextLineWidth !== value ) {
  7976. _context.lineWidth = value;
  7977. _contextLineWidth = value;
  7978. }
  7979. }
  7980. function setLineCap( value ) {
  7981. // "butt", "round", "square"
  7982. if ( _contextLineCap !== value ) {
  7983. _context.lineCap = value;
  7984. _contextLineCap = value;
  7985. }
  7986. }
  7987. function setLineJoin( value ) {
  7988. // "round", "bevel", "miter"
  7989. if ( _contextLineJoin !== value ) {
  7990. _context.lineJoin = value;
  7991. _contextLineJoin = value;
  7992. }
  7993. }
  7994. function setStrokeStyle( value ) {
  7995. if ( _contextStrokeStyle !== value ) {
  7996. _context.strokeStyle = value;
  7997. _contextStrokeStyle = value;
  7998. }
  7999. }
  8000. function setFillStyle( value ) {
  8001. if ( _contextFillStyle !== value ) {
  8002. _context.fillStyle = value;
  8003. _contextFillStyle = value;
  8004. }
  8005. }
  8006. };
  8007. /**
  8008. * @author alteredq / http://alteredqualia.com/
  8009. * @author mrdoob / http://mrdoob.com/
  8010. * @author mikael emtinger / http://gomo.se/
  8011. */
  8012. THREE.ShaderChunk = {
  8013. // FOG
  8014. fog_pars_fragment: [
  8015. "#ifdef USE_FOG",
  8016. "uniform vec3 fogColor;",
  8017. "#ifdef FOG_EXP2",
  8018. "uniform float fogDensity;",
  8019. "#else",
  8020. "uniform float fogNear;",
  8021. "uniform float fogFar;",
  8022. "#endif",
  8023. "#endif"
  8024. ].join("\n"),
  8025. fog_fragment: [
  8026. "#ifdef USE_FOG",
  8027. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8028. "#ifdef FOG_EXP2",
  8029. "const float LOG2 = 1.442695;",
  8030. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8031. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8032. "#else",
  8033. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8034. "#endif",
  8035. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8036. "#endif"
  8037. ].join("\n"),
  8038. // ENVIRONMENT MAP
  8039. envmap_pars_fragment: [
  8040. "#ifdef USE_ENVMAP",
  8041. "uniform float reflectivity;",
  8042. "uniform samplerCube envMap;",
  8043. "uniform float flipEnvMap;",
  8044. "uniform int combine;",
  8045. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8046. "uniform bool useRefract;",
  8047. "uniform float refractionRatio;",
  8048. "#else",
  8049. "varying vec3 vReflect;",
  8050. "#endif",
  8051. "#endif"
  8052. ].join("\n"),
  8053. envmap_fragment: [
  8054. "#ifdef USE_ENVMAP",
  8055. "vec3 reflectVec;",
  8056. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8057. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8058. "if ( useRefract ) {",
  8059. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8060. "} else { ",
  8061. "reflectVec = reflect( cameraToVertex, normal );",
  8062. "}",
  8063. "#else",
  8064. "reflectVec = vReflect;",
  8065. "#endif",
  8066. "#ifdef DOUBLE_SIDED",
  8067. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8068. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8069. "#else",
  8070. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8071. "#endif",
  8072. "#ifdef GAMMA_INPUT",
  8073. "cubeColor.xyz *= cubeColor.xyz;",
  8074. "#endif",
  8075. "if ( combine == 1 ) {",
  8076. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8077. "} else if ( combine == 2 ) {",
  8078. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8079. "} else {",
  8080. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8081. "}",
  8082. "#endif"
  8083. ].join("\n"),
  8084. envmap_pars_vertex: [
  8085. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8086. "varying vec3 vReflect;",
  8087. "uniform float refractionRatio;",
  8088. "uniform bool useRefract;",
  8089. "#endif"
  8090. ].join("\n"),
  8091. worldpos_vertex : [
  8092. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8093. "#ifdef USE_SKINNING",
  8094. "vec4 worldPosition = modelMatrix * skinned;",
  8095. "#endif",
  8096. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8097. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8098. "#endif",
  8099. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8100. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8101. "#endif",
  8102. "#endif"
  8103. ].join("\n"),
  8104. envmap_vertex : [
  8105. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8106. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8107. "worldNormal = normalize( worldNormal );",
  8108. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8109. "if ( useRefract ) {",
  8110. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8111. "} else {",
  8112. "vReflect = reflect( cameraToVertex, worldNormal );",
  8113. "}",
  8114. "#endif"
  8115. ].join("\n"),
  8116. // COLOR MAP (particles)
  8117. map_particle_pars_fragment: [
  8118. "#ifdef USE_MAP",
  8119. "uniform sampler2D map;",
  8120. "#endif"
  8121. ].join("\n"),
  8122. map_particle_fragment: [
  8123. "#ifdef USE_MAP",
  8124. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8125. "#endif"
  8126. ].join("\n"),
  8127. // COLOR MAP (triangles)
  8128. map_pars_vertex: [
  8129. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8130. "varying vec2 vUv;",
  8131. "uniform vec4 offsetRepeat;",
  8132. "#endif"
  8133. ].join("\n"),
  8134. map_pars_fragment: [
  8135. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8136. "varying vec2 vUv;",
  8137. "#endif",
  8138. "#ifdef USE_MAP",
  8139. "uniform sampler2D map;",
  8140. "#endif"
  8141. ].join("\n"),
  8142. map_vertex: [
  8143. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8144. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8145. "#endif"
  8146. ].join("\n"),
  8147. map_fragment: [
  8148. "#ifdef USE_MAP",
  8149. "#ifdef GAMMA_INPUT",
  8150. "vec4 texelColor = texture2D( map, vUv );",
  8151. "texelColor.xyz *= texelColor.xyz;",
  8152. "gl_FragColor = gl_FragColor * texelColor;",
  8153. "#else",
  8154. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  8155. "#endif",
  8156. "#endif"
  8157. ].join("\n"),
  8158. // LIGHT MAP
  8159. lightmap_pars_fragment: [
  8160. "#ifdef USE_LIGHTMAP",
  8161. "varying vec2 vUv2;",
  8162. "uniform sampler2D lightMap;",
  8163. "#endif"
  8164. ].join("\n"),
  8165. lightmap_pars_vertex: [
  8166. "#ifdef USE_LIGHTMAP",
  8167. "varying vec2 vUv2;",
  8168. "#endif"
  8169. ].join("\n"),
  8170. lightmap_fragment: [
  8171. "#ifdef USE_LIGHTMAP",
  8172. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8173. "#endif"
  8174. ].join("\n"),
  8175. lightmap_vertex: [
  8176. "#ifdef USE_LIGHTMAP",
  8177. "vUv2 = uv2;",
  8178. "#endif"
  8179. ].join("\n"),
  8180. // BUMP MAP
  8181. bumpmap_pars_fragment: [
  8182. "#ifdef USE_BUMPMAP",
  8183. "uniform sampler2D bumpMap;",
  8184. "uniform float bumpScale;",
  8185. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8186. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8187. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8188. "vec2 dHdxy_fwd() {",
  8189. "vec2 dSTdx = dFdx( vUv );",
  8190. "vec2 dSTdy = dFdy( vUv );",
  8191. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8192. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8193. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8194. "return vec2( dBx, dBy );",
  8195. "}",
  8196. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8197. "vec3 vSigmaX = dFdx( surf_pos );",
  8198. "vec3 vSigmaY = dFdy( surf_pos );",
  8199. "vec3 vN = surf_norm;", // normalized
  8200. "vec3 R1 = cross( vSigmaY, vN );",
  8201. "vec3 R2 = cross( vN, vSigmaX );",
  8202. "float fDet = dot( vSigmaX, R1 );",
  8203. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8204. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8205. "}",
  8206. "#endif"
  8207. ].join("\n"),
  8208. // NORMAL MAP
  8209. normalmap_pars_fragment: [
  8210. "#ifdef USE_NORMALMAP",
  8211. "uniform sampler2D normalMap;",
  8212. "uniform vec2 normalScale;",
  8213. // Per-Pixel Tangent Space Normal Mapping
  8214. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8215. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8216. "vec3 q0 = dFdx( eye_pos.xyz );",
  8217. "vec3 q1 = dFdy( eye_pos.xyz );",
  8218. "vec2 st0 = dFdx( vUv.st );",
  8219. "vec2 st1 = dFdy( vUv.st );",
  8220. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8221. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8222. "vec3 N = normalize( surf_norm );",
  8223. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8224. "mapN.xy = normalScale * mapN.xy;",
  8225. "mat3 tsn = mat3( S, T, N );",
  8226. "return normalize( tsn * mapN );",
  8227. "}",
  8228. "#endif"
  8229. ].join("\n"),
  8230. // SPECULAR MAP
  8231. specularmap_pars_fragment: [
  8232. "#ifdef USE_SPECULARMAP",
  8233. "uniform sampler2D specularMap;",
  8234. "#endif"
  8235. ].join("\n"),
  8236. specularmap_fragment: [
  8237. "float specularStrength;",
  8238. "#ifdef USE_SPECULARMAP",
  8239. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8240. "specularStrength = texelSpecular.r;",
  8241. "#else",
  8242. "specularStrength = 1.0;",
  8243. "#endif"
  8244. ].join("\n"),
  8245. // LIGHTS LAMBERT
  8246. lights_lambert_pars_vertex: [
  8247. "uniform vec3 ambient;",
  8248. "uniform vec3 diffuse;",
  8249. "uniform vec3 emissive;",
  8250. "uniform vec3 ambientLightColor;",
  8251. "#if MAX_DIR_LIGHTS > 0",
  8252. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8253. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8254. "#endif",
  8255. "#if MAX_HEMI_LIGHTS > 0",
  8256. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8257. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8258. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8259. "#endif",
  8260. "#if MAX_POINT_LIGHTS > 0",
  8261. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8262. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8263. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8264. "#endif",
  8265. "#if MAX_SPOT_LIGHTS > 0",
  8266. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8267. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8268. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8269. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8270. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8271. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8272. "#endif",
  8273. "#ifdef WRAP_AROUND",
  8274. "uniform vec3 wrapRGB;",
  8275. "#endif"
  8276. ].join("\n"),
  8277. lights_lambert_vertex: [
  8278. "vLightFront = vec3( 0.0 );",
  8279. "#ifdef DOUBLE_SIDED",
  8280. "vLightBack = vec3( 0.0 );",
  8281. "#endif",
  8282. "transformedNormal = normalize( transformedNormal );",
  8283. "#if MAX_DIR_LIGHTS > 0",
  8284. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8285. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8286. "vec3 dirVector = normalize( lDirection.xyz );",
  8287. "float dotProduct = dot( transformedNormal, dirVector );",
  8288. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8289. "#ifdef DOUBLE_SIDED",
  8290. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8291. "#ifdef WRAP_AROUND",
  8292. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8293. "#endif",
  8294. "#endif",
  8295. "#ifdef WRAP_AROUND",
  8296. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8297. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8298. "#ifdef DOUBLE_SIDED",
  8299. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8300. "#endif",
  8301. "#endif",
  8302. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8303. "#ifdef DOUBLE_SIDED",
  8304. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8305. "#endif",
  8306. "}",
  8307. "#endif",
  8308. "#if MAX_POINT_LIGHTS > 0",
  8309. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8310. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8311. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8312. "float lDistance = 1.0;",
  8313. "if ( pointLightDistance[ i ] > 0.0 )",
  8314. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8315. "lVector = normalize( lVector );",
  8316. "float dotProduct = dot( transformedNormal, lVector );",
  8317. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8318. "#ifdef DOUBLE_SIDED",
  8319. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8320. "#ifdef WRAP_AROUND",
  8321. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8322. "#endif",
  8323. "#endif",
  8324. "#ifdef WRAP_AROUND",
  8325. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8326. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8327. "#ifdef DOUBLE_SIDED",
  8328. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8329. "#endif",
  8330. "#endif",
  8331. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8332. "#ifdef DOUBLE_SIDED",
  8333. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8334. "#endif",
  8335. "}",
  8336. "#endif",
  8337. "#if MAX_SPOT_LIGHTS > 0",
  8338. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8339. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8340. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8341. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8342. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8343. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8344. "float lDistance = 1.0;",
  8345. "if ( spotLightDistance[ i ] > 0.0 )",
  8346. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8347. "lVector = normalize( lVector );",
  8348. "float dotProduct = dot( transformedNormal, lVector );",
  8349. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8350. "#ifdef DOUBLE_SIDED",
  8351. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8352. "#ifdef WRAP_AROUND",
  8353. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8354. "#endif",
  8355. "#endif",
  8356. "#ifdef WRAP_AROUND",
  8357. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8358. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8359. "#ifdef DOUBLE_SIDED",
  8360. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8361. "#endif",
  8362. "#endif",
  8363. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8364. "#ifdef DOUBLE_SIDED",
  8365. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8366. "#endif",
  8367. "}",
  8368. "}",
  8369. "#endif",
  8370. "#if MAX_HEMI_LIGHTS > 0",
  8371. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8372. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8373. "vec3 lVector = normalize( lDirection.xyz );",
  8374. "float dotProduct = dot( transformedNormal, lVector );",
  8375. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8376. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8377. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8378. "#ifdef DOUBLE_SIDED",
  8379. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8380. "#endif",
  8381. "}",
  8382. "#endif",
  8383. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8384. "#ifdef DOUBLE_SIDED",
  8385. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8386. "#endif"
  8387. ].join("\n"),
  8388. // LIGHTS PHONG
  8389. lights_phong_pars_vertex: [
  8390. "#ifndef PHONG_PER_PIXEL",
  8391. "#if MAX_POINT_LIGHTS > 0",
  8392. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8393. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8394. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8395. "#endif",
  8396. "#if MAX_SPOT_LIGHTS > 0",
  8397. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8398. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8399. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8400. "#endif",
  8401. "#endif",
  8402. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8403. "varying vec3 vWorldPosition;",
  8404. "#endif"
  8405. ].join("\n"),
  8406. lights_phong_vertex: [
  8407. "#ifndef PHONG_PER_PIXEL",
  8408. "#if MAX_POINT_LIGHTS > 0",
  8409. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8410. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8411. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8412. "float lDistance = 1.0;",
  8413. "if ( pointLightDistance[ i ] > 0.0 )",
  8414. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8415. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8416. "}",
  8417. "#endif",
  8418. "#if MAX_SPOT_LIGHTS > 0",
  8419. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8420. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8421. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8422. "float lDistance = 1.0;",
  8423. "if ( spotLightDistance[ i ] > 0.0 )",
  8424. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8425. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8426. "}",
  8427. "#endif",
  8428. "#endif",
  8429. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8430. "vWorldPosition = worldPosition.xyz;",
  8431. "#endif"
  8432. ].join("\n"),
  8433. lights_phong_pars_fragment: [
  8434. "uniform vec3 ambientLightColor;",
  8435. "#if MAX_DIR_LIGHTS > 0",
  8436. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8437. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8438. "#endif",
  8439. "#if MAX_HEMI_LIGHTS > 0",
  8440. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8441. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8442. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8443. "#endif",
  8444. "#if MAX_POINT_LIGHTS > 0",
  8445. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8446. "#ifdef PHONG_PER_PIXEL",
  8447. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8448. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8449. "#else",
  8450. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8451. "#endif",
  8452. "#endif",
  8453. "#if MAX_SPOT_LIGHTS > 0",
  8454. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8455. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8456. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8457. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8458. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8459. "#ifdef PHONG_PER_PIXEL",
  8460. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8461. "#else",
  8462. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8463. "#endif",
  8464. "#endif",
  8465. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8466. "varying vec3 vWorldPosition;",
  8467. "#endif",
  8468. "#ifdef WRAP_AROUND",
  8469. "uniform vec3 wrapRGB;",
  8470. "#endif",
  8471. "varying vec3 vViewPosition;",
  8472. "varying vec3 vNormal;"
  8473. ].join("\n"),
  8474. lights_phong_fragment: [
  8475. "vec3 normal = normalize( vNormal );",
  8476. "vec3 viewPosition = normalize( vViewPosition );",
  8477. "#ifdef DOUBLE_SIDED",
  8478. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8479. "#endif",
  8480. "#ifdef USE_NORMALMAP",
  8481. "normal = perturbNormal2Arb( -viewPosition, normal );",
  8482. "#elif defined( USE_BUMPMAP )",
  8483. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8484. "#endif",
  8485. "#if MAX_POINT_LIGHTS > 0",
  8486. "vec3 pointDiffuse = vec3( 0.0 );",
  8487. "vec3 pointSpecular = vec3( 0.0 );",
  8488. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8489. "#ifdef PHONG_PER_PIXEL",
  8490. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8491. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8492. "float lDistance = 1.0;",
  8493. "if ( pointLightDistance[ i ] > 0.0 )",
  8494. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8495. "lVector = normalize( lVector );",
  8496. "#else",
  8497. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8498. "float lDistance = vPointLight[ i ].w;",
  8499. "#endif",
  8500. // diffuse
  8501. "float dotProduct = dot( normal, lVector );",
  8502. "#ifdef WRAP_AROUND",
  8503. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8504. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8505. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8506. "#else",
  8507. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8508. "#endif",
  8509. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8510. // specular
  8511. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8512. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8513. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8514. "#ifdef PHYSICALLY_BASED_SHADING",
  8515. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8516. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8517. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8518. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8519. "#else",
  8520. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8521. "#endif",
  8522. "}",
  8523. "#endif",
  8524. "#if MAX_SPOT_LIGHTS > 0",
  8525. "vec3 spotDiffuse = vec3( 0.0 );",
  8526. "vec3 spotSpecular = vec3( 0.0 );",
  8527. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8528. "#ifdef PHONG_PER_PIXEL",
  8529. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8530. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8531. "float lDistance = 1.0;",
  8532. "if ( spotLightDistance[ i ] > 0.0 )",
  8533. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8534. "lVector = normalize( lVector );",
  8535. "#else",
  8536. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8537. "float lDistance = vSpotLight[ i ].w;",
  8538. "#endif",
  8539. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8540. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8541. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8542. // diffuse
  8543. "float dotProduct = dot( normal, lVector );",
  8544. "#ifdef WRAP_AROUND",
  8545. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8546. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8547. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8548. "#else",
  8549. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8550. "#endif",
  8551. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8552. // specular
  8553. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8554. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8555. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8556. "#ifdef PHYSICALLY_BASED_SHADING",
  8557. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8558. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8559. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8560. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8561. "#else",
  8562. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8563. "#endif",
  8564. "}",
  8565. "}",
  8566. "#endif",
  8567. "#if MAX_DIR_LIGHTS > 0",
  8568. "vec3 dirDiffuse = vec3( 0.0 );",
  8569. "vec3 dirSpecular = vec3( 0.0 );" ,
  8570. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8571. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8572. "vec3 dirVector = normalize( lDirection.xyz );",
  8573. // diffuse
  8574. "float dotProduct = dot( normal, dirVector );",
  8575. "#ifdef WRAP_AROUND",
  8576. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8577. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8578. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8579. "#else",
  8580. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8581. "#endif",
  8582. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8583. // specular
  8584. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8585. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8586. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8587. "#ifdef PHYSICALLY_BASED_SHADING",
  8588. /*
  8589. // fresnel term from skin shader
  8590. "const float F0 = 0.128;",
  8591. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8592. "float exponential = pow( base, 5.0 );",
  8593. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8594. */
  8595. /*
  8596. // fresnel term from fresnel shader
  8597. "const float mFresnelBias = 0.08;",
  8598. "const float mFresnelScale = 0.3;",
  8599. "const float mFresnelPower = 5.0;",
  8600. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8601. */
  8602. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8603. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8604. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8605. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8606. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8607. "#else",
  8608. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8609. "#endif",
  8610. "}",
  8611. "#endif",
  8612. "#if MAX_HEMI_LIGHTS > 0",
  8613. "vec3 hemiDiffuse = vec3( 0.0 );",
  8614. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8615. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8616. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  8617. "vec3 lVector = normalize( lDirection.xyz );",
  8618. // diffuse
  8619. "float dotProduct = dot( normal, lVector );",
  8620. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8621. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8622. "hemiDiffuse += diffuse * hemiColor;",
  8623. // specular (sky light)
  8624. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8625. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8626. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8627. // specular (ground light)
  8628. "vec3 lVectorGround = -lVector;",
  8629. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8630. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8631. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8632. "#ifdef PHYSICALLY_BASED_SHADING",
  8633. "float dotProductGround = dot( normal, lVectorGround );",
  8634. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8635. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8636. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8637. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8638. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  8639. "#else",
  8640. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  8641. "#endif",
  8642. "}",
  8643. "#endif",
  8644. "vec3 totalDiffuse = vec3( 0.0 );",
  8645. "vec3 totalSpecular = vec3( 0.0 );",
  8646. "#if MAX_DIR_LIGHTS > 0",
  8647. "totalDiffuse += dirDiffuse;",
  8648. "totalSpecular += dirSpecular;",
  8649. "#endif",
  8650. "#if MAX_HEMI_LIGHTS > 0",
  8651. "totalDiffuse += hemiDiffuse;",
  8652. "totalSpecular += hemiSpecular;",
  8653. "#endif",
  8654. "#if MAX_POINT_LIGHTS > 0",
  8655. "totalDiffuse += pointDiffuse;",
  8656. "totalSpecular += pointSpecular;",
  8657. "#endif",
  8658. "#if MAX_SPOT_LIGHTS > 0",
  8659. "totalDiffuse += spotDiffuse;",
  8660. "totalSpecular += spotSpecular;",
  8661. "#endif",
  8662. "#ifdef METAL",
  8663. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8664. "#else",
  8665. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8666. "#endif"
  8667. ].join("\n"),
  8668. // VERTEX COLORS
  8669. color_pars_fragment: [
  8670. "#ifdef USE_COLOR",
  8671. "varying vec3 vColor;",
  8672. "#endif"
  8673. ].join("\n"),
  8674. color_fragment: [
  8675. "#ifdef USE_COLOR",
  8676. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8677. "#endif"
  8678. ].join("\n"),
  8679. color_pars_vertex: [
  8680. "#ifdef USE_COLOR",
  8681. "varying vec3 vColor;",
  8682. "#endif"
  8683. ].join("\n"),
  8684. color_vertex: [
  8685. "#ifdef USE_COLOR",
  8686. "#ifdef GAMMA_INPUT",
  8687. "vColor = color * color;",
  8688. "#else",
  8689. "vColor = color;",
  8690. "#endif",
  8691. "#endif"
  8692. ].join("\n"),
  8693. // SKINNING
  8694. skinning_pars_vertex: [
  8695. "#ifdef USE_SKINNING",
  8696. "#ifdef BONE_TEXTURE",
  8697. "uniform sampler2D boneTexture;",
  8698. "mat4 getBoneMatrix( const in float i ) {",
  8699. "float j = i * 4.0;",
  8700. "float x = mod( j, N_BONE_PIXEL_X );",
  8701. "float y = floor( j / N_BONE_PIXEL_X );",
  8702. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8703. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8704. "y = dy * ( y + 0.5 );",
  8705. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8706. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8707. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8708. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8709. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8710. "return bone;",
  8711. "}",
  8712. "#else",
  8713. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8714. "mat4 getBoneMatrix( const in float i ) {",
  8715. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8716. "return bone;",
  8717. "}",
  8718. "#endif",
  8719. "#endif"
  8720. ].join("\n"),
  8721. skinbase_vertex: [
  8722. "#ifdef USE_SKINNING",
  8723. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8724. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8725. "#endif"
  8726. ].join("\n"),
  8727. skinning_vertex: [
  8728. "#ifdef USE_SKINNING",
  8729. "#ifdef USE_MORPHTARGETS",
  8730. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8731. "#else",
  8732. "vec4 skinVertex = vec4( position, 1.0 );",
  8733. "#endif",
  8734. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8735. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8736. "#endif"
  8737. ].join("\n"),
  8738. // MORPHING
  8739. morphtarget_pars_vertex: [
  8740. "#ifdef USE_MORPHTARGETS",
  8741. "#ifndef USE_MORPHNORMALS",
  8742. "uniform float morphTargetInfluences[ 8 ];",
  8743. "#else",
  8744. "uniform float morphTargetInfluences[ 4 ];",
  8745. "#endif",
  8746. "#endif"
  8747. ].join("\n"),
  8748. morphtarget_vertex: [
  8749. "#ifdef USE_MORPHTARGETS",
  8750. "vec3 morphed = vec3( 0.0 );",
  8751. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8752. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8753. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8754. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8755. "#ifndef USE_MORPHNORMALS",
  8756. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8757. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8758. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8759. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8760. "#endif",
  8761. "morphed += position;",
  8762. "#endif"
  8763. ].join("\n"),
  8764. default_vertex : [
  8765. "vec4 mvPosition;",
  8766. "#ifdef USE_SKINNING",
  8767. "mvPosition = modelViewMatrix * skinned;",
  8768. "#endif",
  8769. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8770. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8771. "#endif",
  8772. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8773. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8774. "#endif",
  8775. "gl_Position = projectionMatrix * mvPosition;"
  8776. ].join("\n"),
  8777. morphnormal_vertex: [
  8778. "#ifdef USE_MORPHNORMALS",
  8779. "vec3 morphedNormal = vec3( 0.0 );",
  8780. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8781. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8782. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8783. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8784. "morphedNormal += normal;",
  8785. "#endif"
  8786. ].join("\n"),
  8787. skinnormal_vertex: [
  8788. "#ifdef USE_SKINNING",
  8789. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8790. "skinMatrix += skinWeight.y * boneMatY;",
  8791. "#ifdef USE_MORPHNORMALS",
  8792. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8793. "#else",
  8794. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8795. "#endif",
  8796. "#endif"
  8797. ].join("\n"),
  8798. defaultnormal_vertex: [
  8799. "vec3 objectNormal;",
  8800. "#ifdef USE_SKINNING",
  8801. "objectNormal = skinnedNormal.xyz;",
  8802. "#endif",
  8803. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8804. "objectNormal = morphedNormal;",
  8805. "#endif",
  8806. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8807. "objectNormal = normal;",
  8808. "#endif",
  8809. "#ifdef FLIP_SIDED",
  8810. "objectNormal = -objectNormal;",
  8811. "#endif",
  8812. "vec3 transformedNormal = normalMatrix * objectNormal;"
  8813. ].join("\n"),
  8814. // SHADOW MAP
  8815. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8816. // http://spidergl.org/example.php?id=6
  8817. // http://fabiensanglard.net/shadowmapping
  8818. shadowmap_pars_fragment: [
  8819. "#ifdef USE_SHADOWMAP",
  8820. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8821. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8822. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8823. "uniform float shadowBias[ MAX_SHADOWS ];",
  8824. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8825. "float unpackDepth( const in vec4 rgba_depth ) {",
  8826. "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 );",
  8827. "float depth = dot( rgba_depth, bit_shift );",
  8828. "return depth;",
  8829. "}",
  8830. "#endif"
  8831. ].join("\n"),
  8832. shadowmap_fragment: [
  8833. "#ifdef USE_SHADOWMAP",
  8834. "#ifdef SHADOWMAP_DEBUG",
  8835. "vec3 frustumColors[3];",
  8836. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8837. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8838. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8839. "#endif",
  8840. "#ifdef SHADOWMAP_CASCADE",
  8841. "int inFrustumCount = 0;",
  8842. "#endif",
  8843. "float fDepth;",
  8844. "vec3 shadowColor = vec3( 1.0 );",
  8845. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8846. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8847. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8848. // "if ( all( something, something ) )" using this instead
  8849. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8850. "bool inFrustum = all( inFrustumVec );",
  8851. // don't shadow pixels outside of light frustum
  8852. // use just first frustum (for cascades)
  8853. // don't shadow pixels behind far plane of light frustum
  8854. "#ifdef SHADOWMAP_CASCADE",
  8855. "inFrustumCount += int( inFrustum );",
  8856. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8857. "#else",
  8858. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8859. "#endif",
  8860. "bool frustumTest = all( frustumTestVec );",
  8861. "if ( frustumTest ) {",
  8862. "shadowCoord.z += shadowBias[ i ];",
  8863. "#ifdef SHADOWMAP_SOFT",
  8864. // Percentage-close filtering
  8865. // (9 pixel kernel)
  8866. // http://fabiensanglard.net/shadowmappingPCF/
  8867. "float shadow = 0.0;",
  8868. /*
  8869. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8870. // must enroll loop manually
  8871. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8872. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8873. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8874. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8875. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8876. "float fDepth = unpackDepth( rgbaDepth );",
  8877. "if ( fDepth < shadowCoord.z )",
  8878. "shadow += 1.0;",
  8879. "}",
  8880. "shadow /= 9.0;",
  8881. */
  8882. "const float shadowDelta = 1.0 / 9.0;",
  8883. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8884. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8885. "float dx0 = -1.25 * xPixelOffset;",
  8886. "float dy0 = -1.25 * yPixelOffset;",
  8887. "float dx1 = 1.25 * xPixelOffset;",
  8888. "float dy1 = 1.25 * yPixelOffset;",
  8889. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8890. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8891. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8892. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8893. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8894. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8895. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8896. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8897. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8898. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8899. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8900. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8901. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8902. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8903. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8904. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8905. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8906. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8907. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8908. "#else",
  8909. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8910. "float fDepth = unpackDepth( rgbaDepth );",
  8911. "if ( fDepth < shadowCoord.z )",
  8912. // spot with multiple shadows is darker
  8913. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8914. // spot with multiple shadows has the same color as single shadow spot
  8915. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8916. "#endif",
  8917. "}",
  8918. "#ifdef SHADOWMAP_DEBUG",
  8919. "#ifdef SHADOWMAP_CASCADE",
  8920. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8921. "#else",
  8922. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8923. "#endif",
  8924. "#endif",
  8925. "}",
  8926. "#ifdef GAMMA_OUTPUT",
  8927. "shadowColor *= shadowColor;",
  8928. "#endif",
  8929. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8930. "#endif"
  8931. ].join("\n"),
  8932. shadowmap_pars_vertex: [
  8933. "#ifdef USE_SHADOWMAP",
  8934. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8935. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8936. "#endif"
  8937. ].join("\n"),
  8938. shadowmap_vertex: [
  8939. "#ifdef USE_SHADOWMAP",
  8940. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8941. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  8942. "}",
  8943. "#endif"
  8944. ].join("\n"),
  8945. // ALPHATEST
  8946. alphatest_fragment: [
  8947. "#ifdef ALPHATEST",
  8948. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8949. "#endif"
  8950. ].join("\n"),
  8951. // LINEAR SPACE
  8952. linear_to_gamma_fragment: [
  8953. "#ifdef GAMMA_OUTPUT",
  8954. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8955. "#endif"
  8956. ].join("\n")
  8957. };
  8958. THREE.UniformsUtils = {
  8959. merge: function ( uniforms ) {
  8960. var u, p, tmp, merged = {};
  8961. for ( u = 0; u < uniforms.length; u ++ ) {
  8962. tmp = this.clone( uniforms[ u ] );
  8963. for ( p in tmp ) {
  8964. merged[ p ] = tmp[ p ];
  8965. }
  8966. }
  8967. return merged;
  8968. },
  8969. clone: function ( uniforms_src ) {
  8970. var u, p, parameter, parameter_src, uniforms_dst = {};
  8971. for ( u in uniforms_src ) {
  8972. uniforms_dst[ u ] = {};
  8973. for ( p in uniforms_src[ u ] ) {
  8974. parameter_src = uniforms_src[ u ][ p ];
  8975. if ( parameter_src instanceof THREE.Color ||
  8976. parameter_src instanceof THREE.Vector2 ||
  8977. parameter_src instanceof THREE.Vector3 ||
  8978. parameter_src instanceof THREE.Vector4 ||
  8979. parameter_src instanceof THREE.Matrix4 ||
  8980. parameter_src instanceof THREE.Texture ) {
  8981. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8982. } else if ( parameter_src instanceof Array ) {
  8983. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8984. } else {
  8985. uniforms_dst[ u ][ p ] = parameter_src;
  8986. }
  8987. }
  8988. }
  8989. return uniforms_dst;
  8990. }
  8991. };
  8992. THREE.UniformsLib = {
  8993. common: {
  8994. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8995. "opacity" : { type: "f", value: 1.0 },
  8996. "map" : { type: "t", value: null },
  8997. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8998. "lightMap" : { type: "t", value: null },
  8999. "specularMap" : { type: "t", value: null },
  9000. "envMap" : { type: "t", value: null },
  9001. "flipEnvMap" : { type: "f", value: -1 },
  9002. "useRefract" : { type: "i", value: 0 },
  9003. "reflectivity" : { type: "f", value: 1.0 },
  9004. "refractionRatio" : { type: "f", value: 0.98 },
  9005. "combine" : { type: "i", value: 0 },
  9006. "morphTargetInfluences" : { type: "f", value: 0 }
  9007. },
  9008. bump: {
  9009. "bumpMap" : { type: "t", value: null },
  9010. "bumpScale" : { type: "f", value: 1 }
  9011. },
  9012. normalmap: {
  9013. "normalMap" : { type: "t", value: null },
  9014. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9015. },
  9016. fog : {
  9017. "fogDensity" : { type: "f", value: 0.00025 },
  9018. "fogNear" : { type: "f", value: 1 },
  9019. "fogFar" : { type: "f", value: 2000 },
  9020. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9021. },
  9022. lights: {
  9023. "ambientLightColor" : { type: "fv", value: [] },
  9024. "directionalLightDirection" : { type: "fv", value: [] },
  9025. "directionalLightColor" : { type: "fv", value: [] },
  9026. "hemisphereLightDirection" : { type: "fv", value: [] },
  9027. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9028. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9029. "pointLightColor" : { type: "fv", value: [] },
  9030. "pointLightPosition" : { type: "fv", value: [] },
  9031. "pointLightDistance" : { type: "fv1", value: [] },
  9032. "spotLightColor" : { type: "fv", value: [] },
  9033. "spotLightPosition" : { type: "fv", value: [] },
  9034. "spotLightDirection" : { type: "fv", value: [] },
  9035. "spotLightDistance" : { type: "fv1", value: [] },
  9036. "spotLightAngleCos" : { type: "fv1", value: [] },
  9037. "spotLightExponent" : { type: "fv1", value: [] }
  9038. },
  9039. particle: {
  9040. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9041. "opacity" : { type: "f", value: 1.0 },
  9042. "size" : { type: "f", value: 1.0 },
  9043. "scale" : { type: "f", value: 1.0 },
  9044. "map" : { type: "t", value: null },
  9045. "fogDensity" : { type: "f", value: 0.00025 },
  9046. "fogNear" : { type: "f", value: 1 },
  9047. "fogFar" : { type: "f", value: 2000 },
  9048. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9049. },
  9050. shadowmap: {
  9051. "shadowMap": { type: "tv", value: [] },
  9052. "shadowMapSize": { type: "v2v", value: [] },
  9053. "shadowBias" : { type: "fv1", value: [] },
  9054. "shadowDarkness": { type: "fv1", value: [] },
  9055. "shadowMatrix" : { type: "m4v", value: [] }
  9056. }
  9057. };
  9058. THREE.ShaderLib = {
  9059. 'depth': {
  9060. uniforms: {
  9061. "mNear": { type: "f", value: 1.0 },
  9062. "mFar" : { type: "f", value: 2000.0 },
  9063. "opacity" : { type: "f", value: 1.0 }
  9064. },
  9065. vertexShader: [
  9066. "void main() {",
  9067. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9068. "}"
  9069. ].join("\n"),
  9070. fragmentShader: [
  9071. "uniform float mNear;",
  9072. "uniform float mFar;",
  9073. "uniform float opacity;",
  9074. "void main() {",
  9075. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9076. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9077. "gl_FragColor = vec4( vec3( color ), opacity );",
  9078. "}"
  9079. ].join("\n")
  9080. },
  9081. 'normal': {
  9082. uniforms: {
  9083. "opacity" : { type: "f", value: 1.0 }
  9084. },
  9085. vertexShader: [
  9086. "varying vec3 vNormal;",
  9087. "void main() {",
  9088. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9089. "vNormal = normalize( normalMatrix * normal );",
  9090. "gl_Position = projectionMatrix * mvPosition;",
  9091. "}"
  9092. ].join("\n"),
  9093. fragmentShader: [
  9094. "uniform float opacity;",
  9095. "varying vec3 vNormal;",
  9096. "void main() {",
  9097. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9098. "}"
  9099. ].join("\n")
  9100. },
  9101. 'basic': {
  9102. uniforms: THREE.UniformsUtils.merge( [
  9103. THREE.UniformsLib[ "common" ],
  9104. THREE.UniformsLib[ "fog" ],
  9105. THREE.UniformsLib[ "shadowmap" ]
  9106. ] ),
  9107. vertexShader: [
  9108. THREE.ShaderChunk[ "map_pars_vertex" ],
  9109. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9110. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9111. THREE.ShaderChunk[ "color_pars_vertex" ],
  9112. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9113. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9114. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9115. "void main() {",
  9116. THREE.ShaderChunk[ "map_vertex" ],
  9117. THREE.ShaderChunk[ "lightmap_vertex" ],
  9118. THREE.ShaderChunk[ "color_vertex" ],
  9119. "#ifdef USE_ENVMAP",
  9120. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9121. THREE.ShaderChunk[ "skinbase_vertex" ],
  9122. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9123. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9124. "#endif",
  9125. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9126. THREE.ShaderChunk[ "skinning_vertex" ],
  9127. THREE.ShaderChunk[ "default_vertex" ],
  9128. THREE.ShaderChunk[ "worldpos_vertex" ],
  9129. THREE.ShaderChunk[ "envmap_vertex" ],
  9130. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9131. "}"
  9132. ].join("\n"),
  9133. fragmentShader: [
  9134. "uniform vec3 diffuse;",
  9135. "uniform float opacity;",
  9136. THREE.ShaderChunk[ "color_pars_fragment" ],
  9137. THREE.ShaderChunk[ "map_pars_fragment" ],
  9138. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9139. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9140. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9141. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9142. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9143. "void main() {",
  9144. "gl_FragColor = vec4( diffuse, opacity );",
  9145. THREE.ShaderChunk[ "map_fragment" ],
  9146. THREE.ShaderChunk[ "alphatest_fragment" ],
  9147. THREE.ShaderChunk[ "specularmap_fragment" ],
  9148. THREE.ShaderChunk[ "lightmap_fragment" ],
  9149. THREE.ShaderChunk[ "color_fragment" ],
  9150. THREE.ShaderChunk[ "envmap_fragment" ],
  9151. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9152. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9153. THREE.ShaderChunk[ "fog_fragment" ],
  9154. "}"
  9155. ].join("\n")
  9156. },
  9157. 'lambert': {
  9158. uniforms: THREE.UniformsUtils.merge( [
  9159. THREE.UniformsLib[ "common" ],
  9160. THREE.UniformsLib[ "fog" ],
  9161. THREE.UniformsLib[ "lights" ],
  9162. THREE.UniformsLib[ "shadowmap" ],
  9163. {
  9164. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9165. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9166. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9167. }
  9168. ] ),
  9169. vertexShader: [
  9170. "#define LAMBERT",
  9171. "varying vec3 vLightFront;",
  9172. "#ifdef DOUBLE_SIDED",
  9173. "varying vec3 vLightBack;",
  9174. "#endif",
  9175. THREE.ShaderChunk[ "map_pars_vertex" ],
  9176. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9177. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9178. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9179. THREE.ShaderChunk[ "color_pars_vertex" ],
  9180. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9181. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9182. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9183. "void main() {",
  9184. THREE.ShaderChunk[ "map_vertex" ],
  9185. THREE.ShaderChunk[ "lightmap_vertex" ],
  9186. THREE.ShaderChunk[ "color_vertex" ],
  9187. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9188. THREE.ShaderChunk[ "skinbase_vertex" ],
  9189. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9190. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9191. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9192. THREE.ShaderChunk[ "skinning_vertex" ],
  9193. THREE.ShaderChunk[ "default_vertex" ],
  9194. THREE.ShaderChunk[ "worldpos_vertex" ],
  9195. THREE.ShaderChunk[ "envmap_vertex" ],
  9196. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9197. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9198. "}"
  9199. ].join("\n"),
  9200. fragmentShader: [
  9201. "uniform float opacity;",
  9202. "varying vec3 vLightFront;",
  9203. "#ifdef DOUBLE_SIDED",
  9204. "varying vec3 vLightBack;",
  9205. "#endif",
  9206. THREE.ShaderChunk[ "color_pars_fragment" ],
  9207. THREE.ShaderChunk[ "map_pars_fragment" ],
  9208. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9209. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9210. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9211. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9212. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9213. "void main() {",
  9214. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9215. THREE.ShaderChunk[ "map_fragment" ],
  9216. THREE.ShaderChunk[ "alphatest_fragment" ],
  9217. THREE.ShaderChunk[ "specularmap_fragment" ],
  9218. "#ifdef DOUBLE_SIDED",
  9219. //"float isFront = float( gl_FrontFacing );",
  9220. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9221. "if ( gl_FrontFacing )",
  9222. "gl_FragColor.xyz *= vLightFront;",
  9223. "else",
  9224. "gl_FragColor.xyz *= vLightBack;",
  9225. "#else",
  9226. "gl_FragColor.xyz *= vLightFront;",
  9227. "#endif",
  9228. THREE.ShaderChunk[ "lightmap_fragment" ],
  9229. THREE.ShaderChunk[ "color_fragment" ],
  9230. THREE.ShaderChunk[ "envmap_fragment" ],
  9231. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9232. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9233. THREE.ShaderChunk[ "fog_fragment" ],
  9234. "}"
  9235. ].join("\n")
  9236. },
  9237. 'phong': {
  9238. uniforms: THREE.UniformsUtils.merge( [
  9239. THREE.UniformsLib[ "common" ],
  9240. THREE.UniformsLib[ "bump" ],
  9241. THREE.UniformsLib[ "normalmap" ],
  9242. THREE.UniformsLib[ "fog" ],
  9243. THREE.UniformsLib[ "lights" ],
  9244. THREE.UniformsLib[ "shadowmap" ],
  9245. {
  9246. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9247. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9248. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9249. "shininess": { type: "f", value: 30 },
  9250. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9251. }
  9252. ] ),
  9253. vertexShader: [
  9254. "#define PHONG",
  9255. "varying vec3 vViewPosition;",
  9256. "varying vec3 vNormal;",
  9257. THREE.ShaderChunk[ "map_pars_vertex" ],
  9258. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9259. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9260. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9261. THREE.ShaderChunk[ "color_pars_vertex" ],
  9262. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9263. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9264. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9265. "void main() {",
  9266. THREE.ShaderChunk[ "map_vertex" ],
  9267. THREE.ShaderChunk[ "lightmap_vertex" ],
  9268. THREE.ShaderChunk[ "color_vertex" ],
  9269. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9270. THREE.ShaderChunk[ "skinbase_vertex" ],
  9271. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9272. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9273. "vNormal = normalize( transformedNormal );",
  9274. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9275. THREE.ShaderChunk[ "skinning_vertex" ],
  9276. THREE.ShaderChunk[ "default_vertex" ],
  9277. "vViewPosition = -mvPosition.xyz;",
  9278. THREE.ShaderChunk[ "worldpos_vertex" ],
  9279. THREE.ShaderChunk[ "envmap_vertex" ],
  9280. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9281. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9282. "}"
  9283. ].join("\n"),
  9284. fragmentShader: [
  9285. "uniform vec3 diffuse;",
  9286. "uniform float opacity;",
  9287. "uniform vec3 ambient;",
  9288. "uniform vec3 emissive;",
  9289. "uniform vec3 specular;",
  9290. "uniform float shininess;",
  9291. THREE.ShaderChunk[ "color_pars_fragment" ],
  9292. THREE.ShaderChunk[ "map_pars_fragment" ],
  9293. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9294. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9295. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9296. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9297. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9298. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9299. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9300. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9301. "void main() {",
  9302. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9303. THREE.ShaderChunk[ "map_fragment" ],
  9304. THREE.ShaderChunk[ "alphatest_fragment" ],
  9305. THREE.ShaderChunk[ "specularmap_fragment" ],
  9306. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9307. THREE.ShaderChunk[ "lightmap_fragment" ],
  9308. THREE.ShaderChunk[ "color_fragment" ],
  9309. THREE.ShaderChunk[ "envmap_fragment" ],
  9310. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9311. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9312. THREE.ShaderChunk[ "fog_fragment" ],
  9313. "}"
  9314. ].join("\n")
  9315. },
  9316. 'particle_basic': {
  9317. uniforms: THREE.UniformsUtils.merge( [
  9318. THREE.UniformsLib[ "particle" ],
  9319. THREE.UniformsLib[ "shadowmap" ]
  9320. ] ),
  9321. vertexShader: [
  9322. "uniform float size;",
  9323. "uniform float scale;",
  9324. THREE.ShaderChunk[ "color_pars_vertex" ],
  9325. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9326. "void main() {",
  9327. THREE.ShaderChunk[ "color_vertex" ],
  9328. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9329. "#ifdef USE_SIZEATTENUATION",
  9330. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9331. "#else",
  9332. "gl_PointSize = size;",
  9333. "#endif",
  9334. "gl_Position = projectionMatrix * mvPosition;",
  9335. THREE.ShaderChunk[ "worldpos_vertex" ],
  9336. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9337. "}"
  9338. ].join("\n"),
  9339. fragmentShader: [
  9340. "uniform vec3 psColor;",
  9341. "uniform float opacity;",
  9342. THREE.ShaderChunk[ "color_pars_fragment" ],
  9343. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9344. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9345. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9346. "void main() {",
  9347. "gl_FragColor = vec4( psColor, opacity );",
  9348. THREE.ShaderChunk[ "map_particle_fragment" ],
  9349. THREE.ShaderChunk[ "alphatest_fragment" ],
  9350. THREE.ShaderChunk[ "color_fragment" ],
  9351. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9352. THREE.ShaderChunk[ "fog_fragment" ],
  9353. "}"
  9354. ].join("\n")
  9355. },
  9356. 'dashed': {
  9357. uniforms: THREE.UniformsUtils.merge( [
  9358. THREE.UniformsLib[ "common" ],
  9359. THREE.UniformsLib[ "fog" ],
  9360. {
  9361. "scale": { type: "f", value: 1 },
  9362. "dashSize": { type: "f", value: 1 },
  9363. "totalSize": { type: "f", value: 2 }
  9364. }
  9365. ] ),
  9366. vertexShader: [
  9367. "uniform float scale;",
  9368. "attribute float lineDistance;",
  9369. "varying float vLineDistance;",
  9370. THREE.ShaderChunk[ "color_pars_vertex" ],
  9371. "void main() {",
  9372. THREE.ShaderChunk[ "color_vertex" ],
  9373. "vLineDistance = scale * lineDistance;",
  9374. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9375. "gl_Position = projectionMatrix * mvPosition;",
  9376. "}"
  9377. ].join("\n"),
  9378. fragmentShader: [
  9379. "uniform vec3 diffuse;",
  9380. "uniform float opacity;",
  9381. "uniform float dashSize;",
  9382. "uniform float totalSize;",
  9383. "varying float vLineDistance;",
  9384. THREE.ShaderChunk[ "color_pars_fragment" ],
  9385. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9386. "void main() {",
  9387. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  9388. "discard;",
  9389. "}",
  9390. "gl_FragColor = vec4( diffuse, opacity );",
  9391. THREE.ShaderChunk[ "color_fragment" ],
  9392. THREE.ShaderChunk[ "fog_fragment" ],
  9393. "}"
  9394. ].join("\n")
  9395. },
  9396. // Depth encoding into RGBA texture
  9397. // based on SpiderGL shadow map example
  9398. // http://spidergl.org/example.php?id=6
  9399. // originally from
  9400. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  9401. // see also here:
  9402. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  9403. 'depthRGBA': {
  9404. uniforms: {},
  9405. vertexShader: [
  9406. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9407. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9408. "void main() {",
  9409. THREE.ShaderChunk[ "skinbase_vertex" ],
  9410. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9411. THREE.ShaderChunk[ "skinning_vertex" ],
  9412. THREE.ShaderChunk[ "default_vertex" ],
  9413. "}"
  9414. ].join("\n"),
  9415. fragmentShader: [
  9416. "vec4 pack_depth( const in float depth ) {",
  9417. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  9418. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  9419. "vec4 res = fract( depth * bit_shift );",
  9420. "res -= res.xxyz * bit_mask;",
  9421. "return res;",
  9422. "}",
  9423. "void main() {",
  9424. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  9425. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  9426. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  9427. //"gl_FragData[ 0 ] = pack_depth( z );",
  9428. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  9429. "}"
  9430. ].join("\n")
  9431. }
  9432. };
  9433. /**
  9434. * @author supereggbert / http://www.paulbrunt.co.uk/
  9435. * @author mrdoob / http://mrdoob.com/
  9436. * @author alteredq / http://alteredqualia.com/
  9437. * @author szimek / https://github.com/szimek/
  9438. */
  9439. THREE.WebGLRenderer = function ( parameters ) {
  9440. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9441. parameters = parameters || {};
  9442. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  9443. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  9444. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  9445. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  9446. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  9447. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  9448. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  9449. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  9450. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  9451. // public properties
  9452. this.domElement = _canvas;
  9453. this.context = null;
  9454. // clearing
  9455. this.autoClear = true;
  9456. this.autoClearColor = true;
  9457. this.autoClearDepth = true;
  9458. this.autoClearStencil = true;
  9459. // scene graph
  9460. this.sortObjects = true;
  9461. this.autoUpdateObjects = true;
  9462. this.autoUpdateScene = true;
  9463. // physically based shading
  9464. this.gammaInput = false;
  9465. this.gammaOutput = false;
  9466. this.physicallyBasedShading = false;
  9467. // shadow map
  9468. this.shadowMapEnabled = false;
  9469. this.shadowMapAutoUpdate = true;
  9470. this.shadowMapSoft = true;
  9471. this.shadowMapCullFrontFaces = true;
  9472. this.shadowMapDebug = false;
  9473. this.shadowMapCascade = false;
  9474. // morphs
  9475. this.maxMorphTargets = 8;
  9476. this.maxMorphNormals = 4;
  9477. // flags
  9478. this.autoScaleCubemaps = true;
  9479. // custom render plugins
  9480. this.renderPluginsPre = [];
  9481. this.renderPluginsPost = [];
  9482. // info
  9483. this.info = {
  9484. memory: {
  9485. programs: 0,
  9486. geometries: 0,
  9487. textures: 0
  9488. },
  9489. render: {
  9490. calls: 0,
  9491. vertices: 0,
  9492. faces: 0,
  9493. points: 0
  9494. }
  9495. };
  9496. // internal properties
  9497. var _this = this,
  9498. _programs = [],
  9499. _programs_counter = 0,
  9500. // internal state cache
  9501. _currentProgram = null,
  9502. _currentFramebuffer = null,
  9503. _currentMaterialId = -1,
  9504. _currentGeometryGroupHash = null,
  9505. _currentCamera = null,
  9506. _geometryGroupCounter = 0,
  9507. _usedTextureUnits = 0,
  9508. // GL state cache
  9509. _oldDoubleSided = -1,
  9510. _oldFlipSided = -1,
  9511. _oldBlending = -1,
  9512. _oldBlendEquation = -1,
  9513. _oldBlendSrc = -1,
  9514. _oldBlendDst = -1,
  9515. _oldDepthTest = -1,
  9516. _oldDepthWrite = -1,
  9517. _oldPolygonOffset = null,
  9518. _oldPolygonOffsetFactor = null,
  9519. _oldPolygonOffsetUnits = null,
  9520. _oldLineWidth = null,
  9521. _viewportX = 0,
  9522. _viewportY = 0,
  9523. _viewportWidth = 0,
  9524. _viewportHeight = 0,
  9525. _currentWidth = 0,
  9526. _currentHeight = 0,
  9527. _enabledAttributes = {},
  9528. // frustum
  9529. _frustum = new THREE.Frustum(),
  9530. // camera matrices cache
  9531. _projScreenMatrix = new THREE.Matrix4(),
  9532. _projScreenMatrixPS = new THREE.Matrix4(),
  9533. _vector3 = new THREE.Vector4(),
  9534. // light arrays cache
  9535. _direction = new THREE.Vector3(),
  9536. _lightsNeedUpdate = true,
  9537. _lights = {
  9538. ambient: [ 0, 0, 0 ],
  9539. directional: { length: 0, colors: new Array(), positions: new Array() },
  9540. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9541. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  9542. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9543. };
  9544. // initialize
  9545. var _gl;
  9546. var _glExtensionTextureFloat;
  9547. var _glExtensionStandardDerivatives;
  9548. var _glExtensionTextureFilterAnisotropic;
  9549. var _glExtensionCompressedTextureS3TC;
  9550. initGL();
  9551. setDefaultGLState();
  9552. this.context = _gl;
  9553. // GPU capabilities
  9554. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9555. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9556. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9557. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9558. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9559. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9560. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9561. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  9562. // API
  9563. this.getContext = function () {
  9564. return _gl;
  9565. };
  9566. this.supportsVertexTextures = function () {
  9567. return _supportsVertexTextures;
  9568. };
  9569. this.getMaxAnisotropy = function () {
  9570. return _maxAnisotropy;
  9571. };
  9572. this.setSize = function ( width, height ) {
  9573. _canvas.width = width;
  9574. _canvas.height = height;
  9575. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9576. };
  9577. this.setViewport = function ( x, y, width, height ) {
  9578. _viewportX = x !== undefined ? x : 0;
  9579. _viewportY = y !== undefined ? y : 0;
  9580. _viewportWidth = width !== undefined ? width : _canvas.width;
  9581. _viewportHeight = height !== undefined ? height : _canvas.height;
  9582. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9583. };
  9584. this.setScissor = function ( x, y, width, height ) {
  9585. _gl.scissor( x, y, width, height );
  9586. };
  9587. this.enableScissorTest = function ( enable ) {
  9588. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9589. };
  9590. // Clearing
  9591. this.setClearColorHex = function ( hex, alpha ) {
  9592. _clearColor.setHex( hex );
  9593. _clearAlpha = alpha;
  9594. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9595. };
  9596. this.setClearColor = function ( color, alpha ) {
  9597. _clearColor.copy( color );
  9598. _clearAlpha = alpha;
  9599. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9600. };
  9601. this.getClearColor = function () {
  9602. return _clearColor;
  9603. };
  9604. this.getClearAlpha = function () {
  9605. return _clearAlpha;
  9606. };
  9607. this.clear = function ( color, depth, stencil ) {
  9608. var bits = 0;
  9609. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9610. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9611. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9612. _gl.clear( bits );
  9613. };
  9614. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9615. this.setRenderTarget( renderTarget );
  9616. this.clear( color, depth, stencil );
  9617. };
  9618. // Plugins
  9619. this.addPostPlugin = function ( plugin ) {
  9620. plugin.init( this );
  9621. this.renderPluginsPost.push( plugin );
  9622. };
  9623. this.addPrePlugin = function ( plugin ) {
  9624. plugin.init( this );
  9625. this.renderPluginsPre.push( plugin );
  9626. };
  9627. // Deallocation
  9628. this.deallocateObject = function ( object ) {
  9629. if ( ! object.__webglInit ) return;
  9630. object.__webglInit = false;
  9631. delete object._modelViewMatrix;
  9632. delete object._normalMatrix;
  9633. if ( object instanceof THREE.Mesh ) {
  9634. for ( var g in object.geometry.geometryGroups ) {
  9635. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9636. }
  9637. } else if ( object instanceof THREE.Ribbon ) {
  9638. deleteRibbonBuffers( object.geometry );
  9639. } else if ( object instanceof THREE.Line ) {
  9640. deleteLineBuffers( object.geometry );
  9641. } else if ( object instanceof THREE.ParticleSystem ) {
  9642. deleteParticleBuffers( object.geometry );
  9643. }
  9644. };
  9645. this.deallocateTexture = function ( texture ) {
  9646. if ( ! texture.__webglInit ) return;
  9647. texture.__webglInit = false;
  9648. _gl.deleteTexture( texture.__webglTexture );
  9649. _this.info.memory.textures --;
  9650. };
  9651. this.deallocateRenderTarget = function ( renderTarget ) {
  9652. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9653. _gl.deleteTexture( renderTarget.__webglTexture );
  9654. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9655. for ( var i = 0; i < 6; i ++ ) {
  9656. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9657. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9658. }
  9659. } else {
  9660. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9661. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9662. }
  9663. };
  9664. this.deallocateMaterial = function ( material ) {
  9665. var program = material.program;
  9666. if ( ! program ) return;
  9667. material.program = undefined;
  9668. // only deallocate GL program if this was the last use of shared program
  9669. // assumed there is only single copy of any program in the _programs list
  9670. // (that's how it's constructed)
  9671. var i, il, programInfo;
  9672. var deleteProgram = false;
  9673. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9674. programInfo = _programs[ i ];
  9675. if ( programInfo.program === program ) {
  9676. programInfo.usedTimes --;
  9677. if ( programInfo.usedTimes === 0 ) {
  9678. deleteProgram = true;
  9679. }
  9680. break;
  9681. }
  9682. }
  9683. if ( deleteProgram ) {
  9684. // avoid using array.splice, this is costlier than creating new array from scratch
  9685. var newPrograms = [];
  9686. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9687. programInfo = _programs[ i ];
  9688. if ( programInfo.program !== program ) {
  9689. newPrograms.push( programInfo );
  9690. }
  9691. }
  9692. _programs = newPrograms;
  9693. _gl.deleteProgram( program );
  9694. _this.info.memory.programs --;
  9695. }
  9696. };
  9697. // Rendering
  9698. this.updateShadowMap = function ( scene, camera ) {
  9699. _currentProgram = null;
  9700. _oldBlending = -1;
  9701. _oldDepthTest = -1;
  9702. _oldDepthWrite = -1;
  9703. _currentGeometryGroupHash = -1;
  9704. _currentMaterialId = -1;
  9705. _lightsNeedUpdate = true;
  9706. _oldDoubleSided = -1;
  9707. _oldFlipSided = -1;
  9708. this.shadowMapPlugin.update( scene, camera );
  9709. };
  9710. // Internal functions
  9711. // Buffer allocation
  9712. function createParticleBuffers ( geometry ) {
  9713. geometry.__webglVertexBuffer = _gl.createBuffer();
  9714. geometry.__webglColorBuffer = _gl.createBuffer();
  9715. _this.info.memory.geometries ++;
  9716. };
  9717. function createLineBuffers ( geometry ) {
  9718. geometry.__webglVertexBuffer = _gl.createBuffer();
  9719. geometry.__webglColorBuffer = _gl.createBuffer();
  9720. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  9721. _this.info.memory.geometries ++;
  9722. };
  9723. function createRibbonBuffers ( geometry ) {
  9724. geometry.__webglVertexBuffer = _gl.createBuffer();
  9725. geometry.__webglColorBuffer = _gl.createBuffer();
  9726. geometry.__webglNormalBuffer = _gl.createBuffer();
  9727. _this.info.memory.geometries ++;
  9728. };
  9729. function createMeshBuffers ( geometryGroup ) {
  9730. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9731. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9732. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9733. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9734. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9735. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9736. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9737. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9738. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9739. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9740. var m, ml;
  9741. if ( geometryGroup.numMorphTargets ) {
  9742. geometryGroup.__webglMorphTargetsBuffers = [];
  9743. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9744. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9745. }
  9746. }
  9747. if ( geometryGroup.numMorphNormals ) {
  9748. geometryGroup.__webglMorphNormalsBuffers = [];
  9749. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9750. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9751. }
  9752. }
  9753. _this.info.memory.geometries ++;
  9754. };
  9755. // Buffer deallocation
  9756. function deleteParticleBuffers ( geometry ) {
  9757. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9758. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9759. deleteCustomAttributesBuffers( geometry );
  9760. _this.info.memory.geometries --;
  9761. };
  9762. function deleteLineBuffers ( geometry ) {
  9763. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9764. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9765. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  9766. deleteCustomAttributesBuffers( geometry );
  9767. _this.info.memory.geometries --;
  9768. };
  9769. function deleteRibbonBuffers ( geometry ) {
  9770. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9771. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9772. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  9773. deleteCustomAttributesBuffers( geometry );
  9774. _this.info.memory.geometries --;
  9775. };
  9776. function deleteMeshBuffers ( geometryGroup ) {
  9777. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9778. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9779. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9780. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9781. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9782. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9783. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9784. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9785. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9786. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9787. var m, ml;
  9788. if ( geometryGroup.numMorphTargets ) {
  9789. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9790. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9791. }
  9792. }
  9793. if ( geometryGroup.numMorphNormals ) {
  9794. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9795. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9796. }
  9797. }
  9798. deleteCustomAttributesBuffers( geometryGroup );
  9799. _this.info.memory.geometries --;
  9800. };
  9801. function deleteCustomAttributesBuffers( geometry ) {
  9802. if ( geometry.__webglCustomAttributesList ) {
  9803. for ( var id in geometry.__webglCustomAttributesList ) {
  9804. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  9805. }
  9806. }
  9807. };
  9808. // Buffer initialization
  9809. function initCustomAttributes ( geometry, object ) {
  9810. var nvertices = geometry.vertices.length;
  9811. var material = object.material;
  9812. if ( material.attributes ) {
  9813. if ( geometry.__webglCustomAttributesList === undefined ) {
  9814. geometry.__webglCustomAttributesList = [];
  9815. }
  9816. for ( var a in material.attributes ) {
  9817. var attribute = material.attributes[ a ];
  9818. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9819. attribute.__webglInitialized = true;
  9820. var size = 1; // "f" and "i"
  9821. if ( attribute.type === "v2" ) size = 2;
  9822. else if ( attribute.type === "v3" ) size = 3;
  9823. else if ( attribute.type === "v4" ) size = 4;
  9824. else if ( attribute.type === "c" ) size = 3;
  9825. attribute.size = size;
  9826. attribute.array = new Float32Array( nvertices * size );
  9827. attribute.buffer = _gl.createBuffer();
  9828. attribute.buffer.belongsToAttribute = a;
  9829. attribute.needsUpdate = true;
  9830. }
  9831. geometry.__webglCustomAttributesList.push( attribute );
  9832. }
  9833. }
  9834. };
  9835. function initParticleBuffers ( geometry, object ) {
  9836. var nvertices = geometry.vertices.length;
  9837. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9838. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9839. geometry.__sortArray = [];
  9840. geometry.__webglParticleCount = nvertices;
  9841. initCustomAttributes ( geometry, object );
  9842. };
  9843. function initLineBuffers ( geometry, object ) {
  9844. var nvertices = geometry.vertices.length;
  9845. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9846. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9847. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  9848. geometry.__webglLineCount = nvertices;
  9849. initCustomAttributes ( geometry, object );
  9850. };
  9851. function initRibbonBuffers ( geometry, object ) {
  9852. var nvertices = geometry.vertices.length;
  9853. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9854. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9855. geometry.__normalArray = new Float32Array( nvertices * 3 );
  9856. geometry.__webglVertexCount = nvertices;
  9857. initCustomAttributes ( geometry, object );
  9858. };
  9859. function initMeshBuffers ( geometryGroup, object ) {
  9860. var geometry = object.geometry,
  9861. faces3 = geometryGroup.faces3,
  9862. faces4 = geometryGroup.faces4,
  9863. nvertices = faces3.length * 3 + faces4.length * 4,
  9864. ntris = faces3.length * 1 + faces4.length * 2,
  9865. nlines = faces3.length * 3 + faces4.length * 4,
  9866. material = getBufferMaterial( object, geometryGroup ),
  9867. uvType = bufferGuessUVType( material ),
  9868. normalType = bufferGuessNormalType( material ),
  9869. vertexColorType = bufferGuessVertexColorType( material );
  9870. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9871. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9872. if ( normalType ) {
  9873. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9874. }
  9875. if ( geometry.hasTangents ) {
  9876. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9877. }
  9878. if ( vertexColorType ) {
  9879. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9880. }
  9881. if ( uvType ) {
  9882. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9883. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9884. }
  9885. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9886. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9887. }
  9888. }
  9889. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9890. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9891. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9892. }
  9893. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9894. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9895. var m, ml;
  9896. if ( geometryGroup.numMorphTargets ) {
  9897. geometryGroup.__morphTargetsArrays = [];
  9898. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9899. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9900. }
  9901. }
  9902. if ( geometryGroup.numMorphNormals ) {
  9903. geometryGroup.__morphNormalsArrays = [];
  9904. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9905. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9906. }
  9907. }
  9908. geometryGroup.__webglFaceCount = ntris * 3;
  9909. geometryGroup.__webglLineCount = nlines * 2;
  9910. // custom attributes
  9911. if ( material.attributes ) {
  9912. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9913. geometryGroup.__webglCustomAttributesList = [];
  9914. }
  9915. for ( var a in material.attributes ) {
  9916. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9917. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9918. var originalAttribute = material.attributes[ a ];
  9919. var attribute = {};
  9920. for ( var property in originalAttribute ) {
  9921. attribute[ property ] = originalAttribute[ property ];
  9922. }
  9923. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9924. attribute.__webglInitialized = true;
  9925. var size = 1; // "f" and "i"
  9926. if( attribute.type === "v2" ) size = 2;
  9927. else if( attribute.type === "v3" ) size = 3;
  9928. else if( attribute.type === "v4" ) size = 4;
  9929. else if( attribute.type === "c" ) size = 3;
  9930. attribute.size = size;
  9931. attribute.array = new Float32Array( nvertices * size );
  9932. attribute.buffer = _gl.createBuffer();
  9933. attribute.buffer.belongsToAttribute = a;
  9934. originalAttribute.needsUpdate = true;
  9935. attribute.__original = originalAttribute;
  9936. }
  9937. geometryGroup.__webglCustomAttributesList.push( attribute );
  9938. }
  9939. }
  9940. geometryGroup.__inittedArrays = true;
  9941. };
  9942. function getBufferMaterial( object, geometryGroup ) {
  9943. return object.material instanceof THREE.MeshFaceMaterial
  9944. ? object.material.materials[ geometryGroup.materialIndex ]
  9945. : object.material;
  9946. };
  9947. function materialNeedsSmoothNormals ( material ) {
  9948. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9949. };
  9950. function bufferGuessNormalType ( material ) {
  9951. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9952. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9953. return false;
  9954. }
  9955. if ( materialNeedsSmoothNormals( material ) ) {
  9956. return THREE.SmoothShading;
  9957. } else {
  9958. return THREE.FlatShading;
  9959. }
  9960. };
  9961. function bufferGuessVertexColorType ( material ) {
  9962. if ( material.vertexColors ) {
  9963. return material.vertexColors;
  9964. }
  9965. return false;
  9966. };
  9967. function bufferGuessUVType ( material ) {
  9968. // material must use some texture to require uvs
  9969. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9970. return true;
  9971. }
  9972. return false;
  9973. };
  9974. //
  9975. function initDirectBuffers( geometry ) {
  9976. var a, attribute, type;
  9977. for ( a in geometry.attributes ) {
  9978. if ( a === "index" ) {
  9979. type = _gl.ELEMENT_ARRAY_BUFFER;
  9980. } else {
  9981. type = _gl.ARRAY_BUFFER;
  9982. }
  9983. attribute = geometry.attributes[ a ];
  9984. attribute.buffer = _gl.createBuffer();
  9985. _gl.bindBuffer( type, attribute.buffer );
  9986. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9987. }
  9988. };
  9989. // Buffer setting
  9990. function setParticleBuffers ( geometry, hint, object ) {
  9991. var v, c, vertex, offset, index, color,
  9992. vertices = geometry.vertices,
  9993. vl = vertices.length,
  9994. colors = geometry.colors,
  9995. cl = colors.length,
  9996. vertexArray = geometry.__vertexArray,
  9997. colorArray = geometry.__colorArray,
  9998. sortArray = geometry.__sortArray,
  9999. dirtyVertices = geometry.verticesNeedUpdate,
  10000. dirtyElements = geometry.elementsNeedUpdate,
  10001. dirtyColors = geometry.colorsNeedUpdate,
  10002. customAttributes = geometry.__webglCustomAttributesList,
  10003. i, il,
  10004. a, ca, cal, value,
  10005. customAttribute;
  10006. if ( object.sortParticles ) {
  10007. _projScreenMatrixPS.copy( _projScreenMatrix );
  10008. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  10009. for ( v = 0; v < vl; v ++ ) {
  10010. vertex = vertices[ v ];
  10011. _vector3.copy( vertex );
  10012. _projScreenMatrixPS.multiplyVector3( _vector3 );
  10013. sortArray[ v ] = [ _vector3.z, v ];
  10014. }
  10015. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  10016. for ( v = 0; v < vl; v ++ ) {
  10017. vertex = vertices[ sortArray[v][1] ];
  10018. offset = v * 3;
  10019. vertexArray[ offset ] = vertex.x;
  10020. vertexArray[ offset + 1 ] = vertex.y;
  10021. vertexArray[ offset + 2 ] = vertex.z;
  10022. }
  10023. for ( c = 0; c < cl; c ++ ) {
  10024. offset = c * 3;
  10025. color = colors[ sortArray[c][1] ];
  10026. colorArray[ offset ] = color.r;
  10027. colorArray[ offset + 1 ] = color.g;
  10028. colorArray[ offset + 2 ] = color.b;
  10029. }
  10030. if ( customAttributes ) {
  10031. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10032. customAttribute = customAttributes[ i ];
  10033. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10034. offset = 0;
  10035. cal = customAttribute.value.length;
  10036. if ( customAttribute.size === 1 ) {
  10037. for ( ca = 0; ca < cal; ca ++ ) {
  10038. index = sortArray[ ca ][ 1 ];
  10039. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10040. }
  10041. } else if ( customAttribute.size === 2 ) {
  10042. for ( ca = 0; ca < cal; ca ++ ) {
  10043. index = sortArray[ ca ][ 1 ];
  10044. value = customAttribute.value[ index ];
  10045. customAttribute.array[ offset ] = value.x;
  10046. customAttribute.array[ offset + 1 ] = value.y;
  10047. offset += 2;
  10048. }
  10049. } else if ( customAttribute.size === 3 ) {
  10050. if ( customAttribute.type === "c" ) {
  10051. for ( ca = 0; ca < cal; ca ++ ) {
  10052. index = sortArray[ ca ][ 1 ];
  10053. value = customAttribute.value[ index ];
  10054. customAttribute.array[ offset ] = value.r;
  10055. customAttribute.array[ offset + 1 ] = value.g;
  10056. customAttribute.array[ offset + 2 ] = value.b;
  10057. offset += 3;
  10058. }
  10059. } else {
  10060. for ( ca = 0; ca < cal; ca ++ ) {
  10061. index = sortArray[ ca ][ 1 ];
  10062. value = customAttribute.value[ index ];
  10063. customAttribute.array[ offset ] = value.x;
  10064. customAttribute.array[ offset + 1 ] = value.y;
  10065. customAttribute.array[ offset + 2 ] = value.z;
  10066. offset += 3;
  10067. }
  10068. }
  10069. } else if ( customAttribute.size === 4 ) {
  10070. for ( ca = 0; ca < cal; ca ++ ) {
  10071. index = sortArray[ ca ][ 1 ];
  10072. value = customAttribute.value[ index ];
  10073. customAttribute.array[ offset ] = value.x;
  10074. customAttribute.array[ offset + 1 ] = value.y;
  10075. customAttribute.array[ offset + 2 ] = value.z;
  10076. customAttribute.array[ offset + 3 ] = value.w;
  10077. offset += 4;
  10078. }
  10079. }
  10080. }
  10081. }
  10082. } else {
  10083. if ( dirtyVertices ) {
  10084. for ( v = 0; v < vl; v ++ ) {
  10085. vertex = vertices[ v ];
  10086. offset = v * 3;
  10087. vertexArray[ offset ] = vertex.x;
  10088. vertexArray[ offset + 1 ] = vertex.y;
  10089. vertexArray[ offset + 2 ] = vertex.z;
  10090. }
  10091. }
  10092. if ( dirtyColors ) {
  10093. for ( c = 0; c < cl; c ++ ) {
  10094. color = colors[ c ];
  10095. offset = c * 3;
  10096. colorArray[ offset ] = color.r;
  10097. colorArray[ offset + 1 ] = color.g;
  10098. colorArray[ offset + 2 ] = color.b;
  10099. }
  10100. }
  10101. if ( customAttributes ) {
  10102. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10103. customAttribute = customAttributes[ i ];
  10104. if ( customAttribute.needsUpdate &&
  10105. ( customAttribute.boundTo === undefined ||
  10106. customAttribute.boundTo === "vertices") ) {
  10107. cal = customAttribute.value.length;
  10108. offset = 0;
  10109. if ( customAttribute.size === 1 ) {
  10110. for ( ca = 0; ca < cal; ca ++ ) {
  10111. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10112. }
  10113. } else if ( customAttribute.size === 2 ) {
  10114. for ( ca = 0; ca < cal; ca ++ ) {
  10115. value = customAttribute.value[ ca ];
  10116. customAttribute.array[ offset ] = value.x;
  10117. customAttribute.array[ offset + 1 ] = value.y;
  10118. offset += 2;
  10119. }
  10120. } else if ( customAttribute.size === 3 ) {
  10121. if ( customAttribute.type === "c" ) {
  10122. for ( ca = 0; ca < cal; ca ++ ) {
  10123. value = customAttribute.value[ ca ];
  10124. customAttribute.array[ offset ] = value.r;
  10125. customAttribute.array[ offset + 1 ] = value.g;
  10126. customAttribute.array[ offset + 2 ] = value.b;
  10127. offset += 3;
  10128. }
  10129. } else {
  10130. for ( ca = 0; ca < cal; ca ++ ) {
  10131. value = customAttribute.value[ ca ];
  10132. customAttribute.array[ offset ] = value.x;
  10133. customAttribute.array[ offset + 1 ] = value.y;
  10134. customAttribute.array[ offset + 2 ] = value.z;
  10135. offset += 3;
  10136. }
  10137. }
  10138. } else if ( customAttribute.size === 4 ) {
  10139. for ( ca = 0; ca < cal; ca ++ ) {
  10140. value = customAttribute.value[ ca ];
  10141. customAttribute.array[ offset ] = value.x;
  10142. customAttribute.array[ offset + 1 ] = value.y;
  10143. customAttribute.array[ offset + 2 ] = value.z;
  10144. customAttribute.array[ offset + 3 ] = value.w;
  10145. offset += 4;
  10146. }
  10147. }
  10148. }
  10149. }
  10150. }
  10151. }
  10152. if ( dirtyVertices || object.sortParticles ) {
  10153. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10154. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10155. }
  10156. if ( dirtyColors || object.sortParticles ) {
  10157. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10158. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10159. }
  10160. if ( customAttributes ) {
  10161. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10162. customAttribute = customAttributes[ i ];
  10163. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10164. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10165. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10166. }
  10167. }
  10168. }
  10169. };
  10170. function setLineBuffers ( geometry, hint ) {
  10171. var v, c, d, vertex, offset, color,
  10172. vertices = geometry.vertices,
  10173. colors = geometry.colors,
  10174. lineDistances = geometry.lineDistances,
  10175. vl = vertices.length,
  10176. cl = colors.length,
  10177. dl = lineDistances.length,
  10178. vertexArray = geometry.__vertexArray,
  10179. colorArray = geometry.__colorArray,
  10180. lineDistanceArray = geometry.__lineDistanceArray,
  10181. dirtyVertices = geometry.verticesNeedUpdate,
  10182. dirtyColors = geometry.colorsNeedUpdate,
  10183. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10184. customAttributes = geometry.__webglCustomAttributesList,
  10185. i, il,
  10186. a, ca, cal, value,
  10187. customAttribute;
  10188. if ( dirtyVertices ) {
  10189. for ( v = 0; v < vl; v ++ ) {
  10190. vertex = vertices[ v ];
  10191. offset = v * 3;
  10192. vertexArray[ offset ] = vertex.x;
  10193. vertexArray[ offset + 1 ] = vertex.y;
  10194. vertexArray[ offset + 2 ] = vertex.z;
  10195. }
  10196. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10197. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10198. }
  10199. if ( dirtyColors ) {
  10200. for ( c = 0; c < cl; c ++ ) {
  10201. color = colors[ c ];
  10202. offset = c * 3;
  10203. colorArray[ offset ] = color.r;
  10204. colorArray[ offset + 1 ] = color.g;
  10205. colorArray[ offset + 2 ] = color.b;
  10206. }
  10207. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10208. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10209. }
  10210. if ( dirtyLineDistances ) {
  10211. for ( d = 0; d < dl; d ++ ) {
  10212. lineDistanceArray[ d ] = lineDistances[ d ];
  10213. }
  10214. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10215. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10216. }
  10217. if ( customAttributes ) {
  10218. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10219. customAttribute = customAttributes[ i ];
  10220. if ( customAttribute.needsUpdate &&
  10221. ( customAttribute.boundTo === undefined ||
  10222. customAttribute.boundTo === "vertices" ) ) {
  10223. offset = 0;
  10224. cal = customAttribute.value.length;
  10225. if ( customAttribute.size === 1 ) {
  10226. for ( ca = 0; ca < cal; ca ++ ) {
  10227. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10228. }
  10229. } else if ( customAttribute.size === 2 ) {
  10230. for ( ca = 0; ca < cal; ca ++ ) {
  10231. value = customAttribute.value[ ca ];
  10232. customAttribute.array[ offset ] = value.x;
  10233. customAttribute.array[ offset + 1 ] = value.y;
  10234. offset += 2;
  10235. }
  10236. } else if ( customAttribute.size === 3 ) {
  10237. if ( customAttribute.type === "c" ) {
  10238. for ( ca = 0; ca < cal; ca ++ ) {
  10239. value = customAttribute.value[ ca ];
  10240. customAttribute.array[ offset ] = value.r;
  10241. customAttribute.array[ offset + 1 ] = value.g;
  10242. customAttribute.array[ offset + 2 ] = value.b;
  10243. offset += 3;
  10244. }
  10245. } else {
  10246. for ( ca = 0; ca < cal; ca ++ ) {
  10247. value = customAttribute.value[ ca ];
  10248. customAttribute.array[ offset ] = value.x;
  10249. customAttribute.array[ offset + 1 ] = value.y;
  10250. customAttribute.array[ offset + 2 ] = value.z;
  10251. offset += 3;
  10252. }
  10253. }
  10254. } else if ( customAttribute.size === 4 ) {
  10255. for ( ca = 0; ca < cal; ca ++ ) {
  10256. value = customAttribute.value[ ca ];
  10257. customAttribute.array[ offset ] = value.x;
  10258. customAttribute.array[ offset + 1 ] = value.y;
  10259. customAttribute.array[ offset + 2 ] = value.z;
  10260. customAttribute.array[ offset + 3 ] = value.w;
  10261. offset += 4;
  10262. }
  10263. }
  10264. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10265. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10266. }
  10267. }
  10268. }
  10269. };
  10270. function setRibbonBuffers ( geometry, hint ) {
  10271. var v, c, n, vertex, offset, color, normal,
  10272. i, il, ca, cal, customAttribute, value,
  10273. vertices = geometry.vertices,
  10274. colors = geometry.colors,
  10275. normals = geometry.normals,
  10276. vl = vertices.length,
  10277. cl = colors.length,
  10278. nl = normals.length,
  10279. vertexArray = geometry.__vertexArray,
  10280. colorArray = geometry.__colorArray,
  10281. normalArray = geometry.__normalArray,
  10282. dirtyVertices = geometry.verticesNeedUpdate,
  10283. dirtyColors = geometry.colorsNeedUpdate,
  10284. dirtyNormals = geometry.normalsNeedUpdate,
  10285. customAttributes = geometry.__webglCustomAttributesList;
  10286. if ( dirtyVertices ) {
  10287. for ( v = 0; v < vl; v ++ ) {
  10288. vertex = vertices[ v ];
  10289. offset = v * 3;
  10290. vertexArray[ offset ] = vertex.x;
  10291. vertexArray[ offset + 1 ] = vertex.y;
  10292. vertexArray[ offset + 2 ] = vertex.z;
  10293. }
  10294. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10295. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10296. }
  10297. if ( dirtyColors ) {
  10298. for ( c = 0; c < cl; c ++ ) {
  10299. color = colors[ c ];
  10300. offset = c * 3;
  10301. colorArray[ offset ] = color.r;
  10302. colorArray[ offset + 1 ] = color.g;
  10303. colorArray[ offset + 2 ] = color.b;
  10304. }
  10305. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10306. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10307. }
  10308. if ( dirtyNormals ) {
  10309. for ( n = 0; n < nl; n ++ ) {
  10310. normal = normals[ n ];
  10311. offset = n * 3;
  10312. normalArray[ offset ] = normal.x;
  10313. normalArray[ offset + 1 ] = normal.y;
  10314. normalArray[ offset + 2 ] = normal.z;
  10315. }
  10316. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  10317. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10318. }
  10319. if ( customAttributes ) {
  10320. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10321. customAttribute = customAttributes[ i ];
  10322. if ( customAttribute.needsUpdate &&
  10323. ( customAttribute.boundTo === undefined ||
  10324. customAttribute.boundTo === "vertices" ) ) {
  10325. offset = 0;
  10326. cal = customAttribute.value.length;
  10327. if ( customAttribute.size === 1 ) {
  10328. for ( ca = 0; ca < cal; ca ++ ) {
  10329. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10330. }
  10331. } else if ( customAttribute.size === 2 ) {
  10332. for ( ca = 0; ca < cal; ca ++ ) {
  10333. value = customAttribute.value[ ca ];
  10334. customAttribute.array[ offset ] = value.x;
  10335. customAttribute.array[ offset + 1 ] = value.y;
  10336. offset += 2;
  10337. }
  10338. } else if ( customAttribute.size === 3 ) {
  10339. if ( customAttribute.type === "c" ) {
  10340. for ( ca = 0; ca < cal; ca ++ ) {
  10341. value = customAttribute.value[ ca ];
  10342. customAttribute.array[ offset ] = value.r;
  10343. customAttribute.array[ offset + 1 ] = value.g;
  10344. customAttribute.array[ offset + 2 ] = value.b;
  10345. offset += 3;
  10346. }
  10347. } else {
  10348. for ( ca = 0; ca < cal; ca ++ ) {
  10349. value = customAttribute.value[ ca ];
  10350. customAttribute.array[ offset ] = value.x;
  10351. customAttribute.array[ offset + 1 ] = value.y;
  10352. customAttribute.array[ offset + 2 ] = value.z;
  10353. offset += 3;
  10354. }
  10355. }
  10356. } else if ( customAttribute.size === 4 ) {
  10357. for ( ca = 0; ca < cal; ca ++ ) {
  10358. value = customAttribute.value[ ca ];
  10359. customAttribute.array[ offset ] = value.x;
  10360. customAttribute.array[ offset + 1 ] = value.y;
  10361. customAttribute.array[ offset + 2 ] = value.z;
  10362. customAttribute.array[ offset + 3 ] = value.w;
  10363. offset += 4;
  10364. }
  10365. }
  10366. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10367. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10368. }
  10369. }
  10370. }
  10371. };
  10372. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  10373. if ( ! geometryGroup.__inittedArrays ) {
  10374. return;
  10375. }
  10376. var normalType = bufferGuessNormalType( material ),
  10377. vertexColorType = bufferGuessVertexColorType( material ),
  10378. uvType = bufferGuessUVType( material ),
  10379. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  10380. var f, fl, fi, face,
  10381. vertexNormals, faceNormal, normal,
  10382. vertexColors, faceColor,
  10383. vertexTangents,
  10384. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  10385. c1, c2, c3, c4,
  10386. sw1, sw2, sw3, sw4,
  10387. si1, si2, si3, si4,
  10388. sa1, sa2, sa3, sa4,
  10389. sb1, sb2, sb3, sb4,
  10390. m, ml, i, il,
  10391. vn, uvi, uv2i,
  10392. vk, vkl, vka,
  10393. nka, chf, faceVertexNormals,
  10394. a,
  10395. vertexIndex = 0,
  10396. offset = 0,
  10397. offset_uv = 0,
  10398. offset_uv2 = 0,
  10399. offset_face = 0,
  10400. offset_normal = 0,
  10401. offset_tangent = 0,
  10402. offset_line = 0,
  10403. offset_color = 0,
  10404. offset_skin = 0,
  10405. offset_morphTarget = 0,
  10406. offset_custom = 0,
  10407. offset_customSrc = 0,
  10408. value,
  10409. vertexArray = geometryGroup.__vertexArray,
  10410. uvArray = geometryGroup.__uvArray,
  10411. uv2Array = geometryGroup.__uv2Array,
  10412. normalArray = geometryGroup.__normalArray,
  10413. tangentArray = geometryGroup.__tangentArray,
  10414. colorArray = geometryGroup.__colorArray,
  10415. skinIndexArray = geometryGroup.__skinIndexArray,
  10416. skinWeightArray = geometryGroup.__skinWeightArray,
  10417. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  10418. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  10419. customAttributes = geometryGroup.__webglCustomAttributesList,
  10420. customAttribute,
  10421. faceArray = geometryGroup.__faceArray,
  10422. lineArray = geometryGroup.__lineArray,
  10423. geometry = object.geometry, // this is shared for all chunks
  10424. dirtyVertices = geometry.verticesNeedUpdate,
  10425. dirtyElements = geometry.elementsNeedUpdate,
  10426. dirtyUvs = geometry.uvsNeedUpdate,
  10427. dirtyNormals = geometry.normalsNeedUpdate,
  10428. dirtyTangents = geometry.tangentsNeedUpdate,
  10429. dirtyColors = geometry.colorsNeedUpdate,
  10430. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  10431. vertices = geometry.vertices,
  10432. chunk_faces3 = geometryGroup.faces3,
  10433. chunk_faces4 = geometryGroup.faces4,
  10434. obj_faces = geometry.faces,
  10435. obj_uvs = geometry.faceVertexUvs[ 0 ],
  10436. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  10437. obj_colors = geometry.colors,
  10438. obj_skinIndices = geometry.skinIndices,
  10439. obj_skinWeights = geometry.skinWeights,
  10440. morphTargets = geometry.morphTargets,
  10441. morphNormals = geometry.morphNormals;
  10442. if ( dirtyVertices ) {
  10443. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10444. face = obj_faces[ chunk_faces3[ f ] ];
  10445. v1 = vertices[ face.a ];
  10446. v2 = vertices[ face.b ];
  10447. v3 = vertices[ face.c ];
  10448. vertexArray[ offset ] = v1.x;
  10449. vertexArray[ offset + 1 ] = v1.y;
  10450. vertexArray[ offset + 2 ] = v1.z;
  10451. vertexArray[ offset + 3 ] = v2.x;
  10452. vertexArray[ offset + 4 ] = v2.y;
  10453. vertexArray[ offset + 5 ] = v2.z;
  10454. vertexArray[ offset + 6 ] = v3.x;
  10455. vertexArray[ offset + 7 ] = v3.y;
  10456. vertexArray[ offset + 8 ] = v3.z;
  10457. offset += 9;
  10458. }
  10459. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10460. face = obj_faces[ chunk_faces4[ f ] ];
  10461. v1 = vertices[ face.a ];
  10462. v2 = vertices[ face.b ];
  10463. v3 = vertices[ face.c ];
  10464. v4 = vertices[ face.d ];
  10465. vertexArray[ offset ] = v1.x;
  10466. vertexArray[ offset + 1 ] = v1.y;
  10467. vertexArray[ offset + 2 ] = v1.z;
  10468. vertexArray[ offset + 3 ] = v2.x;
  10469. vertexArray[ offset + 4 ] = v2.y;
  10470. vertexArray[ offset + 5 ] = v2.z;
  10471. vertexArray[ offset + 6 ] = v3.x;
  10472. vertexArray[ offset + 7 ] = v3.y;
  10473. vertexArray[ offset + 8 ] = v3.z;
  10474. vertexArray[ offset + 9 ] = v4.x;
  10475. vertexArray[ offset + 10 ] = v4.y;
  10476. vertexArray[ offset + 11 ] = v4.z;
  10477. offset += 12;
  10478. }
  10479. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10480. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10481. }
  10482. if ( dirtyMorphTargets ) {
  10483. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  10484. offset_morphTarget = 0;
  10485. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10486. chf = chunk_faces3[ f ];
  10487. face = obj_faces[ chf ];
  10488. // morph positions
  10489. v1 = morphTargets[ vk ].vertices[ face.a ];
  10490. v2 = morphTargets[ vk ].vertices[ face.b ];
  10491. v3 = morphTargets[ vk ].vertices[ face.c ];
  10492. vka = morphTargetsArrays[ vk ];
  10493. vka[ offset_morphTarget ] = v1.x;
  10494. vka[ offset_morphTarget + 1 ] = v1.y;
  10495. vka[ offset_morphTarget + 2 ] = v1.z;
  10496. vka[ offset_morphTarget + 3 ] = v2.x;
  10497. vka[ offset_morphTarget + 4 ] = v2.y;
  10498. vka[ offset_morphTarget + 5 ] = v2.z;
  10499. vka[ offset_morphTarget + 6 ] = v3.x;
  10500. vka[ offset_morphTarget + 7 ] = v3.y;
  10501. vka[ offset_morphTarget + 8 ] = v3.z;
  10502. // morph normals
  10503. if ( material.morphNormals ) {
  10504. if ( needsSmoothNormals ) {
  10505. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10506. n1 = faceVertexNormals.a;
  10507. n2 = faceVertexNormals.b;
  10508. n3 = faceVertexNormals.c;
  10509. } else {
  10510. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10511. n2 = n1;
  10512. n3 = n1;
  10513. }
  10514. nka = morphNormalsArrays[ vk ];
  10515. nka[ offset_morphTarget ] = n1.x;
  10516. nka[ offset_morphTarget + 1 ] = n1.y;
  10517. nka[ offset_morphTarget + 2 ] = n1.z;
  10518. nka[ offset_morphTarget + 3 ] = n2.x;
  10519. nka[ offset_morphTarget + 4 ] = n2.y;
  10520. nka[ offset_morphTarget + 5 ] = n2.z;
  10521. nka[ offset_morphTarget + 6 ] = n3.x;
  10522. nka[ offset_morphTarget + 7 ] = n3.y;
  10523. nka[ offset_morphTarget + 8 ] = n3.z;
  10524. }
  10525. //
  10526. offset_morphTarget += 9;
  10527. }
  10528. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10529. chf = chunk_faces4[ f ];
  10530. face = obj_faces[ chf ];
  10531. // morph positions
  10532. v1 = morphTargets[ vk ].vertices[ face.a ];
  10533. v2 = morphTargets[ vk ].vertices[ face.b ];
  10534. v3 = morphTargets[ vk ].vertices[ face.c ];
  10535. v4 = morphTargets[ vk ].vertices[ face.d ];
  10536. vka = morphTargetsArrays[ vk ];
  10537. vka[ offset_morphTarget ] = v1.x;
  10538. vka[ offset_morphTarget + 1 ] = v1.y;
  10539. vka[ offset_morphTarget + 2 ] = v1.z;
  10540. vka[ offset_morphTarget + 3 ] = v2.x;
  10541. vka[ offset_morphTarget + 4 ] = v2.y;
  10542. vka[ offset_morphTarget + 5 ] = v2.z;
  10543. vka[ offset_morphTarget + 6 ] = v3.x;
  10544. vka[ offset_morphTarget + 7 ] = v3.y;
  10545. vka[ offset_morphTarget + 8 ] = v3.z;
  10546. vka[ offset_morphTarget + 9 ] = v4.x;
  10547. vka[ offset_morphTarget + 10 ] = v4.y;
  10548. vka[ offset_morphTarget + 11 ] = v4.z;
  10549. // morph normals
  10550. if ( material.morphNormals ) {
  10551. if ( needsSmoothNormals ) {
  10552. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10553. n1 = faceVertexNormals.a;
  10554. n2 = faceVertexNormals.b;
  10555. n3 = faceVertexNormals.c;
  10556. n4 = faceVertexNormals.d;
  10557. } else {
  10558. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10559. n2 = n1;
  10560. n3 = n1;
  10561. n4 = n1;
  10562. }
  10563. nka = morphNormalsArrays[ vk ];
  10564. nka[ offset_morphTarget ] = n1.x;
  10565. nka[ offset_morphTarget + 1 ] = n1.y;
  10566. nka[ offset_morphTarget + 2 ] = n1.z;
  10567. nka[ offset_morphTarget + 3 ] = n2.x;
  10568. nka[ offset_morphTarget + 4 ] = n2.y;
  10569. nka[ offset_morphTarget + 5 ] = n2.z;
  10570. nka[ offset_morphTarget + 6 ] = n3.x;
  10571. nka[ offset_morphTarget + 7 ] = n3.y;
  10572. nka[ offset_morphTarget + 8 ] = n3.z;
  10573. nka[ offset_morphTarget + 9 ] = n4.x;
  10574. nka[ offset_morphTarget + 10 ] = n4.y;
  10575. nka[ offset_morphTarget + 11 ] = n4.z;
  10576. }
  10577. //
  10578. offset_morphTarget += 12;
  10579. }
  10580. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10581. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10582. if ( material.morphNormals ) {
  10583. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10584. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10585. }
  10586. }
  10587. }
  10588. if ( obj_skinWeights.length ) {
  10589. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10590. face = obj_faces[ chunk_faces3[ f ] ];
  10591. // weights
  10592. sw1 = obj_skinWeights[ face.a ];
  10593. sw2 = obj_skinWeights[ face.b ];
  10594. sw3 = obj_skinWeights[ face.c ];
  10595. skinWeightArray[ offset_skin ] = sw1.x;
  10596. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10597. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10598. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10599. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10600. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10601. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10602. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10603. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10604. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10605. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10606. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10607. // indices
  10608. si1 = obj_skinIndices[ face.a ];
  10609. si2 = obj_skinIndices[ face.b ];
  10610. si3 = obj_skinIndices[ face.c ];
  10611. skinIndexArray[ offset_skin ] = si1.x;
  10612. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10613. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10614. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10615. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10616. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10617. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10618. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10619. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10620. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10621. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10622. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10623. offset_skin += 12;
  10624. }
  10625. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10626. face = obj_faces[ chunk_faces4[ f ] ];
  10627. // weights
  10628. sw1 = obj_skinWeights[ face.a ];
  10629. sw2 = obj_skinWeights[ face.b ];
  10630. sw3 = obj_skinWeights[ face.c ];
  10631. sw4 = obj_skinWeights[ face.d ];
  10632. skinWeightArray[ offset_skin ] = sw1.x;
  10633. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10634. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10635. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10636. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10637. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10638. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10639. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10640. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10641. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10642. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10643. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10644. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10645. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10646. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10647. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10648. // indices
  10649. si1 = obj_skinIndices[ face.a ];
  10650. si2 = obj_skinIndices[ face.b ];
  10651. si3 = obj_skinIndices[ face.c ];
  10652. si4 = obj_skinIndices[ face.d ];
  10653. skinIndexArray[ offset_skin ] = si1.x;
  10654. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10655. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10656. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10657. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10658. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10659. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10660. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10661. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10662. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10663. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10664. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10665. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10666. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10667. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10668. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10669. offset_skin += 16;
  10670. }
  10671. if ( offset_skin > 0 ) {
  10672. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10673. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10674. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10675. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10676. }
  10677. }
  10678. if ( dirtyColors && vertexColorType ) {
  10679. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10680. face = obj_faces[ chunk_faces3[ f ] ];
  10681. vertexColors = face.vertexColors;
  10682. faceColor = face.color;
  10683. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10684. c1 = vertexColors[ 0 ];
  10685. c2 = vertexColors[ 1 ];
  10686. c3 = vertexColors[ 2 ];
  10687. } else {
  10688. c1 = faceColor;
  10689. c2 = faceColor;
  10690. c3 = faceColor;
  10691. }
  10692. colorArray[ offset_color ] = c1.r;
  10693. colorArray[ offset_color + 1 ] = c1.g;
  10694. colorArray[ offset_color + 2 ] = c1.b;
  10695. colorArray[ offset_color + 3 ] = c2.r;
  10696. colorArray[ offset_color + 4 ] = c2.g;
  10697. colorArray[ offset_color + 5 ] = c2.b;
  10698. colorArray[ offset_color + 6 ] = c3.r;
  10699. colorArray[ offset_color + 7 ] = c3.g;
  10700. colorArray[ offset_color + 8 ] = c3.b;
  10701. offset_color += 9;
  10702. }
  10703. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10704. face = obj_faces[ chunk_faces4[ f ] ];
  10705. vertexColors = face.vertexColors;
  10706. faceColor = face.color;
  10707. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10708. c1 = vertexColors[ 0 ];
  10709. c2 = vertexColors[ 1 ];
  10710. c3 = vertexColors[ 2 ];
  10711. c4 = vertexColors[ 3 ];
  10712. } else {
  10713. c1 = faceColor;
  10714. c2 = faceColor;
  10715. c3 = faceColor;
  10716. c4 = faceColor;
  10717. }
  10718. colorArray[ offset_color ] = c1.r;
  10719. colorArray[ offset_color + 1 ] = c1.g;
  10720. colorArray[ offset_color + 2 ] = c1.b;
  10721. colorArray[ offset_color + 3 ] = c2.r;
  10722. colorArray[ offset_color + 4 ] = c2.g;
  10723. colorArray[ offset_color + 5 ] = c2.b;
  10724. colorArray[ offset_color + 6 ] = c3.r;
  10725. colorArray[ offset_color + 7 ] = c3.g;
  10726. colorArray[ offset_color + 8 ] = c3.b;
  10727. colorArray[ offset_color + 9 ] = c4.r;
  10728. colorArray[ offset_color + 10 ] = c4.g;
  10729. colorArray[ offset_color + 11 ] = c4.b;
  10730. offset_color += 12;
  10731. }
  10732. if ( offset_color > 0 ) {
  10733. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10734. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10735. }
  10736. }
  10737. if ( dirtyTangents && geometry.hasTangents ) {
  10738. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10739. face = obj_faces[ chunk_faces3[ f ] ];
  10740. vertexTangents = face.vertexTangents;
  10741. t1 = vertexTangents[ 0 ];
  10742. t2 = vertexTangents[ 1 ];
  10743. t3 = vertexTangents[ 2 ];
  10744. tangentArray[ offset_tangent ] = t1.x;
  10745. tangentArray[ offset_tangent + 1 ] = t1.y;
  10746. tangentArray[ offset_tangent + 2 ] = t1.z;
  10747. tangentArray[ offset_tangent + 3 ] = t1.w;
  10748. tangentArray[ offset_tangent + 4 ] = t2.x;
  10749. tangentArray[ offset_tangent + 5 ] = t2.y;
  10750. tangentArray[ offset_tangent + 6 ] = t2.z;
  10751. tangentArray[ offset_tangent + 7 ] = t2.w;
  10752. tangentArray[ offset_tangent + 8 ] = t3.x;
  10753. tangentArray[ offset_tangent + 9 ] = t3.y;
  10754. tangentArray[ offset_tangent + 10 ] = t3.z;
  10755. tangentArray[ offset_tangent + 11 ] = t3.w;
  10756. offset_tangent += 12;
  10757. }
  10758. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10759. face = obj_faces[ chunk_faces4[ f ] ];
  10760. vertexTangents = face.vertexTangents;
  10761. t1 = vertexTangents[ 0 ];
  10762. t2 = vertexTangents[ 1 ];
  10763. t3 = vertexTangents[ 2 ];
  10764. t4 = vertexTangents[ 3 ];
  10765. tangentArray[ offset_tangent ] = t1.x;
  10766. tangentArray[ offset_tangent + 1 ] = t1.y;
  10767. tangentArray[ offset_tangent + 2 ] = t1.z;
  10768. tangentArray[ offset_tangent + 3 ] = t1.w;
  10769. tangentArray[ offset_tangent + 4 ] = t2.x;
  10770. tangentArray[ offset_tangent + 5 ] = t2.y;
  10771. tangentArray[ offset_tangent + 6 ] = t2.z;
  10772. tangentArray[ offset_tangent + 7 ] = t2.w;
  10773. tangentArray[ offset_tangent + 8 ] = t3.x;
  10774. tangentArray[ offset_tangent + 9 ] = t3.y;
  10775. tangentArray[ offset_tangent + 10 ] = t3.z;
  10776. tangentArray[ offset_tangent + 11 ] = t3.w;
  10777. tangentArray[ offset_tangent + 12 ] = t4.x;
  10778. tangentArray[ offset_tangent + 13 ] = t4.y;
  10779. tangentArray[ offset_tangent + 14 ] = t4.z;
  10780. tangentArray[ offset_tangent + 15 ] = t4.w;
  10781. offset_tangent += 16;
  10782. }
  10783. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10784. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10785. }
  10786. if ( dirtyNormals && normalType ) {
  10787. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10788. face = obj_faces[ chunk_faces3[ f ] ];
  10789. vertexNormals = face.vertexNormals;
  10790. faceNormal = face.normal;
  10791. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10792. for ( i = 0; i < 3; i ++ ) {
  10793. vn = vertexNormals[ i ];
  10794. normalArray[ offset_normal ] = vn.x;
  10795. normalArray[ offset_normal + 1 ] = vn.y;
  10796. normalArray[ offset_normal + 2 ] = vn.z;
  10797. offset_normal += 3;
  10798. }
  10799. } else {
  10800. for ( i = 0; i < 3; i ++ ) {
  10801. normalArray[ offset_normal ] = faceNormal.x;
  10802. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10803. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10804. offset_normal += 3;
  10805. }
  10806. }
  10807. }
  10808. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10809. face = obj_faces[ chunk_faces4[ f ] ];
  10810. vertexNormals = face.vertexNormals;
  10811. faceNormal = face.normal;
  10812. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10813. for ( i = 0; i < 4; i ++ ) {
  10814. vn = vertexNormals[ i ];
  10815. normalArray[ offset_normal ] = vn.x;
  10816. normalArray[ offset_normal + 1 ] = vn.y;
  10817. normalArray[ offset_normal + 2 ] = vn.z;
  10818. offset_normal += 3;
  10819. }
  10820. } else {
  10821. for ( i = 0; i < 4; i ++ ) {
  10822. normalArray[ offset_normal ] = faceNormal.x;
  10823. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10824. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10825. offset_normal += 3;
  10826. }
  10827. }
  10828. }
  10829. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10830. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10831. }
  10832. if ( dirtyUvs && obj_uvs && uvType ) {
  10833. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10834. fi = chunk_faces3[ f ];
  10835. uv = obj_uvs[ fi ];
  10836. if ( uv === undefined ) continue;
  10837. for ( i = 0; i < 3; i ++ ) {
  10838. uvi = uv[ i ];
  10839. uvArray[ offset_uv ] = uvi.u;
  10840. uvArray[ offset_uv + 1 ] = uvi.v;
  10841. offset_uv += 2;
  10842. }
  10843. }
  10844. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10845. fi = chunk_faces4[ f ];
  10846. uv = obj_uvs[ fi ];
  10847. if ( uv === undefined ) continue;
  10848. for ( i = 0; i < 4; i ++ ) {
  10849. uvi = uv[ i ];
  10850. uvArray[ offset_uv ] = uvi.u;
  10851. uvArray[ offset_uv + 1 ] = uvi.v;
  10852. offset_uv += 2;
  10853. }
  10854. }
  10855. if ( offset_uv > 0 ) {
  10856. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10857. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10858. }
  10859. }
  10860. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10861. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10862. fi = chunk_faces3[ f ];
  10863. uv2 = obj_uvs2[ fi ];
  10864. if ( uv2 === undefined ) continue;
  10865. for ( i = 0; i < 3; i ++ ) {
  10866. uv2i = uv2[ i ];
  10867. uv2Array[ offset_uv2 ] = uv2i.u;
  10868. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10869. offset_uv2 += 2;
  10870. }
  10871. }
  10872. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10873. fi = chunk_faces4[ f ];
  10874. uv2 = obj_uvs2[ fi ];
  10875. if ( uv2 === undefined ) continue;
  10876. for ( i = 0; i < 4; i ++ ) {
  10877. uv2i = uv2[ i ];
  10878. uv2Array[ offset_uv2 ] = uv2i.u;
  10879. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10880. offset_uv2 += 2;
  10881. }
  10882. }
  10883. if ( offset_uv2 > 0 ) {
  10884. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10885. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10886. }
  10887. }
  10888. if ( dirtyElements ) {
  10889. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10890. faceArray[ offset_face ] = vertexIndex;
  10891. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10892. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10893. offset_face += 3;
  10894. lineArray[ offset_line ] = vertexIndex;
  10895. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10896. lineArray[ offset_line + 2 ] = vertexIndex;
  10897. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10898. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10899. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10900. offset_line += 6;
  10901. vertexIndex += 3;
  10902. }
  10903. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10904. faceArray[ offset_face ] = vertexIndex;
  10905. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10906. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10907. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10908. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10909. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10910. offset_face += 6;
  10911. lineArray[ offset_line ] = vertexIndex;
  10912. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10913. lineArray[ offset_line + 2 ] = vertexIndex;
  10914. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10915. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10916. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10917. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10918. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10919. offset_line += 8;
  10920. vertexIndex += 4;
  10921. }
  10922. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10923. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10924. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10925. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10926. }
  10927. if ( customAttributes ) {
  10928. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10929. customAttribute = customAttributes[ i ];
  10930. if ( ! customAttribute.__original.needsUpdate ) continue;
  10931. offset_custom = 0;
  10932. offset_customSrc = 0;
  10933. if ( customAttribute.size === 1 ) {
  10934. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10935. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10936. face = obj_faces[ chunk_faces3[ f ] ];
  10937. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10938. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10939. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10940. offset_custom += 3;
  10941. }
  10942. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10943. face = obj_faces[ chunk_faces4[ f ] ];
  10944. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10945. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10946. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10947. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10948. offset_custom += 4;
  10949. }
  10950. } else if ( customAttribute.boundTo === "faces" ) {
  10951. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10952. value = customAttribute.value[ chunk_faces3[ f ] ];
  10953. customAttribute.array[ offset_custom ] = value;
  10954. customAttribute.array[ offset_custom + 1 ] = value;
  10955. customAttribute.array[ offset_custom + 2 ] = value;
  10956. offset_custom += 3;
  10957. }
  10958. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10959. value = customAttribute.value[ chunk_faces4[ f ] ];
  10960. customAttribute.array[ offset_custom ] = value;
  10961. customAttribute.array[ offset_custom + 1 ] = value;
  10962. customAttribute.array[ offset_custom + 2 ] = value;
  10963. customAttribute.array[ offset_custom + 3 ] = value;
  10964. offset_custom += 4;
  10965. }
  10966. }
  10967. } else if ( customAttribute.size === 2 ) {
  10968. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10969. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10970. face = obj_faces[ chunk_faces3[ f ] ];
  10971. v1 = customAttribute.value[ face.a ];
  10972. v2 = customAttribute.value[ face.b ];
  10973. v3 = customAttribute.value[ face.c ];
  10974. customAttribute.array[ offset_custom ] = v1.x;
  10975. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10976. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10977. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10978. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10979. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10980. offset_custom += 6;
  10981. }
  10982. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10983. face = obj_faces[ chunk_faces4[ f ] ];
  10984. v1 = customAttribute.value[ face.a ];
  10985. v2 = customAttribute.value[ face.b ];
  10986. v3 = customAttribute.value[ face.c ];
  10987. v4 = customAttribute.value[ face.d ];
  10988. customAttribute.array[ offset_custom ] = v1.x;
  10989. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10990. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10991. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10992. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10993. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10994. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10995. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10996. offset_custom += 8;
  10997. }
  10998. } else if ( customAttribute.boundTo === "faces" ) {
  10999. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11000. value = customAttribute.value[ chunk_faces3[ f ] ];
  11001. v1 = value;
  11002. v2 = value;
  11003. v3 = value;
  11004. customAttribute.array[ offset_custom ] = v1.x;
  11005. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11006. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11007. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11008. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11009. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11010. offset_custom += 6;
  11011. }
  11012. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11013. value = customAttribute.value[ chunk_faces4[ f ] ];
  11014. v1 = value;
  11015. v2 = value;
  11016. v3 = value;
  11017. v4 = value;
  11018. customAttribute.array[ offset_custom ] = v1.x;
  11019. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11020. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11021. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11022. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11023. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11024. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11025. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11026. offset_custom += 8;
  11027. }
  11028. }
  11029. } else if ( customAttribute.size === 3 ) {
  11030. var pp;
  11031. if ( customAttribute.type === "c" ) {
  11032. pp = [ "r", "g", "b" ];
  11033. } else {
  11034. pp = [ "x", "y", "z" ];
  11035. }
  11036. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11037. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11038. face = obj_faces[ chunk_faces3[ f ] ];
  11039. v1 = customAttribute.value[ face.a ];
  11040. v2 = customAttribute.value[ face.b ];
  11041. v3 = customAttribute.value[ face.c ];
  11042. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11043. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11044. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11045. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11046. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11047. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11048. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11049. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11050. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11051. offset_custom += 9;
  11052. }
  11053. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11054. face = obj_faces[ chunk_faces4[ f ] ];
  11055. v1 = customAttribute.value[ face.a ];
  11056. v2 = customAttribute.value[ face.b ];
  11057. v3 = customAttribute.value[ face.c ];
  11058. v4 = customAttribute.value[ face.d ];
  11059. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11060. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11061. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11062. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11063. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11064. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11065. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11066. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11067. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11068. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11069. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11070. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11071. offset_custom += 12;
  11072. }
  11073. } else if ( customAttribute.boundTo === "faces" ) {
  11074. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11075. value = customAttribute.value[ chunk_faces3[ f ] ];
  11076. v1 = value;
  11077. v2 = value;
  11078. v3 = value;
  11079. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11080. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11081. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11082. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11083. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11084. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11085. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11086. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11087. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11088. offset_custom += 9;
  11089. }
  11090. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11091. value = customAttribute.value[ chunk_faces4[ f ] ];
  11092. v1 = value;
  11093. v2 = value;
  11094. v3 = value;
  11095. v4 = value;
  11096. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11097. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11098. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11099. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11100. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11101. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11102. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11103. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11104. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11105. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11106. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11107. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11108. offset_custom += 12;
  11109. }
  11110. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11111. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11112. value = customAttribute.value[ chunk_faces3[ f ] ];
  11113. v1 = value[ 0 ];
  11114. v2 = value[ 1 ];
  11115. v3 = value[ 2 ];
  11116. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11117. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11118. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11119. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11120. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11121. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11122. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11123. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11124. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11125. offset_custom += 9;
  11126. }
  11127. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11128. value = customAttribute.value[ chunk_faces4[ f ] ];
  11129. v1 = value[ 0 ];
  11130. v2 = value[ 1 ];
  11131. v3 = value[ 2 ];
  11132. v4 = value[ 3 ];
  11133. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11134. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11135. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11136. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11137. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11138. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11139. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11140. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11141. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11142. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11143. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11144. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11145. offset_custom += 12;
  11146. }
  11147. }
  11148. } else if ( customAttribute.size === 4 ) {
  11149. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11150. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11151. face = obj_faces[ chunk_faces3[ f ] ];
  11152. v1 = customAttribute.value[ face.a ];
  11153. v2 = customAttribute.value[ face.b ];
  11154. v3 = customAttribute.value[ face.c ];
  11155. customAttribute.array[ offset_custom ] = v1.x;
  11156. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11157. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11158. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11159. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11160. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11161. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11162. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11163. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11164. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11165. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11166. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11167. offset_custom += 12;
  11168. }
  11169. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11170. face = obj_faces[ chunk_faces4[ f ] ];
  11171. v1 = customAttribute.value[ face.a ];
  11172. v2 = customAttribute.value[ face.b ];
  11173. v3 = customAttribute.value[ face.c ];
  11174. v4 = customAttribute.value[ face.d ];
  11175. customAttribute.array[ offset_custom ] = v1.x;
  11176. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11177. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11178. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11179. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11180. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11181. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11182. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11183. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11184. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11185. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11186. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11187. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11188. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11189. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11190. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11191. offset_custom += 16;
  11192. }
  11193. } else if ( customAttribute.boundTo === "faces" ) {
  11194. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11195. value = customAttribute.value[ chunk_faces3[ f ] ];
  11196. v1 = value;
  11197. v2 = value;
  11198. v3 = value;
  11199. customAttribute.array[ offset_custom ] = v1.x;
  11200. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11201. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11202. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11203. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11204. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11205. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11206. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11207. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11208. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11209. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11210. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11211. offset_custom += 12;
  11212. }
  11213. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11214. value = customAttribute.value[ chunk_faces4[ f ] ];
  11215. v1 = value;
  11216. v2 = value;
  11217. v3 = value;
  11218. v4 = value;
  11219. customAttribute.array[ offset_custom ] = v1.x;
  11220. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11221. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11222. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11223. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11224. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11225. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11226. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11227. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11228. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11229. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11230. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11231. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11232. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11233. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11234. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11235. offset_custom += 16;
  11236. }
  11237. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11238. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11239. value = customAttribute.value[ chunk_faces3[ f ] ];
  11240. v1 = value[ 0 ];
  11241. v2 = value[ 1 ];
  11242. v3 = value[ 2 ];
  11243. customAttribute.array[ offset_custom ] = v1.x;
  11244. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11245. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11246. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11247. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11248. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11249. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11250. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11251. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11252. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11253. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11254. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11255. offset_custom += 12;
  11256. }
  11257. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11258. value = customAttribute.value[ chunk_faces4[ f ] ];
  11259. v1 = value[ 0 ];
  11260. v2 = value[ 1 ];
  11261. v3 = value[ 2 ];
  11262. v4 = value[ 3 ];
  11263. customAttribute.array[ offset_custom ] = v1.x;
  11264. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11265. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11266. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11267. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11268. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11269. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11270. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11271. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11272. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11273. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11274. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11275. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11276. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11277. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11278. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11279. offset_custom += 16;
  11280. }
  11281. }
  11282. }
  11283. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11284. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11285. }
  11286. }
  11287. if ( dispose ) {
  11288. delete geometryGroup.__inittedArrays;
  11289. delete geometryGroup.__colorArray;
  11290. delete geometryGroup.__normalArray;
  11291. delete geometryGroup.__tangentArray;
  11292. delete geometryGroup.__uvArray;
  11293. delete geometryGroup.__uv2Array;
  11294. delete geometryGroup.__faceArray;
  11295. delete geometryGroup.__vertexArray;
  11296. delete geometryGroup.__lineArray;
  11297. delete geometryGroup.__skinIndexArray;
  11298. delete geometryGroup.__skinWeightArray;
  11299. }
  11300. };
  11301. function setDirectBuffers ( geometry, hint, dispose ) {
  11302. var attributes = geometry.attributes;
  11303. var index = attributes[ "index" ];
  11304. var position = attributes[ "position" ];
  11305. var normal = attributes[ "normal" ];
  11306. var uv = attributes[ "uv" ];
  11307. var color = attributes[ "color" ];
  11308. var tangent = attributes[ "tangent" ];
  11309. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11310. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11311. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11312. }
  11313. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11314. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11315. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11316. }
  11317. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11318. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11319. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11320. }
  11321. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11322. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11323. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11324. }
  11325. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11326. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11327. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11328. }
  11329. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11330. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11331. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11332. }
  11333. if ( dispose ) {
  11334. for ( var i in geometry.attributes ) {
  11335. delete geometry.attributes[ i ].array;
  11336. }
  11337. }
  11338. };
  11339. // Buffer rendering
  11340. this.renderBufferImmediate = function ( object, program, material ) {
  11341. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11342. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11343. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11344. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11345. if ( object.hasPositions ) {
  11346. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11347. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11348. _gl.enableVertexAttribArray( program.attributes.position );
  11349. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11350. }
  11351. if ( object.hasNormals ) {
  11352. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11353. if ( material.shading === THREE.FlatShading ) {
  11354. var nx, ny, nz,
  11355. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11356. normalArray,
  11357. i, il = object.count * 3;
  11358. for( i = 0; i < il; i += 9 ) {
  11359. normalArray = object.normalArray;
  11360. nax = normalArray[ i ];
  11361. nay = normalArray[ i + 1 ];
  11362. naz = normalArray[ i + 2 ];
  11363. nbx = normalArray[ i + 3 ];
  11364. nby = normalArray[ i + 4 ];
  11365. nbz = normalArray[ i + 5 ];
  11366. ncx = normalArray[ i + 6 ];
  11367. ncy = normalArray[ i + 7 ];
  11368. ncz = normalArray[ i + 8 ];
  11369. nx = ( nax + nbx + ncx ) / 3;
  11370. ny = ( nay + nby + ncy ) / 3;
  11371. nz = ( naz + nbz + ncz ) / 3;
  11372. normalArray[ i ] = nx;
  11373. normalArray[ i + 1 ] = ny;
  11374. normalArray[ i + 2 ] = nz;
  11375. normalArray[ i + 3 ] = nx;
  11376. normalArray[ i + 4 ] = ny;
  11377. normalArray[ i + 5 ] = nz;
  11378. normalArray[ i + 6 ] = nx;
  11379. normalArray[ i + 7 ] = ny;
  11380. normalArray[ i + 8 ] = nz;
  11381. }
  11382. }
  11383. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11384. _gl.enableVertexAttribArray( program.attributes.normal );
  11385. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11386. }
  11387. if ( object.hasUvs && material.map ) {
  11388. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11389. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11390. _gl.enableVertexAttribArray( program.attributes.uv );
  11391. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11392. }
  11393. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11394. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11395. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11396. _gl.enableVertexAttribArray( program.attributes.color );
  11397. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11398. }
  11399. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11400. object.count = 0;
  11401. };
  11402. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11403. if ( material.visible === false ) return;
  11404. var program, attributes, linewidth, primitives, a, attribute;
  11405. program = setProgram( camera, lights, fog, material, object );
  11406. attributes = program.attributes;
  11407. var updateBuffers = false,
  11408. wireframeBit = material.wireframe ? 1 : 0,
  11409. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11410. if ( geometryHash !== _currentGeometryGroupHash ) {
  11411. _currentGeometryGroupHash = geometryHash;
  11412. updateBuffers = true;
  11413. }
  11414. if ( updateBuffers ) {
  11415. disableAttributes();
  11416. }
  11417. // render mesh
  11418. if ( object instanceof THREE.Mesh ) {
  11419. var index = geometry.attributes[ "index" ];
  11420. // indexed triangles
  11421. if ( index ) {
  11422. var offsets = geometry.offsets;
  11423. // if there is more than 1 chunk
  11424. // must set attribute pointers to use new offsets for each chunk
  11425. // even if geometry and materials didn't change
  11426. if ( offsets.length > 1 ) updateBuffers = true;
  11427. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  11428. var startIndex = offsets[ i ].index;
  11429. if ( updateBuffers ) {
  11430. // vertices
  11431. var position = geometry.attributes[ "position" ];
  11432. var positionSize = position.itemSize;
  11433. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11434. enableAttribute( attributes.position );
  11435. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  11436. // normals
  11437. var normal = geometry.attributes[ "normal" ];
  11438. if ( attributes.normal >= 0 && normal ) {
  11439. var normalSize = normal.itemSize;
  11440. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11441. enableAttribute( attributes.normal );
  11442. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  11443. }
  11444. // uvs
  11445. var uv = geometry.attributes[ "uv" ];
  11446. if ( attributes.uv >= 0 && uv ) {
  11447. var uvSize = uv.itemSize;
  11448. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11449. enableAttribute( attributes.uv );
  11450. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  11451. }
  11452. // colors
  11453. var color = geometry.attributes[ "color" ];
  11454. if ( attributes.color >= 0 && color ) {
  11455. var colorSize = color.itemSize;
  11456. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11457. enableAttribute( attributes.color );
  11458. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  11459. }
  11460. // tangents
  11461. var tangent = geometry.attributes[ "tangent" ];
  11462. if ( attributes.tangent >= 0 && tangent ) {
  11463. var tangentSize = tangent.itemSize;
  11464. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11465. enableAttribute( attributes.tangent );
  11466. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  11467. }
  11468. // indices
  11469. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11470. }
  11471. // render indexed triangles
  11472. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  11473. _this.info.render.calls ++;
  11474. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11475. _this.info.render.faces += offsets[ i ].count / 3;
  11476. }
  11477. // non-indexed triangles
  11478. } else {
  11479. if ( updateBuffers ) {
  11480. // vertices
  11481. var position = geometry.attributes[ "position" ];
  11482. var positionSize = position.itemSize;
  11483. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11484. enableAttribute( attributes.position );
  11485. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11486. // normals
  11487. var normal = geometry.attributes[ "normal" ];
  11488. if ( attributes.normal >= 0 && normal ) {
  11489. var normalSize = normal.itemSize;
  11490. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11491. enableAttribute( attributes.normal );
  11492. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  11493. }
  11494. // uvs
  11495. var uv = geometry.attributes[ "uv" ];
  11496. if ( attributes.uv >= 0 && uv ) {
  11497. var uvSize = uv.itemSize;
  11498. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11499. enableAttribute( attributes.uv );
  11500. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  11501. }
  11502. // colors
  11503. var color = geometry.attributes[ "color" ];
  11504. if ( attributes.color >= 0 && color ) {
  11505. var colorSize = color.itemSize;
  11506. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11507. enableAttribute( attributes.color );
  11508. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11509. }
  11510. // tangents
  11511. var tangent = geometry.attributes[ "tangent" ];
  11512. if ( attributes.tangent >= 0 && tangent ) {
  11513. var tangentSize = tangent.itemSize;
  11514. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11515. enableAttribute( attributes.tangent );
  11516. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  11517. }
  11518. }
  11519. // render non-indexed triangles
  11520. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  11521. _this.info.render.calls ++;
  11522. _this.info.render.vertices += position.numItems / 3;
  11523. _this.info.render.faces += position.numItems / 3 / 3;
  11524. }
  11525. // render particles
  11526. } else if ( object instanceof THREE.ParticleSystem ) {
  11527. if ( updateBuffers ) {
  11528. // vertices
  11529. var position = geometry.attributes[ "position" ];
  11530. var positionSize = position.itemSize;
  11531. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11532. enableAttribute( attributes.position );
  11533. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11534. // colors
  11535. var color = geometry.attributes[ "color" ];
  11536. if ( attributes.color >= 0 && color ) {
  11537. var colorSize = color.itemSize;
  11538. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11539. enableAttribute( attributes.color );
  11540. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11541. }
  11542. // render particles
  11543. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  11544. _this.info.render.calls ++;
  11545. _this.info.render.points += position.numItems / 3;
  11546. }
  11547. }
  11548. };
  11549. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11550. if ( material.visible === false ) return;
  11551. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11552. program = setProgram( camera, lights, fog, material, object );
  11553. attributes = program.attributes;
  11554. var updateBuffers = false,
  11555. wireframeBit = material.wireframe ? 1 : 0,
  11556. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11557. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11558. _currentGeometryGroupHash = geometryGroupHash;
  11559. updateBuffers = true;
  11560. }
  11561. if ( updateBuffers ) {
  11562. disableAttributes();
  11563. }
  11564. // vertices
  11565. if ( !material.morphTargets && attributes.position >= 0 ) {
  11566. if ( updateBuffers ) {
  11567. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11568. enableAttribute( attributes.position );
  11569. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11570. }
  11571. } else {
  11572. if ( object.morphTargetBase ) {
  11573. setupMorphTargets( material, geometryGroup, object );
  11574. }
  11575. }
  11576. if ( updateBuffers ) {
  11577. // custom attributes
  11578. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11579. if ( geometryGroup.__webglCustomAttributesList ) {
  11580. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11581. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11582. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11583. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11584. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  11585. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11586. }
  11587. }
  11588. }
  11589. // colors
  11590. if ( attributes.color >= 0 ) {
  11591. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11592. enableAttribute( attributes.color );
  11593. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11594. }
  11595. // normals
  11596. if ( attributes.normal >= 0 ) {
  11597. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11598. enableAttribute( attributes.normal );
  11599. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11600. }
  11601. // tangents
  11602. if ( attributes.tangent >= 0 ) {
  11603. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11604. enableAttribute( attributes.tangent );
  11605. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11606. }
  11607. // uvs
  11608. if ( attributes.uv >= 0 ) {
  11609. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11610. enableAttribute( attributes.uv );
  11611. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11612. }
  11613. if ( attributes.uv2 >= 0 ) {
  11614. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11615. enableAttribute( attributes.uv2 );
  11616. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11617. }
  11618. if ( material.skinning &&
  11619. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11620. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11621. enableAttribute( attributes.skinIndex );
  11622. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11623. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11624. enableAttribute( attributes.skinWeight );
  11625. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11626. }
  11627. // line distances
  11628. if ( attributes.lineDistance >= 0 ) {
  11629. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  11630. enableAttribute( attributes.lineDistance );
  11631. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  11632. }
  11633. }
  11634. // render mesh
  11635. if ( object instanceof THREE.Mesh ) {
  11636. // wireframe
  11637. if ( material.wireframe ) {
  11638. setLineWidth( material.wireframeLinewidth );
  11639. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11640. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  11641. // triangles
  11642. } else {
  11643. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11644. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11645. }
  11646. _this.info.render.calls ++;
  11647. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11648. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11649. // render lines
  11650. } else if ( object instanceof THREE.Line ) {
  11651. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11652. setLineWidth( material.linewidth );
  11653. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11654. _this.info.render.calls ++;
  11655. // render particles
  11656. } else if ( object instanceof THREE.ParticleSystem ) {
  11657. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11658. _this.info.render.calls ++;
  11659. _this.info.render.points += geometryGroup.__webglParticleCount;
  11660. // render ribbon
  11661. } else if ( object instanceof THREE.Ribbon ) {
  11662. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11663. _this.info.render.calls ++;
  11664. }
  11665. };
  11666. function enableAttribute( attribute ) {
  11667. if ( ! _enabledAttributes[ attribute ] ) {
  11668. _gl.enableVertexAttribArray( attribute );
  11669. _enabledAttributes[ attribute ] = true;
  11670. }
  11671. };
  11672. function disableAttributes() {
  11673. for ( var attribute in _enabledAttributes ) {
  11674. if ( _enabledAttributes[ attribute ] ) {
  11675. _gl.disableVertexAttribArray( attribute );
  11676. _enabledAttributes[ attribute ] = false;
  11677. }
  11678. }
  11679. };
  11680. function setupMorphTargets ( material, geometryGroup, object ) {
  11681. // set base
  11682. var attributes = material.program.attributes;
  11683. if ( object.morphTargetBase !== -1 ) {
  11684. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11685. enableAttribute( attributes.position );
  11686. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11687. } else if ( attributes.position >= 0 ) {
  11688. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11689. enableAttribute( attributes.position );
  11690. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11691. }
  11692. if ( object.morphTargetForcedOrder.length ) {
  11693. // set forced order
  11694. var m = 0;
  11695. var order = object.morphTargetForcedOrder;
  11696. var influences = object.morphTargetInfluences;
  11697. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11698. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11699. enableAttribute( attributes[ "morphTarget" + m ] );
  11700. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11701. if ( material.morphNormals ) {
  11702. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11703. enableAttribute( attributes[ "morphNormal" + m ] );
  11704. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11705. }
  11706. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11707. m ++;
  11708. }
  11709. } else {
  11710. // find the most influencing
  11711. var influence, activeInfluenceIndices = [];
  11712. var influences = object.morphTargetInfluences;
  11713. var i, il = influences.length;
  11714. for ( i = 0; i < il; i ++ ) {
  11715. influence = influences[ i ];
  11716. if ( influence > 0 ) {
  11717. activeInfluenceIndices.push( [ i, influence ] );
  11718. }
  11719. }
  11720. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11721. activeInfluenceIndices.sort( numericalSort );
  11722. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11723. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11724. activeInfluenceIndices.sort( numericalSort );
  11725. } else if ( activeInfluenceIndices.length === 0 ) {
  11726. activeInfluenceIndices.push( [ 0, 0 ] );
  11727. };
  11728. var influenceIndex, m = 0;
  11729. while ( m < material.numSupportedMorphTargets ) {
  11730. if ( activeInfluenceIndices[ m ] ) {
  11731. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11732. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11733. enableAttribute( attributes[ "morphTarget" + m ] );
  11734. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11735. if ( material.morphNormals ) {
  11736. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11737. enableAttribute( attributes[ "morphNormal" + m ] );
  11738. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11739. }
  11740. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11741. } else {
  11742. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11743. if ( material.morphNormals ) {
  11744. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11745. }
  11746. object.__webglMorphTargetInfluences[ m ] = 0;
  11747. }
  11748. m ++;
  11749. }
  11750. }
  11751. // load updated influences uniform
  11752. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11753. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11754. }
  11755. };
  11756. // Sorting
  11757. function painterSortStable ( a, b ) {
  11758. if ( a.z !== b.z ) {
  11759. return b.z - a.z;
  11760. } else {
  11761. return b.id - a.id;
  11762. }
  11763. };
  11764. function numericalSort ( a, b ) {
  11765. return b[ 1 ] - a[ 1 ];
  11766. };
  11767. // Rendering
  11768. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11769. if ( camera instanceof THREE.Camera === false ) {
  11770. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11771. return;
  11772. }
  11773. var i, il,
  11774. webglObject, object,
  11775. renderList,
  11776. lights = scene.__lights,
  11777. fog = scene.fog;
  11778. // reset caching for this frame
  11779. _currentMaterialId = -1;
  11780. _lightsNeedUpdate = true;
  11781. // update scene graph
  11782. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11783. // update camera matrices and frustum
  11784. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11785. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11786. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11787. _frustum.setFromMatrix( _projScreenMatrix );
  11788. // update WebGL objects
  11789. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11790. // custom render plugins (pre pass)
  11791. renderPlugins( this.renderPluginsPre, scene, camera );
  11792. //
  11793. _this.info.render.calls = 0;
  11794. _this.info.render.vertices = 0;
  11795. _this.info.render.faces = 0;
  11796. _this.info.render.points = 0;
  11797. this.setRenderTarget( renderTarget );
  11798. if ( this.autoClear || forceClear ) {
  11799. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11800. }
  11801. // set matrices for regular objects (frustum culled)
  11802. renderList = scene.__webglObjects;
  11803. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11804. webglObject = renderList[ i ];
  11805. object = webglObject.object;
  11806. webglObject.render = false;
  11807. if ( object.visible ) {
  11808. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11809. setupMatrices( object, camera );
  11810. unrollBufferMaterial( webglObject );
  11811. webglObject.render = true;
  11812. if ( this.sortObjects === true ) {
  11813. if ( object.renderDepth !== null ) {
  11814. webglObject.z = object.renderDepth;
  11815. } else {
  11816. _vector3.copy( object.matrixWorld.getPosition() );
  11817. _projScreenMatrix.multiplyVector3( _vector3 );
  11818. webglObject.z = _vector3.z;
  11819. }
  11820. webglObject.id = object.id;
  11821. }
  11822. }
  11823. }
  11824. }
  11825. if ( this.sortObjects ) {
  11826. renderList.sort( painterSortStable );
  11827. }
  11828. // set matrices for immediate objects
  11829. renderList = scene.__webglObjectsImmediate;
  11830. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11831. webglObject = renderList[ i ];
  11832. object = webglObject.object;
  11833. if ( object.visible ) {
  11834. setupMatrices( object, camera );
  11835. unrollImmediateBufferMaterial( webglObject );
  11836. }
  11837. }
  11838. if ( scene.overrideMaterial ) {
  11839. var material = scene.overrideMaterial;
  11840. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11841. this.setDepthTest( material.depthTest );
  11842. this.setDepthWrite( material.depthWrite );
  11843. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11844. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11845. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11846. } else {
  11847. var material = null;
  11848. // opaque pass (front-to-back order)
  11849. this.setBlending( THREE.NormalBlending );
  11850. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  11851. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  11852. // transparent pass (back-to-front order)
  11853. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  11854. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  11855. }
  11856. // custom render plugins (post pass)
  11857. renderPlugins( this.renderPluginsPost, scene, camera );
  11858. // Generate mipmap if we're using any kind of mipmap filtering
  11859. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11860. updateRenderTargetMipmap( renderTarget );
  11861. }
  11862. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11863. this.setDepthTest( true );
  11864. this.setDepthWrite( true );
  11865. // _gl.finish();
  11866. };
  11867. function renderPlugins( plugins, scene, camera ) {
  11868. if ( ! plugins.length ) return;
  11869. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11870. // reset state for plugin (to start from clean slate)
  11871. _currentProgram = null;
  11872. _currentCamera = null;
  11873. _oldBlending = -1;
  11874. _oldDepthTest = -1;
  11875. _oldDepthWrite = -1;
  11876. _oldDoubleSided = -1;
  11877. _oldFlipSided = -1;
  11878. _currentGeometryGroupHash = -1;
  11879. _currentMaterialId = -1;
  11880. _lightsNeedUpdate = true;
  11881. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11882. // reset state after plugin (anything could have changed)
  11883. _currentProgram = null;
  11884. _currentCamera = null;
  11885. _oldBlending = -1;
  11886. _oldDepthTest = -1;
  11887. _oldDepthWrite = -1;
  11888. _oldDoubleSided = -1;
  11889. _oldFlipSided = -1;
  11890. _currentGeometryGroupHash = -1;
  11891. _currentMaterialId = -1;
  11892. _lightsNeedUpdate = true;
  11893. }
  11894. };
  11895. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11896. var webglObject, object, buffer, material, start, end, delta;
  11897. if ( reverse ) {
  11898. start = renderList.length - 1;
  11899. end = -1;
  11900. delta = -1;
  11901. } else {
  11902. start = 0;
  11903. end = renderList.length;
  11904. delta = 1;
  11905. }
  11906. for ( var i = start; i !== end; i += delta ) {
  11907. webglObject = renderList[ i ];
  11908. if ( webglObject.render ) {
  11909. object = webglObject.object;
  11910. buffer = webglObject.buffer;
  11911. if ( overrideMaterial ) {
  11912. material = overrideMaterial;
  11913. } else {
  11914. material = webglObject[ materialType ];
  11915. if ( ! material ) continue;
  11916. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11917. _this.setDepthTest( material.depthTest );
  11918. _this.setDepthWrite( material.depthWrite );
  11919. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11920. }
  11921. _this.setMaterialFaces( material );
  11922. if ( buffer instanceof THREE.BufferGeometry ) {
  11923. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11924. } else {
  11925. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11926. }
  11927. }
  11928. }
  11929. };
  11930. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11931. var webglObject, object, material, program;
  11932. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11933. webglObject = renderList[ i ];
  11934. object = webglObject.object;
  11935. if ( object.visible ) {
  11936. if ( overrideMaterial ) {
  11937. material = overrideMaterial;
  11938. } else {
  11939. material = webglObject[ materialType ];
  11940. if ( ! material ) continue;
  11941. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11942. _this.setDepthTest( material.depthTest );
  11943. _this.setDepthWrite( material.depthWrite );
  11944. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11945. }
  11946. _this.renderImmediateObject( camera, lights, fog, material, object );
  11947. }
  11948. }
  11949. };
  11950. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11951. var program = setProgram( camera, lights, fog, material, object );
  11952. _currentGeometryGroupHash = -1;
  11953. _this.setMaterialFaces( material );
  11954. if ( object.immediateRenderCallback ) {
  11955. object.immediateRenderCallback( program, _gl, _frustum );
  11956. } else {
  11957. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11958. }
  11959. };
  11960. function unrollImmediateBufferMaterial ( globject ) {
  11961. var object = globject.object,
  11962. material = object.material;
  11963. if ( material.transparent ) {
  11964. globject.transparent = material;
  11965. globject.opaque = null;
  11966. } else {
  11967. globject.opaque = material;
  11968. globject.transparent = null;
  11969. }
  11970. };
  11971. function unrollBufferMaterial ( globject ) {
  11972. var object = globject.object,
  11973. buffer = globject.buffer,
  11974. material, materialIndex, meshMaterial;
  11975. meshMaterial = object.material;
  11976. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11977. materialIndex = buffer.materialIndex;
  11978. if ( materialIndex >= 0 ) {
  11979. material = meshMaterial.materials[ materialIndex ];
  11980. if ( material.transparent ) {
  11981. globject.transparent = material;
  11982. globject.opaque = null;
  11983. } else {
  11984. globject.opaque = material;
  11985. globject.transparent = null;
  11986. }
  11987. }
  11988. } else {
  11989. material = meshMaterial;
  11990. if ( material ) {
  11991. if ( material.transparent ) {
  11992. globject.transparent = material;
  11993. globject.opaque = null;
  11994. } else {
  11995. globject.opaque = material;
  11996. globject.transparent = null;
  11997. }
  11998. }
  11999. }
  12000. };
  12001. // Geometry splitting
  12002. function sortFacesByMaterial ( geometry, material ) {
  12003. var f, fl, face, materialIndex, vertices,
  12004. materialHash, groupHash,
  12005. hash_map = {};
  12006. var numMorphTargets = geometry.morphTargets.length;
  12007. var numMorphNormals = geometry.morphNormals.length;
  12008. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12009. geometry.geometryGroups = {};
  12010. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12011. face = geometry.faces[ f ];
  12012. materialIndex = usesFaceMaterial ? face.materialIndex : undefined;
  12013. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  12014. if ( hash_map[ materialHash ] === undefined ) {
  12015. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  12016. }
  12017. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  12018. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12019. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12020. }
  12021. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12022. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12023. hash_map[ materialHash ].counter += 1;
  12024. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  12025. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12026. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12027. }
  12028. }
  12029. if ( face instanceof THREE.Face3 ) {
  12030. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12031. } else {
  12032. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12033. }
  12034. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12035. }
  12036. geometry.geometryGroupsList = [];
  12037. for ( var g in geometry.geometryGroups ) {
  12038. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12039. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12040. }
  12041. };
  12042. // Objects refresh
  12043. this.initWebGLObjects = function ( scene ) {
  12044. if ( !scene.__webglObjects ) {
  12045. scene.__webglObjects = [];
  12046. scene.__webglObjectsImmediate = [];
  12047. scene.__webglSprites = [];
  12048. scene.__webglFlares = [];
  12049. }
  12050. while ( scene.__objectsAdded.length ) {
  12051. addObject( scene.__objectsAdded[ 0 ], scene );
  12052. scene.__objectsAdded.splice( 0, 1 );
  12053. }
  12054. while ( scene.__objectsRemoved.length ) {
  12055. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12056. scene.__objectsRemoved.splice( 0, 1 );
  12057. }
  12058. // update must be called after objects adding / removal
  12059. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12060. updateObject( scene.__webglObjects[ o ].object );
  12061. }
  12062. };
  12063. // Objects adding
  12064. function addObject ( object, scene ) {
  12065. var g, geometry, material, geometryGroup;
  12066. if ( ! object.__webglInit ) {
  12067. object.__webglInit = true;
  12068. object._modelViewMatrix = new THREE.Matrix4();
  12069. object._normalMatrix = new THREE.Matrix3();
  12070. if ( object instanceof THREE.Mesh ) {
  12071. geometry = object.geometry;
  12072. material = object.material;
  12073. if ( geometry instanceof THREE.Geometry ) {
  12074. if ( geometry.geometryGroups === undefined ) {
  12075. sortFacesByMaterial( geometry, material );
  12076. }
  12077. // create separate VBOs per geometry chunk
  12078. for ( g in geometry.geometryGroups ) {
  12079. geometryGroup = geometry.geometryGroups[ g ];
  12080. // initialise VBO on the first access
  12081. if ( ! geometryGroup.__webglVertexBuffer ) {
  12082. createMeshBuffers( geometryGroup );
  12083. initMeshBuffers( geometryGroup, object );
  12084. geometry.verticesNeedUpdate = true;
  12085. geometry.morphTargetsNeedUpdate = true;
  12086. geometry.elementsNeedUpdate = true;
  12087. geometry.uvsNeedUpdate = true;
  12088. geometry.normalsNeedUpdate = true;
  12089. geometry.tangentsNeedUpdate = true;
  12090. geometry.colorsNeedUpdate = true;
  12091. }
  12092. }
  12093. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12094. initDirectBuffers( geometry );
  12095. }
  12096. } else if ( object instanceof THREE.Ribbon ) {
  12097. geometry = object.geometry;
  12098. if ( ! geometry.__webglVertexBuffer ) {
  12099. createRibbonBuffers( geometry );
  12100. initRibbonBuffers( geometry, object );
  12101. geometry.verticesNeedUpdate = true;
  12102. geometry.colorsNeedUpdate = true;
  12103. geometry.normalsNeedUpdate = true;
  12104. }
  12105. } else if ( object instanceof THREE.Line ) {
  12106. geometry = object.geometry;
  12107. if ( ! geometry.__webglVertexBuffer ) {
  12108. createLineBuffers( geometry );
  12109. initLineBuffers( geometry, object );
  12110. geometry.verticesNeedUpdate = true;
  12111. geometry.colorsNeedUpdate = true;
  12112. geometry.lineDistancesNeedUpdate = true;
  12113. }
  12114. } else if ( object instanceof THREE.ParticleSystem ) {
  12115. geometry = object.geometry;
  12116. if ( ! geometry.__webglVertexBuffer ) {
  12117. if ( geometry instanceof THREE.Geometry ) {
  12118. createParticleBuffers( geometry );
  12119. initParticleBuffers( geometry, object );
  12120. geometry.verticesNeedUpdate = true;
  12121. geometry.colorsNeedUpdate = true;
  12122. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12123. initDirectBuffers( geometry );
  12124. }
  12125. }
  12126. }
  12127. }
  12128. if ( ! object.__webglActive ) {
  12129. if ( object instanceof THREE.Mesh ) {
  12130. geometry = object.geometry;
  12131. if ( geometry instanceof THREE.BufferGeometry ) {
  12132. addBuffer( scene.__webglObjects, geometry, object );
  12133. } else {
  12134. for ( g in geometry.geometryGroups ) {
  12135. geometryGroup = geometry.geometryGroups[ g ];
  12136. addBuffer( scene.__webglObjects, geometryGroup, object );
  12137. }
  12138. }
  12139. } else if ( object instanceof THREE.Ribbon ||
  12140. object instanceof THREE.Line ||
  12141. object instanceof THREE.ParticleSystem ) {
  12142. geometry = object.geometry;
  12143. addBuffer( scene.__webglObjects, geometry, object );
  12144. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12145. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12146. } else if ( object instanceof THREE.Sprite ) {
  12147. scene.__webglSprites.push( object );
  12148. } else if ( object instanceof THREE.LensFlare ) {
  12149. scene.__webglFlares.push( object );
  12150. }
  12151. object.__webglActive = true;
  12152. }
  12153. };
  12154. function addBuffer ( objlist, buffer, object ) {
  12155. objlist.push(
  12156. {
  12157. buffer: buffer,
  12158. object: object,
  12159. opaque: null,
  12160. transparent: null
  12161. }
  12162. );
  12163. };
  12164. function addBufferImmediate ( objlist, object ) {
  12165. objlist.push(
  12166. {
  12167. object: object,
  12168. opaque: null,
  12169. transparent: null
  12170. }
  12171. );
  12172. };
  12173. // Objects updates
  12174. function updateObject ( object ) {
  12175. var geometry = object.geometry,
  12176. geometryGroup, customAttributesDirty, material;
  12177. if ( object instanceof THREE.Mesh ) {
  12178. if ( geometry instanceof THREE.BufferGeometry ) {
  12179. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12180. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12181. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12182. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12183. }
  12184. geometry.verticesNeedUpdate = false;
  12185. geometry.elementsNeedUpdate = false;
  12186. geometry.uvsNeedUpdate = false;
  12187. geometry.normalsNeedUpdate = false;
  12188. geometry.colorsNeedUpdate = false;
  12189. geometry.tangentsNeedUpdate = false;
  12190. } else {
  12191. // check all geometry groups
  12192. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12193. geometryGroup = geometry.geometryGroupsList[ i ];
  12194. material = getBufferMaterial( object, geometryGroup );
  12195. if ( geometry.buffersNeedUpdate ) {
  12196. initMeshBuffers( geometryGroup, object );
  12197. }
  12198. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12199. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12200. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12201. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12202. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12203. }
  12204. }
  12205. geometry.verticesNeedUpdate = false;
  12206. geometry.morphTargetsNeedUpdate = false;
  12207. geometry.elementsNeedUpdate = false;
  12208. geometry.uvsNeedUpdate = false;
  12209. geometry.normalsNeedUpdate = false;
  12210. geometry.colorsNeedUpdate = false;
  12211. geometry.tangentsNeedUpdate = false;
  12212. geometry.buffersNeedUpdate = false;
  12213. material.attributes && clearCustomAttributes( material );
  12214. }
  12215. } else if ( object instanceof THREE.Ribbon ) {
  12216. material = getBufferMaterial( object, geometry );
  12217. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12218. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12219. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12220. }
  12221. geometry.verticesNeedUpdate = false;
  12222. geometry.colorsNeedUpdate = false;
  12223. geometry.normalsNeedUpdate = false;
  12224. material.attributes && clearCustomAttributes( material );
  12225. } else if ( object instanceof THREE.Line ) {
  12226. material = getBufferMaterial( object, geometry );
  12227. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12228. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12229. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12230. }
  12231. geometry.verticesNeedUpdate = false;
  12232. geometry.colorsNeedUpdate = false;
  12233. geometry.lineDistancesNeedUpdate = false;
  12234. material.attributes && clearCustomAttributes( material );
  12235. } else if ( object instanceof THREE.ParticleSystem ) {
  12236. if ( geometry instanceof THREE.BufferGeometry ) {
  12237. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12238. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12239. }
  12240. geometry.verticesNeedUpdate = false;
  12241. geometry.colorsNeedUpdate = false;
  12242. } else {
  12243. material = getBufferMaterial( object, geometry );
  12244. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12245. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12246. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12247. }
  12248. geometry.verticesNeedUpdate = false;
  12249. geometry.colorsNeedUpdate = false;
  12250. material.attributes && clearCustomAttributes( material );
  12251. }
  12252. }
  12253. };
  12254. // Objects updates - custom attributes check
  12255. function areCustomAttributesDirty ( material ) {
  12256. for ( var a in material.attributes ) {
  12257. if ( material.attributes[ a ].needsUpdate ) return true;
  12258. }
  12259. return false;
  12260. };
  12261. function clearCustomAttributes ( material ) {
  12262. for ( var a in material.attributes ) {
  12263. material.attributes[ a ].needsUpdate = false;
  12264. }
  12265. };
  12266. // Objects removal
  12267. function removeObject ( object, scene ) {
  12268. if ( object instanceof THREE.Mesh ||
  12269. object instanceof THREE.ParticleSystem ||
  12270. object instanceof THREE.Ribbon ||
  12271. object instanceof THREE.Line ) {
  12272. removeInstances( scene.__webglObjects, object );
  12273. } else if ( object instanceof THREE.Sprite ) {
  12274. removeInstancesDirect( scene.__webglSprites, object );
  12275. } else if ( object instanceof THREE.LensFlare ) {
  12276. removeInstancesDirect( scene.__webglFlares, object );
  12277. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12278. removeInstances( scene.__webglObjectsImmediate, object );
  12279. }
  12280. object.__webglActive = false;
  12281. };
  12282. function removeInstances ( objlist, object ) {
  12283. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12284. if ( objlist[ o ].object === object ) {
  12285. objlist.splice( o, 1 );
  12286. }
  12287. }
  12288. };
  12289. function removeInstancesDirect ( objlist, object ) {
  12290. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12291. if ( objlist[ o ] === object ) {
  12292. objlist.splice( o, 1 );
  12293. }
  12294. }
  12295. };
  12296. // Materials
  12297. this.initMaterial = function ( material, lights, fog, object ) {
  12298. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12299. if ( material instanceof THREE.MeshDepthMaterial ) {
  12300. shaderID = 'depth';
  12301. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12302. shaderID = 'normal';
  12303. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12304. shaderID = 'basic';
  12305. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12306. shaderID = 'lambert';
  12307. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12308. shaderID = 'phong';
  12309. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12310. shaderID = 'basic';
  12311. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12312. shaderID = 'dashed';
  12313. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12314. shaderID = 'particle_basic';
  12315. }
  12316. if ( shaderID ) {
  12317. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12318. }
  12319. // heuristics to create shader parameters according to lights in the scene
  12320. // (not to blow over maxLights budget)
  12321. maxLightCount = allocateLights( lights );
  12322. maxShadows = allocateShadows( lights );
  12323. maxBones = allocateBones( object );
  12324. parameters = {
  12325. map: !!material.map,
  12326. envMap: !!material.envMap,
  12327. lightMap: !!material.lightMap,
  12328. bumpMap: !!material.bumpMap,
  12329. normalMap: !!material.normalMap,
  12330. specularMap: !!material.specularMap,
  12331. vertexColors: material.vertexColors,
  12332. fog: fog,
  12333. useFog: material.fog,
  12334. fogExp: fog instanceof THREE.FogExp2,
  12335. sizeAttenuation: material.sizeAttenuation,
  12336. skinning: material.skinning,
  12337. maxBones: maxBones,
  12338. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12339. boneTextureWidth: object && object.boneTextureWidth,
  12340. boneTextureHeight: object && object.boneTextureHeight,
  12341. morphTargets: material.morphTargets,
  12342. morphNormals: material.morphNormals,
  12343. maxMorphTargets: this.maxMorphTargets,
  12344. maxMorphNormals: this.maxMorphNormals,
  12345. maxDirLights: maxLightCount.directional,
  12346. maxPointLights: maxLightCount.point,
  12347. maxSpotLights: maxLightCount.spot,
  12348. maxHemiLights: maxLightCount.hemi,
  12349. maxShadows: maxShadows,
  12350. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  12351. shadowMapSoft: this.shadowMapSoft,
  12352. shadowMapDebug: this.shadowMapDebug,
  12353. shadowMapCascade: this.shadowMapCascade,
  12354. alphaTest: material.alphaTest,
  12355. metal: material.metal,
  12356. perPixel: material.perPixel,
  12357. wrapAround: material.wrapAround,
  12358. doubleSided: material.side === THREE.DoubleSide,
  12359. flipSided: material.side === THREE.BackSide
  12360. };
  12361. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  12362. var attributes = material.program.attributes;
  12363. if ( material.morphTargets ) {
  12364. material.numSupportedMorphTargets = 0;
  12365. var id, base = "morphTarget";
  12366. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  12367. id = base + i;
  12368. if ( attributes[ id ] >= 0 ) {
  12369. material.numSupportedMorphTargets ++;
  12370. }
  12371. }
  12372. }
  12373. if ( material.morphNormals ) {
  12374. material.numSupportedMorphNormals = 0;
  12375. var id, base = "morphNormal";
  12376. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  12377. id = base + i;
  12378. if ( attributes[ id ] >= 0 ) {
  12379. material.numSupportedMorphNormals ++;
  12380. }
  12381. }
  12382. }
  12383. material.uniformsList = [];
  12384. for ( u in material.uniforms ) {
  12385. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  12386. }
  12387. };
  12388. function setMaterialShaders( material, shaders ) {
  12389. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  12390. material.vertexShader = shaders.vertexShader;
  12391. material.fragmentShader = shaders.fragmentShader;
  12392. };
  12393. function setProgram( camera, lights, fog, material, object ) {
  12394. _usedTextureUnits = 0;
  12395. if ( material.needsUpdate ) {
  12396. if ( material.program ) _this.deallocateMaterial( material );
  12397. _this.initMaterial( material, lights, fog, object );
  12398. material.needsUpdate = false;
  12399. }
  12400. if ( material.morphTargets ) {
  12401. if ( ! object.__webglMorphTargetInfluences ) {
  12402. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12403. }
  12404. }
  12405. var refreshMaterial = false;
  12406. var program = material.program,
  12407. p_uniforms = program.uniforms,
  12408. m_uniforms = material.uniforms;
  12409. if ( program !== _currentProgram ) {
  12410. _gl.useProgram( program );
  12411. _currentProgram = program;
  12412. refreshMaterial = true;
  12413. }
  12414. if ( material.id !== _currentMaterialId ) {
  12415. _currentMaterialId = material.id;
  12416. refreshMaterial = true;
  12417. }
  12418. if ( refreshMaterial || camera !== _currentCamera ) {
  12419. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  12420. if ( camera !== _currentCamera ) _currentCamera = camera;
  12421. }
  12422. // skinning uniforms must be set even if material didn't change
  12423. // auto-setting of texture unit for bone texture must go before other textures
  12424. // not sure why, but otherwise weird things happen
  12425. if ( material.skinning ) {
  12426. if ( _supportsBoneTextures && object.useVertexTexture ) {
  12427. if ( p_uniforms.boneTexture !== null ) {
  12428. var textureUnit = getTextureUnit();
  12429. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12430. _this.setTexture( object.boneTexture, textureUnit );
  12431. }
  12432. } else {
  12433. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12434. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  12435. }
  12436. }
  12437. }
  12438. if ( refreshMaterial ) {
  12439. // refresh uniforms common to several materials
  12440. if ( fog && material.fog ) {
  12441. refreshUniformsFog( m_uniforms, fog );
  12442. }
  12443. if ( material instanceof THREE.MeshPhongMaterial ||
  12444. material instanceof THREE.MeshLambertMaterial ||
  12445. material.lights ) {
  12446. if ( _lightsNeedUpdate ) {
  12447. setupLights( program, lights );
  12448. _lightsNeedUpdate = false;
  12449. }
  12450. refreshUniformsLights( m_uniforms, _lights );
  12451. }
  12452. if ( material instanceof THREE.MeshBasicMaterial ||
  12453. material instanceof THREE.MeshLambertMaterial ||
  12454. material instanceof THREE.MeshPhongMaterial ) {
  12455. refreshUniformsCommon( m_uniforms, material );
  12456. }
  12457. // refresh single material specific uniforms
  12458. if ( material instanceof THREE.LineBasicMaterial ) {
  12459. refreshUniformsLine( m_uniforms, material );
  12460. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12461. refreshUniformsLine( m_uniforms, material );
  12462. refreshUniformsDash( m_uniforms, material );
  12463. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12464. refreshUniformsParticle( m_uniforms, material );
  12465. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12466. refreshUniformsPhong( m_uniforms, material );
  12467. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12468. refreshUniformsLambert( m_uniforms, material );
  12469. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12470. m_uniforms.mNear.value = camera.near;
  12471. m_uniforms.mFar.value = camera.far;
  12472. m_uniforms.opacity.value = material.opacity;
  12473. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12474. m_uniforms.opacity.value = material.opacity;
  12475. }
  12476. if ( object.receiveShadow && ! material._shadowPass ) {
  12477. refreshUniformsShadow( m_uniforms, lights );
  12478. }
  12479. // load common uniforms
  12480. loadUniformsGeneric( program, material.uniformsList );
  12481. // load material specific uniforms
  12482. // (shader material also gets them for the sake of genericity)
  12483. if ( material instanceof THREE.ShaderMaterial ||
  12484. material instanceof THREE.MeshPhongMaterial ||
  12485. material.envMap ) {
  12486. if ( p_uniforms.cameraPosition !== null ) {
  12487. var position = camera.matrixWorld.getPosition();
  12488. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  12489. }
  12490. }
  12491. if ( material instanceof THREE.MeshPhongMaterial ||
  12492. material instanceof THREE.MeshLambertMaterial ||
  12493. material instanceof THREE.ShaderMaterial ||
  12494. material.skinning ) {
  12495. if ( p_uniforms.viewMatrix !== null ) {
  12496. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  12497. }
  12498. }
  12499. }
  12500. loadUniformsMatrices( p_uniforms, object );
  12501. if ( p_uniforms.modelMatrix !== null ) {
  12502. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12503. }
  12504. return program;
  12505. };
  12506. // Uniforms (refresh uniforms objects)
  12507. function refreshUniformsCommon ( uniforms, material ) {
  12508. uniforms.opacity.value = material.opacity;
  12509. if ( _this.gammaInput ) {
  12510. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12511. } else {
  12512. uniforms.diffuse.value = material.color;
  12513. }
  12514. uniforms.map.value = material.map;
  12515. uniforms.lightMap.value = material.lightMap;
  12516. uniforms.specularMap.value = material.specularMap;
  12517. if ( material.bumpMap ) {
  12518. uniforms.bumpMap.value = material.bumpMap;
  12519. uniforms.bumpScale.value = material.bumpScale;
  12520. }
  12521. if ( material.normalMap ) {
  12522. uniforms.normalMap.value = material.normalMap;
  12523. uniforms.normalScale.value.copy( material.normalScale );
  12524. }
  12525. // uv repeat and offset setting priorities
  12526. // 1. color map
  12527. // 2. specular map
  12528. // 3. normal map
  12529. // 4. bump map
  12530. var uvScaleMap;
  12531. if ( material.map ) {
  12532. uvScaleMap = material.map;
  12533. } else if ( material.specularMap ) {
  12534. uvScaleMap = material.specularMap;
  12535. } else if ( material.normalMap ) {
  12536. uvScaleMap = material.normalMap;
  12537. } else if ( material.bumpMap ) {
  12538. uvScaleMap = material.bumpMap;
  12539. }
  12540. if ( uvScaleMap !== undefined ) {
  12541. var offset = uvScaleMap.offset;
  12542. var repeat = uvScaleMap.repeat;
  12543. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12544. }
  12545. uniforms.envMap.value = material.envMap;
  12546. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12547. if ( _this.gammaInput ) {
  12548. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12549. uniforms.reflectivity.value = material.reflectivity;
  12550. } else {
  12551. uniforms.reflectivity.value = material.reflectivity;
  12552. }
  12553. uniforms.refractionRatio.value = material.refractionRatio;
  12554. uniforms.combine.value = material.combine;
  12555. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12556. };
  12557. function refreshUniformsLine ( uniforms, material ) {
  12558. uniforms.diffuse.value = material.color;
  12559. uniforms.opacity.value = material.opacity;
  12560. };
  12561. function refreshUniformsDash ( uniforms, material ) {
  12562. uniforms.dashSize.value = material.dashSize;
  12563. uniforms.totalSize.value = material.dashSize + material.gapSize;
  12564. uniforms.scale.value = material.scale;
  12565. };
  12566. function refreshUniformsParticle ( uniforms, material ) {
  12567. uniforms.psColor.value = material.color;
  12568. uniforms.opacity.value = material.opacity;
  12569. uniforms.size.value = material.size;
  12570. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12571. uniforms.map.value = material.map;
  12572. };
  12573. function refreshUniformsFog ( uniforms, fog ) {
  12574. uniforms.fogColor.value = fog.color;
  12575. if ( fog instanceof THREE.Fog ) {
  12576. uniforms.fogNear.value = fog.near;
  12577. uniforms.fogFar.value = fog.far;
  12578. } else if ( fog instanceof THREE.FogExp2 ) {
  12579. uniforms.fogDensity.value = fog.density;
  12580. }
  12581. };
  12582. function refreshUniformsPhong ( uniforms, material ) {
  12583. uniforms.shininess.value = material.shininess;
  12584. if ( _this.gammaInput ) {
  12585. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12586. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12587. uniforms.specular.value.copyGammaToLinear( material.specular );
  12588. } else {
  12589. uniforms.ambient.value = material.ambient;
  12590. uniforms.emissive.value = material.emissive;
  12591. uniforms.specular.value = material.specular;
  12592. }
  12593. if ( material.wrapAround ) {
  12594. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12595. }
  12596. };
  12597. function refreshUniformsLambert ( uniforms, material ) {
  12598. if ( _this.gammaInput ) {
  12599. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12600. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12601. } else {
  12602. uniforms.ambient.value = material.ambient;
  12603. uniforms.emissive.value = material.emissive;
  12604. }
  12605. if ( material.wrapAround ) {
  12606. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12607. }
  12608. };
  12609. function refreshUniformsLights ( uniforms, lights ) {
  12610. uniforms.ambientLightColor.value = lights.ambient;
  12611. uniforms.directionalLightColor.value = lights.directional.colors;
  12612. uniforms.directionalLightDirection.value = lights.directional.positions;
  12613. uniforms.pointLightColor.value = lights.point.colors;
  12614. uniforms.pointLightPosition.value = lights.point.positions;
  12615. uniforms.pointLightDistance.value = lights.point.distances;
  12616. uniforms.spotLightColor.value = lights.spot.colors;
  12617. uniforms.spotLightPosition.value = lights.spot.positions;
  12618. uniforms.spotLightDistance.value = lights.spot.distances;
  12619. uniforms.spotLightDirection.value = lights.spot.directions;
  12620. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  12621. uniforms.spotLightExponent.value = lights.spot.exponents;
  12622. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12623. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12624. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  12625. };
  12626. function refreshUniformsShadow ( uniforms, lights ) {
  12627. if ( uniforms.shadowMatrix ) {
  12628. var j = 0;
  12629. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12630. var light = lights[ i ];
  12631. if ( ! light.castShadow ) continue;
  12632. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12633. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12634. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12635. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12636. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12637. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12638. j ++;
  12639. }
  12640. }
  12641. }
  12642. };
  12643. // Uniforms (load to GPU)
  12644. function loadUniformsMatrices ( uniforms, object ) {
  12645. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12646. if ( uniforms.normalMatrix ) {
  12647. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12648. }
  12649. };
  12650. function getTextureUnit() {
  12651. var textureUnit = _usedTextureUnits;
  12652. if ( textureUnit >= _maxTextures ) {
  12653. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  12654. }
  12655. _usedTextureUnits += 1;
  12656. return textureUnit;
  12657. };
  12658. function loadUniformsGeneric ( program, uniforms ) {
  12659. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12660. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12661. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12662. if ( !location ) continue;
  12663. uniform = uniforms[ j ][ 0 ];
  12664. type = uniform.type;
  12665. value = uniform.value;
  12666. if ( type === "i" ) { // single integer
  12667. _gl.uniform1i( location, value );
  12668. } else if ( type === "f" ) { // single float
  12669. _gl.uniform1f( location, value );
  12670. } else if ( type === "v2" ) { // single THREE.Vector2
  12671. _gl.uniform2f( location, value.x, value.y );
  12672. } else if ( type === "v3" ) { // single THREE.Vector3
  12673. _gl.uniform3f( location, value.x, value.y, value.z );
  12674. } else if ( type === "v4" ) { // single THREE.Vector4
  12675. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12676. } else if ( type === "c" ) { // single THREE.Color
  12677. _gl.uniform3f( location, value.r, value.g, value.b );
  12678. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12679. _gl.uniform1iv( location, value );
  12680. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12681. _gl.uniform3iv( location, value );
  12682. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12683. _gl.uniform1fv( location, value );
  12684. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12685. _gl.uniform3fv( location, value );
  12686. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12687. if ( uniform._array === undefined ) {
  12688. uniform._array = new Float32Array( 2 * value.length );
  12689. }
  12690. for ( i = 0, il = value.length; i < il; i ++ ) {
  12691. offset = i * 2;
  12692. uniform._array[ offset ] = value[ i ].x;
  12693. uniform._array[ offset + 1 ] = value[ i ].y;
  12694. }
  12695. _gl.uniform2fv( location, uniform._array );
  12696. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12697. if ( uniform._array === undefined ) {
  12698. uniform._array = new Float32Array( 3 * value.length );
  12699. }
  12700. for ( i = 0, il = value.length; i < il; i ++ ) {
  12701. offset = i * 3;
  12702. uniform._array[ offset ] = value[ i ].x;
  12703. uniform._array[ offset + 1 ] = value[ i ].y;
  12704. uniform._array[ offset + 2 ] = value[ i ].z;
  12705. }
  12706. _gl.uniform3fv( location, uniform._array );
  12707. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12708. if ( uniform._array === undefined ) {
  12709. uniform._array = new Float32Array( 4 * value.length );
  12710. }
  12711. for ( i = 0, il = value.length; i < il; i ++ ) {
  12712. offset = i * 4;
  12713. uniform._array[ offset ] = value[ i ].x;
  12714. uniform._array[ offset + 1 ] = value[ i ].y;
  12715. uniform._array[ offset + 2 ] = value[ i ].z;
  12716. uniform._array[ offset + 3 ] = value[ i ].w;
  12717. }
  12718. _gl.uniform4fv( location, uniform._array );
  12719. } else if ( type === "m4") { // single THREE.Matrix4
  12720. if ( uniform._array === undefined ) {
  12721. uniform._array = new Float32Array( 16 );
  12722. }
  12723. value.flattenToArray( uniform._array );
  12724. _gl.uniformMatrix4fv( location, false, uniform._array );
  12725. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12726. if ( uniform._array === undefined ) {
  12727. uniform._array = new Float32Array( 16 * value.length );
  12728. }
  12729. for ( i = 0, il = value.length; i < il; i ++ ) {
  12730. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12731. }
  12732. _gl.uniformMatrix4fv( location, false, uniform._array );
  12733. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12734. texture = value;
  12735. textureUnit = getTextureUnit();
  12736. _gl.uniform1i( location, textureUnit );
  12737. if ( !texture ) continue;
  12738. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12739. setCubeTexture( texture, textureUnit );
  12740. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12741. setCubeTextureDynamic( texture, textureUnit );
  12742. } else {
  12743. _this.setTexture( texture, textureUnit );
  12744. }
  12745. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12746. if ( uniform._array === undefined ) {
  12747. uniform._array = [];
  12748. }
  12749. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12750. uniform._array[ i ] = getTextureUnit();
  12751. }
  12752. _gl.uniform1iv( location, uniform._array );
  12753. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12754. texture = uniform.value[ i ];
  12755. textureUnit = uniform._array[ i ];
  12756. if ( !texture ) continue;
  12757. _this.setTexture( texture, textureUnit );
  12758. }
  12759. }
  12760. }
  12761. };
  12762. function setupMatrices ( object, camera ) {
  12763. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12764. object._normalMatrix.getInverse( object._modelViewMatrix );
  12765. object._normalMatrix.transpose();
  12766. };
  12767. //
  12768. function setColorGamma( array, offset, color, intensitySq ) {
  12769. array[ offset ] = color.r * color.r * intensitySq;
  12770. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12771. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12772. };
  12773. function setColorLinear( array, offset, color, intensity ) {
  12774. array[ offset ] = color.r * intensity;
  12775. array[ offset + 1 ] = color.g * intensity;
  12776. array[ offset + 2 ] = color.b * intensity;
  12777. };
  12778. function setupLights ( program, lights ) {
  12779. var l, ll, light, n,
  12780. r = 0, g = 0, b = 0,
  12781. color, skyColor, groundColor,
  12782. intensity, intensitySq,
  12783. position,
  12784. distance,
  12785. zlights = _lights,
  12786. dirColors = zlights.directional.colors,
  12787. dirPositions = zlights.directional.positions,
  12788. pointColors = zlights.point.colors,
  12789. pointPositions = zlights.point.positions,
  12790. pointDistances = zlights.point.distances,
  12791. spotColors = zlights.spot.colors,
  12792. spotPositions = zlights.spot.positions,
  12793. spotDistances = zlights.spot.distances,
  12794. spotDirections = zlights.spot.directions,
  12795. spotAnglesCos = zlights.spot.anglesCos,
  12796. spotExponents = zlights.spot.exponents,
  12797. hemiSkyColors = zlights.hemi.skyColors,
  12798. hemiGroundColors = zlights.hemi.groundColors,
  12799. hemiPositions = zlights.hemi.positions,
  12800. dirLength = 0,
  12801. pointLength = 0,
  12802. spotLength = 0,
  12803. hemiLength = 0,
  12804. dirCount = 0,
  12805. pointCount = 0,
  12806. spotCount = 0,
  12807. hemiCount = 0,
  12808. dirOffset = 0,
  12809. pointOffset = 0,
  12810. spotOffset = 0,
  12811. hemiOffset = 0;
  12812. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12813. light = lights[ l ];
  12814. if ( light.onlyShadow ) continue;
  12815. color = light.color;
  12816. intensity = light.intensity;
  12817. distance = light.distance;
  12818. if ( light instanceof THREE.AmbientLight ) {
  12819. if ( ! light.visible ) continue;
  12820. if ( _this.gammaInput ) {
  12821. r += color.r * color.r;
  12822. g += color.g * color.g;
  12823. b += color.b * color.b;
  12824. } else {
  12825. r += color.r;
  12826. g += color.g;
  12827. b += color.b;
  12828. }
  12829. } else if ( light instanceof THREE.DirectionalLight ) {
  12830. dirCount += 1;
  12831. if ( ! light.visible ) continue;
  12832. dirOffset = dirLength * 3;
  12833. if ( _this.gammaInput ) {
  12834. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12835. } else {
  12836. setColorLinear( dirColors, dirOffset, color, intensity );
  12837. }
  12838. _direction.copy( light.matrixWorld.getPosition() );
  12839. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12840. _direction.normalize();
  12841. dirPositions[ dirOffset ] = _direction.x;
  12842. dirPositions[ dirOffset + 1 ] = _direction.y;
  12843. dirPositions[ dirOffset + 2 ] = _direction.z;
  12844. dirLength += 1;
  12845. } else if ( light instanceof THREE.PointLight ) {
  12846. pointCount += 1;
  12847. if ( ! light.visible ) continue;
  12848. pointOffset = pointLength * 3;
  12849. if ( _this.gammaInput ) {
  12850. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12851. } else {
  12852. setColorLinear( pointColors, pointOffset, color, intensity );
  12853. }
  12854. position = light.matrixWorld.getPosition();
  12855. pointPositions[ pointOffset ] = position.x;
  12856. pointPositions[ pointOffset + 1 ] = position.y;
  12857. pointPositions[ pointOffset + 2 ] = position.z;
  12858. pointDistances[ pointLength ] = distance;
  12859. pointLength += 1;
  12860. } else if ( light instanceof THREE.SpotLight ) {
  12861. spotCount += 1;
  12862. if ( ! light.visible ) continue;
  12863. spotOffset = spotLength * 3;
  12864. if ( _this.gammaInput ) {
  12865. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12866. } else {
  12867. setColorLinear( spotColors, spotOffset, color, intensity );
  12868. }
  12869. position = light.matrixWorld.getPosition();
  12870. spotPositions[ spotOffset ] = position.x;
  12871. spotPositions[ spotOffset + 1 ] = position.y;
  12872. spotPositions[ spotOffset + 2 ] = position.z;
  12873. spotDistances[ spotLength ] = distance;
  12874. _direction.copy( position );
  12875. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12876. _direction.normalize();
  12877. spotDirections[ spotOffset ] = _direction.x;
  12878. spotDirections[ spotOffset + 1 ] = _direction.y;
  12879. spotDirections[ spotOffset + 2 ] = _direction.z;
  12880. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  12881. spotExponents[ spotLength ] = light.exponent;
  12882. spotLength += 1;
  12883. } else if ( light instanceof THREE.HemisphereLight ) {
  12884. hemiCount += 1;
  12885. if ( ! light.visible ) continue;
  12886. skyColor = light.color;
  12887. groundColor = light.groundColor;
  12888. hemiOffset = hemiLength * 3;
  12889. if ( _this.gammaInput ) {
  12890. intensitySq = intensity * intensity;
  12891. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12892. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12893. } else {
  12894. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12895. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12896. }
  12897. _direction.copy( light.matrixWorld.getPosition() );
  12898. _direction.normalize();
  12899. hemiPositions[ hemiOffset ] = _direction.x;
  12900. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  12901. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  12902. hemiLength += 1;
  12903. }
  12904. }
  12905. // null eventual remains from removed lights
  12906. // (this is to avoid if in shader)
  12907. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  12908. for ( l = dirLength * 3, ll = Math.max( dirPositions.length, dirCount * 3 ); l < ll; l ++ ) dirPositions[ l ] = 0.0;
  12909. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  12910. for ( l = pointLength * 3, ll = Math.max( pointPositions.length, pointCount * 3 ); l < ll; l ++ ) pointPositions[ l ] = 0.0;
  12911. for ( l = pointLength, ll = Math.max( pointDistances.length, pointCount ); l < ll; l ++ ) pointDistances[ l ] = 0.0;
  12912. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  12913. for ( l = spotLength * 3, ll = Math.max( spotPositions.length, spotCount * 3 ); l < ll; l ++ ) spotPositions[ l ] = 0.0;
  12914. for ( l = spotLength * 3, ll = Math.max( spotDirections.length, spotCount * 3 ); l < ll; l ++ ) spotDirections[ l ] = 0.0;
  12915. for ( l = spotLength, ll = Math.max( spotAnglesCos.length, spotCount ); l < ll; l ++ ) spotAnglesCos[ l ] = 0.0;
  12916. for ( l = spotLength, ll = Math.max( spotExponents.length, spotCount ); l < ll; l ++ ) spotExponents[ l ] = 0.0;
  12917. for ( l = spotLength, ll = Math.max( spotDistances.length, spotCount ); l < ll; l ++ ) spotDistances[ l ] = 0.0;
  12918. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12919. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12920. for ( l = hemiLength * 3, ll = Math.max( hemiPositions.length, hemiCount * 3 ); l < ll; l ++ ) hemiPositions[ l ] = 0.0;
  12921. zlights.directional.length = dirLength;
  12922. zlights.point.length = pointLength;
  12923. zlights.spot.length = spotLength;
  12924. zlights.hemi.length = hemiLength;
  12925. zlights.ambient[ 0 ] = r;
  12926. zlights.ambient[ 1 ] = g;
  12927. zlights.ambient[ 2 ] = b;
  12928. };
  12929. // GL state setting
  12930. this.setFaceCulling = function ( cullFace, frontFace ) {
  12931. if ( cullFace ) {
  12932. if ( !frontFace || frontFace === "ccw" ) {
  12933. _gl.frontFace( _gl.CCW );
  12934. } else {
  12935. _gl.frontFace( _gl.CW );
  12936. }
  12937. if( cullFace === "back" ) {
  12938. _gl.cullFace( _gl.BACK );
  12939. } else if( cullFace === "front" ) {
  12940. _gl.cullFace( _gl.FRONT );
  12941. } else {
  12942. _gl.cullFace( _gl.FRONT_AND_BACK );
  12943. }
  12944. _gl.enable( _gl.CULL_FACE );
  12945. } else {
  12946. _gl.disable( _gl.CULL_FACE );
  12947. }
  12948. };
  12949. this.setMaterialFaces = function ( material ) {
  12950. var doubleSided = material.side === THREE.DoubleSide;
  12951. var flipSided = material.side === THREE.BackSide;
  12952. if ( _oldDoubleSided !== doubleSided ) {
  12953. if ( doubleSided ) {
  12954. _gl.disable( _gl.CULL_FACE );
  12955. } else {
  12956. _gl.enable( _gl.CULL_FACE );
  12957. }
  12958. _oldDoubleSided = doubleSided;
  12959. }
  12960. if ( _oldFlipSided !== flipSided ) {
  12961. if ( flipSided ) {
  12962. _gl.frontFace( _gl.CW );
  12963. } else {
  12964. _gl.frontFace( _gl.CCW );
  12965. }
  12966. _oldFlipSided = flipSided;
  12967. }
  12968. };
  12969. this.setDepthTest = function ( depthTest ) {
  12970. if ( _oldDepthTest !== depthTest ) {
  12971. if ( depthTest ) {
  12972. _gl.enable( _gl.DEPTH_TEST );
  12973. } else {
  12974. _gl.disable( _gl.DEPTH_TEST );
  12975. }
  12976. _oldDepthTest = depthTest;
  12977. }
  12978. };
  12979. this.setDepthWrite = function ( depthWrite ) {
  12980. if ( _oldDepthWrite !== depthWrite ) {
  12981. _gl.depthMask( depthWrite );
  12982. _oldDepthWrite = depthWrite;
  12983. }
  12984. };
  12985. function setLineWidth ( width ) {
  12986. if ( width !== _oldLineWidth ) {
  12987. _gl.lineWidth( width );
  12988. _oldLineWidth = width;
  12989. }
  12990. };
  12991. function setPolygonOffset ( polygonoffset, factor, units ) {
  12992. if ( _oldPolygonOffset !== polygonoffset ) {
  12993. if ( polygonoffset ) {
  12994. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12995. } else {
  12996. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12997. }
  12998. _oldPolygonOffset = polygonoffset;
  12999. }
  13000. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13001. _gl.polygonOffset( factor, units );
  13002. _oldPolygonOffsetFactor = factor;
  13003. _oldPolygonOffsetUnits = units;
  13004. }
  13005. };
  13006. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13007. if ( blending !== _oldBlending ) {
  13008. if ( blending === THREE.NoBlending ) {
  13009. _gl.disable( _gl.BLEND );
  13010. } else if ( blending === THREE.AdditiveBlending ) {
  13011. _gl.enable( _gl.BLEND );
  13012. _gl.blendEquation( _gl.FUNC_ADD );
  13013. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13014. } else if ( blending === THREE.SubtractiveBlending ) {
  13015. // TODO: Find blendFuncSeparate() combination
  13016. _gl.enable( _gl.BLEND );
  13017. _gl.blendEquation( _gl.FUNC_ADD );
  13018. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13019. } else if ( blending === THREE.MultiplyBlending ) {
  13020. // TODO: Find blendFuncSeparate() combination
  13021. _gl.enable( _gl.BLEND );
  13022. _gl.blendEquation( _gl.FUNC_ADD );
  13023. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13024. } else if ( blending === THREE.CustomBlending ) {
  13025. _gl.enable( _gl.BLEND );
  13026. } else {
  13027. _gl.enable( _gl.BLEND );
  13028. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13029. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13030. }
  13031. _oldBlending = blending;
  13032. }
  13033. if ( blending === THREE.CustomBlending ) {
  13034. if ( blendEquation !== _oldBlendEquation ) {
  13035. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13036. _oldBlendEquation = blendEquation;
  13037. }
  13038. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13039. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13040. _oldBlendSrc = blendSrc;
  13041. _oldBlendDst = blendDst;
  13042. }
  13043. } else {
  13044. _oldBlendEquation = null;
  13045. _oldBlendSrc = null;
  13046. _oldBlendDst = null;
  13047. }
  13048. };
  13049. // Defines
  13050. function generateDefines ( defines ) {
  13051. var value, chunk, chunks = [];
  13052. for ( var d in defines ) {
  13053. value = defines[ d ];
  13054. if ( value === false ) continue;
  13055. chunk = "#define " + d + " " + value;
  13056. chunks.push( chunk );
  13057. }
  13058. return chunks.join( "\n" );
  13059. };
  13060. // Shaders
  13061. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13062. var p, pl, d, program, code;
  13063. var chunks = [];
  13064. // Generate code
  13065. if ( shaderID ) {
  13066. chunks.push( shaderID );
  13067. } else {
  13068. chunks.push( fragmentShader );
  13069. chunks.push( vertexShader );
  13070. }
  13071. for ( d in defines ) {
  13072. chunks.push( d );
  13073. chunks.push( defines[ d ] );
  13074. }
  13075. for ( p in parameters ) {
  13076. chunks.push( p );
  13077. chunks.push( parameters[ p ] );
  13078. }
  13079. code = chunks.join();
  13080. // Check if code has been already compiled
  13081. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13082. var programInfo = _programs[ p ];
  13083. if ( programInfo.code === code ) {
  13084. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13085. programInfo.usedTimes ++;
  13086. return programInfo.program;
  13087. }
  13088. }
  13089. //console.log( "building new program " );
  13090. //
  13091. var customDefines = generateDefines( defines );
  13092. //
  13093. program = _gl.createProgram();
  13094. var prefix_vertex = [
  13095. "precision " + _precision + " float;",
  13096. customDefines,
  13097. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13098. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13099. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13100. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13101. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13102. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13103. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13104. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13105. "#define MAX_SHADOWS " + parameters.maxShadows,
  13106. "#define MAX_BONES " + parameters.maxBones,
  13107. parameters.map ? "#define USE_MAP" : "",
  13108. parameters.envMap ? "#define USE_ENVMAP" : "",
  13109. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13110. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13111. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13112. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13113. parameters.vertexColors ? "#define USE_COLOR" : "",
  13114. parameters.skinning ? "#define USE_SKINNING" : "",
  13115. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13116. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13117. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13118. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13119. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13120. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13121. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13122. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13123. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13124. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13125. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13126. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13127. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13128. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13129. "uniform mat4 modelMatrix;",
  13130. "uniform mat4 modelViewMatrix;",
  13131. "uniform mat4 projectionMatrix;",
  13132. "uniform mat4 viewMatrix;",
  13133. "uniform mat3 normalMatrix;",
  13134. "uniform vec3 cameraPosition;",
  13135. "attribute vec3 position;",
  13136. "attribute vec3 normal;",
  13137. "attribute vec2 uv;",
  13138. "attribute vec2 uv2;",
  13139. "#ifdef USE_COLOR",
  13140. "attribute vec3 color;",
  13141. "#endif",
  13142. "#ifdef USE_MORPHTARGETS",
  13143. "attribute vec3 morphTarget0;",
  13144. "attribute vec3 morphTarget1;",
  13145. "attribute vec3 morphTarget2;",
  13146. "attribute vec3 morphTarget3;",
  13147. "#ifdef USE_MORPHNORMALS",
  13148. "attribute vec3 morphNormal0;",
  13149. "attribute vec3 morphNormal1;",
  13150. "attribute vec3 morphNormal2;",
  13151. "attribute vec3 morphNormal3;",
  13152. "#else",
  13153. "attribute vec3 morphTarget4;",
  13154. "attribute vec3 morphTarget5;",
  13155. "attribute vec3 morphTarget6;",
  13156. "attribute vec3 morphTarget7;",
  13157. "#endif",
  13158. "#endif",
  13159. "#ifdef USE_SKINNING",
  13160. "attribute vec4 skinIndex;",
  13161. "attribute vec4 skinWeight;",
  13162. "#endif",
  13163. ""
  13164. ].join("\n");
  13165. var prefix_fragment = [
  13166. "precision " + _precision + " float;",
  13167. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13168. customDefines,
  13169. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13170. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13171. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13172. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13173. "#define MAX_SHADOWS " + parameters.maxShadows,
  13174. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13175. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13176. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13177. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13178. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13179. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13180. parameters.map ? "#define USE_MAP" : "",
  13181. parameters.envMap ? "#define USE_ENVMAP" : "",
  13182. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13183. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13184. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13185. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13186. parameters.vertexColors ? "#define USE_COLOR" : "",
  13187. parameters.metal ? "#define METAL" : "",
  13188. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13189. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13190. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13191. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13192. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13193. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13194. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13195. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13196. "uniform mat4 viewMatrix;",
  13197. "uniform vec3 cameraPosition;",
  13198. ""
  13199. ].join("\n");
  13200. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13201. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13202. _gl.attachShader( program, glVertexShader );
  13203. _gl.attachShader( program, glFragmentShader );
  13204. _gl.linkProgram( program );
  13205. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13206. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13207. }
  13208. // clean up
  13209. _gl.deleteShader( glFragmentShader );
  13210. _gl.deleteShader( glVertexShader );
  13211. //console.log( prefix_fragment + fragmentShader );
  13212. //console.log( prefix_vertex + vertexShader );
  13213. program.uniforms = {};
  13214. program.attributes = {};
  13215. var identifiers, u, a, i;
  13216. // cache uniform locations
  13217. identifiers = [
  13218. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13219. 'morphTargetInfluences'
  13220. ];
  13221. if ( parameters.useVertexTexture ) {
  13222. identifiers.push( 'boneTexture' );
  13223. } else {
  13224. identifiers.push( 'boneGlobalMatrices' );
  13225. }
  13226. for ( u in uniforms ) {
  13227. identifiers.push( u );
  13228. }
  13229. cacheUniformLocations( program, identifiers );
  13230. // cache attributes locations
  13231. identifiers = [
  13232. "position", "normal", "uv", "uv2", "tangent", "color",
  13233. "skinIndex", "skinWeight", "lineDistance"
  13234. ];
  13235. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13236. identifiers.push( "morphTarget" + i );
  13237. }
  13238. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13239. identifiers.push( "morphNormal" + i );
  13240. }
  13241. for ( a in attributes ) {
  13242. identifiers.push( a );
  13243. }
  13244. cacheAttributeLocations( program, identifiers );
  13245. program.id = _programs_counter ++;
  13246. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13247. _this.info.memory.programs = _programs.length;
  13248. return program;
  13249. };
  13250. // Shader parameters cache
  13251. function cacheUniformLocations ( program, identifiers ) {
  13252. var i, l, id;
  13253. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13254. id = identifiers[ i ];
  13255. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13256. }
  13257. };
  13258. function cacheAttributeLocations ( program, identifiers ) {
  13259. var i, l, id;
  13260. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13261. id = identifiers[ i ];
  13262. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  13263. }
  13264. };
  13265. function addLineNumbers ( string ) {
  13266. var chunks = string.split( "\n" );
  13267. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13268. // Chrome reports shader errors on lines
  13269. // starting counting from 1
  13270. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13271. }
  13272. return chunks.join( "\n" );
  13273. };
  13274. function getShader ( type, string ) {
  13275. var shader;
  13276. if ( type === "fragment" ) {
  13277. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13278. } else if ( type === "vertex" ) {
  13279. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13280. }
  13281. _gl.shaderSource( shader, string );
  13282. _gl.compileShader( shader );
  13283. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13284. console.error( _gl.getShaderInfoLog( shader ) );
  13285. console.error( addLineNumbers( string ) );
  13286. return null;
  13287. }
  13288. return shader;
  13289. };
  13290. // Textures
  13291. function isPowerOfTwo ( value ) {
  13292. return ( value & ( value - 1 ) ) === 0;
  13293. };
  13294. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13295. if ( isImagePowerOfTwo ) {
  13296. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13297. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13298. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13299. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13300. } else {
  13301. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13302. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13303. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13304. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13305. }
  13306. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13307. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13308. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13309. texture.__oldAnisotropy = texture.anisotropy;
  13310. }
  13311. }
  13312. };
  13313. this.setTexture = function ( texture, slot ) {
  13314. if ( texture.needsUpdate ) {
  13315. if ( ! texture.__webglInit ) {
  13316. texture.__webglInit = true;
  13317. texture.__webglTexture = _gl.createTexture();
  13318. _this.info.memory.textures ++;
  13319. }
  13320. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13321. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13322. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13323. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13324. var image = texture.image,
  13325. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13326. glFormat = paramThreeToGL( texture.format ),
  13327. glType = paramThreeToGL( texture.type );
  13328. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13329. if ( texture instanceof THREE.CompressedTexture ) {
  13330. var mipmap, mipmaps = texture.mipmaps;
  13331. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13332. mipmap = mipmaps[ i ];
  13333. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13334. }
  13335. } else if ( texture instanceof THREE.DataTexture ) {
  13336. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13337. } else {
  13338. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13339. }
  13340. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13341. texture.needsUpdate = false;
  13342. if ( texture.onUpdate ) texture.onUpdate();
  13343. } else {
  13344. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13345. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13346. }
  13347. };
  13348. function clampToMaxSize ( image, maxSize ) {
  13349. if ( image.width <= maxSize && image.height <= maxSize ) {
  13350. return image;
  13351. }
  13352. // Warning: Scaling through the canvas will only work with images that use
  13353. // premultiplied alpha.
  13354. var maxDimension = Math.max( image.width, image.height );
  13355. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13356. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13357. var canvas = document.createElement( 'canvas' );
  13358. canvas.width = newWidth;
  13359. canvas.height = newHeight;
  13360. var ctx = canvas.getContext( "2d" );
  13361. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13362. return canvas;
  13363. }
  13364. function setCubeTexture ( texture, slot ) {
  13365. if ( texture.image.length === 6 ) {
  13366. if ( texture.needsUpdate ) {
  13367. if ( ! texture.image.__webglTextureCube ) {
  13368. texture.image.__webglTextureCube = _gl.createTexture();
  13369. }
  13370. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13371. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13372. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13373. var isCompressed = texture instanceof THREE.CompressedTexture;
  13374. var cubeImage = [];
  13375. for ( var i = 0; i < 6; i ++ ) {
  13376. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  13377. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13378. } else {
  13379. cubeImage[ i ] = texture.image[ i ];
  13380. }
  13381. }
  13382. var image = cubeImage[ 0 ],
  13383. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13384. glFormat = paramThreeToGL( texture.format ),
  13385. glType = paramThreeToGL( texture.type );
  13386. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13387. for ( var i = 0; i < 6; i ++ ) {
  13388. if ( isCompressed ) {
  13389. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13390. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13391. mipmap = mipmaps[ j ];
  13392. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13393. }
  13394. } else {
  13395. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13396. }
  13397. }
  13398. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13399. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13400. }
  13401. texture.needsUpdate = false;
  13402. if ( texture.onUpdate ) texture.onUpdate();
  13403. } else {
  13404. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13405. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13406. }
  13407. }
  13408. };
  13409. function setCubeTextureDynamic ( texture, slot ) {
  13410. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13411. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13412. };
  13413. // Render targets
  13414. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13415. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13416. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13417. };
  13418. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13419. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13420. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13421. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13422. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13423. /* For some reason this is not working. Defaulting to RGBA4.
  13424. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13425. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13426. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13427. */
  13428. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13429. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13430. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13431. } else {
  13432. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13433. }
  13434. };
  13435. this.setRenderTarget = function ( renderTarget ) {
  13436. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13437. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13438. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13439. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13440. renderTarget.__webglTexture = _gl.createTexture();
  13441. // Setup texture, create render and frame buffers
  13442. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13443. glFormat = paramThreeToGL( renderTarget.format ),
  13444. glType = paramThreeToGL( renderTarget.type );
  13445. if ( isCube ) {
  13446. renderTarget.__webglFramebuffer = [];
  13447. renderTarget.__webglRenderbuffer = [];
  13448. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13449. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13450. for ( var i = 0; i < 6; i ++ ) {
  13451. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13452. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13453. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13454. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13455. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13456. }
  13457. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13458. } else {
  13459. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13460. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13461. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13462. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13463. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13464. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13465. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13466. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13467. }
  13468. // Release everything
  13469. if ( isCube ) {
  13470. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13471. } else {
  13472. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13473. }
  13474. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13475. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  13476. }
  13477. var framebuffer, width, height, vx, vy;
  13478. if ( renderTarget ) {
  13479. if ( isCube ) {
  13480. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13481. } else {
  13482. framebuffer = renderTarget.__webglFramebuffer;
  13483. }
  13484. width = renderTarget.width;
  13485. height = renderTarget.height;
  13486. vx = 0;
  13487. vy = 0;
  13488. } else {
  13489. framebuffer = null;
  13490. width = _viewportWidth;
  13491. height = _viewportHeight;
  13492. vx = _viewportX;
  13493. vy = _viewportY;
  13494. }
  13495. if ( framebuffer !== _currentFramebuffer ) {
  13496. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13497. _gl.viewport( vx, vy, width, height );
  13498. _currentFramebuffer = framebuffer;
  13499. }
  13500. _currentWidth = width;
  13501. _currentHeight = height;
  13502. };
  13503. function updateRenderTargetMipmap ( renderTarget ) {
  13504. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13505. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13506. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13507. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13508. } else {
  13509. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13510. _gl.generateMipmap( _gl.TEXTURE_2D );
  13511. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13512. }
  13513. };
  13514. // Fallback filters for non-power-of-2 textures
  13515. function filterFallback ( f ) {
  13516. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13517. return _gl.NEAREST;
  13518. }
  13519. return _gl.LINEAR;
  13520. };
  13521. // Map three.js constants to WebGL constants
  13522. function paramThreeToGL ( p ) {
  13523. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13524. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13525. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13526. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13527. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13528. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13529. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13530. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13531. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13532. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13533. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13534. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13535. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13536. if ( p === THREE.ByteType ) return _gl.BYTE;
  13537. if ( p === THREE.ShortType ) return _gl.SHORT;
  13538. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13539. if ( p === THREE.IntType ) return _gl.INT;
  13540. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13541. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13542. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13543. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13544. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13545. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13546. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13547. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13548. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13549. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13550. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13551. if ( p === THREE.OneFactor ) return _gl.ONE;
  13552. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13553. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13554. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13555. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13556. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13557. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13558. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13559. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13560. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13561. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13562. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13563. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13564. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13565. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13566. }
  13567. return 0;
  13568. };
  13569. // Allocations
  13570. function allocateBones ( object ) {
  13571. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  13572. return 1024;
  13573. } else {
  13574. // default for when object is not specified
  13575. // ( for example when prebuilding shader
  13576. // to be used with multiple objects )
  13577. //
  13578. // - leave some extra space for other uniforms
  13579. // - limit here is ANGLE's 254 max uniform vectors
  13580. // (up to 54 should be safe)
  13581. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13582. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13583. var maxBones = nVertexMatrices;
  13584. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13585. maxBones = Math.min( object.bones.length, maxBones );
  13586. if ( maxBones < object.bones.length ) {
  13587. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  13588. }
  13589. }
  13590. return maxBones;
  13591. }
  13592. };
  13593. function allocateLights ( lights ) {
  13594. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  13595. dirLights = pointLights = spotLights = hemiLights = 0;
  13596. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13597. light = lights[ l ];
  13598. if ( light.onlyShadow ) continue;
  13599. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13600. if ( light instanceof THREE.PointLight ) pointLights ++;
  13601. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13602. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13603. }
  13604. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  13605. };
  13606. function allocateShadows ( lights ) {
  13607. var l, ll, light, maxShadows = 0;
  13608. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  13609. light = lights[ l ];
  13610. if ( ! light.castShadow ) continue;
  13611. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13612. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13613. }
  13614. return maxShadows;
  13615. };
  13616. // Initialization
  13617. function initGL () {
  13618. try {
  13619. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  13620. throw 'Error creating WebGL context.';
  13621. }
  13622. } catch ( error ) {
  13623. console.error( error );
  13624. }
  13625. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  13626. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  13627. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  13628. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  13629. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13630. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  13631. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  13632. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13633. if ( ! _glExtensionTextureFloat ) {
  13634. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  13635. }
  13636. if ( ! _glExtensionStandardDerivatives ) {
  13637. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  13638. }
  13639. if ( ! _glExtensionTextureFilterAnisotropic ) {
  13640. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  13641. }
  13642. if ( ! _glExtensionCompressedTextureS3TC ) {
  13643. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  13644. }
  13645. };
  13646. function setDefaultGLState () {
  13647. _gl.clearColor( 0, 0, 0, 1 );
  13648. _gl.clearDepth( 1 );
  13649. _gl.clearStencil( 0 );
  13650. _gl.enable( _gl.DEPTH_TEST );
  13651. _gl.depthFunc( _gl.LEQUAL );
  13652. _gl.frontFace( _gl.CCW );
  13653. _gl.cullFace( _gl.BACK );
  13654. _gl.enable( _gl.CULL_FACE );
  13655. _gl.enable( _gl.BLEND );
  13656. _gl.blendEquation( _gl.FUNC_ADD );
  13657. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  13658. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13659. };
  13660. // default plugins (order is important)
  13661. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  13662. this.addPrePlugin( this.shadowMapPlugin );
  13663. this.addPostPlugin( new THREE.SpritePlugin() );
  13664. this.addPostPlugin( new THREE.LensFlarePlugin() );
  13665. };
  13666. /**
  13667. * @author szimek / https://github.com/szimek/
  13668. * @author alteredq / http://alteredqualia.com/
  13669. */
  13670. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13671. this.width = width;
  13672. this.height = height;
  13673. options = options || {};
  13674. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13675. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13676. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13677. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13678. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13679. this.offset = new THREE.Vector2( 0, 0 );
  13680. this.repeat = new THREE.Vector2( 1, 1 );
  13681. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13682. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13683. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13684. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13685. this.generateMipmaps = true;
  13686. };
  13687. THREE.WebGLRenderTarget.prototype.clone = function() {
  13688. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13689. tmp.wrapS = this.wrapS;
  13690. tmp.wrapT = this.wrapT;
  13691. tmp.magFilter = this.magFilter;
  13692. tmp.anisotropy = this.anisotropy;
  13693. tmp.minFilter = this.minFilter;
  13694. tmp.offset.copy( this.offset );
  13695. tmp.repeat.copy( this.repeat );
  13696. tmp.format = this.format;
  13697. tmp.type = this.type;
  13698. tmp.depthBuffer = this.depthBuffer;
  13699. tmp.stencilBuffer = this.stencilBuffer;
  13700. tmp.generateMipmaps = this.generateMipmaps;
  13701. return tmp;
  13702. };
  13703. /**
  13704. * @author alteredq / http://alteredqualia.com
  13705. */
  13706. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13707. THREE.WebGLRenderTarget.call( this, width, height, options );
  13708. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13709. };
  13710. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13711. /**
  13712. * @author mrdoob / http://mrdoob.com/
  13713. */
  13714. THREE.RenderableVertex = function () {
  13715. this.positionWorld = new THREE.Vector3();
  13716. this.positionScreen = new THREE.Vector4();
  13717. this.visible = true;
  13718. };
  13719. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  13720. this.positionWorld.copy( vertex.positionWorld );
  13721. this.positionScreen.copy( vertex.positionScreen );
  13722. }
  13723. /**
  13724. * @author mrdoob / http://mrdoob.com/
  13725. */
  13726. THREE.RenderableFace3 = function () {
  13727. this.v1 = new THREE.RenderableVertex();
  13728. this.v2 = new THREE.RenderableVertex();
  13729. this.v3 = new THREE.RenderableVertex();
  13730. this.centroidWorld = new THREE.Vector3();
  13731. this.centroidScreen = new THREE.Vector3();
  13732. this.normalWorld = new THREE.Vector3();
  13733. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13734. this.vertexNormalsLength = 0;
  13735. this.color = null;
  13736. this.material = null;
  13737. this.uvs = [[]];
  13738. this.z = null;
  13739. };
  13740. /**
  13741. * @author mrdoob / http://mrdoob.com/
  13742. */
  13743. THREE.RenderableFace4 = function () {
  13744. this.v1 = new THREE.RenderableVertex();
  13745. this.v2 = new THREE.RenderableVertex();
  13746. this.v3 = new THREE.RenderableVertex();
  13747. this.v4 = new THREE.RenderableVertex();
  13748. this.centroidWorld = new THREE.Vector3();
  13749. this.centroidScreen = new THREE.Vector3();
  13750. this.normalWorld = new THREE.Vector3();
  13751. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13752. this.vertexNormalsLength = 0;
  13753. this.color = null;
  13754. this.material = null;
  13755. this.uvs = [[]];
  13756. this.z = null;
  13757. };
  13758. /**
  13759. * @author mrdoob / http://mrdoob.com/
  13760. */
  13761. THREE.RenderableObject = function () {
  13762. this.object = null;
  13763. this.z = null;
  13764. };
  13765. /**
  13766. * @author mrdoob / http://mrdoob.com/
  13767. */
  13768. THREE.RenderableParticle = function () {
  13769. this.object = null;
  13770. this.x = null;
  13771. this.y = null;
  13772. this.z = null;
  13773. this.rotation = null;
  13774. this.scale = new THREE.Vector2();
  13775. this.material = null;
  13776. };
  13777. /**
  13778. * @author mrdoob / http://mrdoob.com/
  13779. */
  13780. THREE.RenderableLine = function () {
  13781. this.z = null;
  13782. this.v1 = new THREE.RenderableVertex();
  13783. this.v2 = new THREE.RenderableVertex();
  13784. this.material = null;
  13785. };
  13786. /**
  13787. * @author alteredq / http://alteredqualia.com/
  13788. */
  13789. THREE.ColorUtils = {
  13790. adjustHSV : function ( color, h, s, v ) {
  13791. var hsv = THREE.ColorUtils.__hsv;
  13792. color.getHSV( hsv );
  13793. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  13794. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  13795. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  13796. color.setHSV( hsv.h, hsv.s, hsv.v );
  13797. }
  13798. };
  13799. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13800. * @author mrdoob / http://mrdoob.com/
  13801. * @author alteredq / http://alteredqualia.com/
  13802. */
  13803. THREE.GeometryUtils = {
  13804. // Merge two geometries or geometry and geometry from object (using object's transform)
  13805. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13806. var matrix, matrixRotation,
  13807. vertexOffset = geometry1.vertices.length,
  13808. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13809. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13810. vertices1 = geometry1.vertices,
  13811. vertices2 = geometry2.vertices,
  13812. faces1 = geometry1.faces,
  13813. faces2 = geometry2.faces,
  13814. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13815. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13816. if ( object2 instanceof THREE.Mesh ) {
  13817. object2.matrixAutoUpdate && object2.updateMatrix();
  13818. matrix = object2.matrix;
  13819. matrixRotation = new THREE.Matrix4();
  13820. matrixRotation.extractRotation( matrix, object2.scale );
  13821. }
  13822. // vertices
  13823. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13824. var vertex = vertices2[ i ];
  13825. var vertexCopy = vertex.clone();
  13826. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13827. vertices1.push( vertexCopy );
  13828. }
  13829. // faces
  13830. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13831. var face = faces2[ i ], faceCopy, normal, color,
  13832. faceVertexNormals = face.vertexNormals,
  13833. faceVertexColors = face.vertexColors;
  13834. if ( face instanceof THREE.Face3 ) {
  13835. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13836. } else if ( face instanceof THREE.Face4 ) {
  13837. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13838. }
  13839. faceCopy.normal.copy( face.normal );
  13840. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13841. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13842. normal = faceVertexNormals[ j ].clone();
  13843. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13844. faceCopy.vertexNormals.push( normal );
  13845. }
  13846. faceCopy.color.copy( face.color );
  13847. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13848. color = faceVertexColors[ j ];
  13849. faceCopy.vertexColors.push( color.clone() );
  13850. }
  13851. faceCopy.materialIndex = face.materialIndex;
  13852. faceCopy.centroid.copy( face.centroid );
  13853. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13854. faces1.push( faceCopy );
  13855. }
  13856. // uvs
  13857. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13858. var uv = uvs2[ i ], uvCopy = [];
  13859. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13860. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13861. }
  13862. uvs1.push( uvCopy );
  13863. }
  13864. },
  13865. removeMaterials: function ( geometry, materialIndexArray ) {
  13866. var materialIndexMap = {};
  13867. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  13868. materialIndexMap[ materialIndexArray[i] ] = true;
  13869. }
  13870. var face, newFaces = [];
  13871. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13872. face = geometry.faces[ i ];
  13873. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  13874. }
  13875. geometry.faces = newFaces;
  13876. },
  13877. // Get random point in triangle (via barycentric coordinates)
  13878. // (uniform distribution)
  13879. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13880. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13881. var a, b, c,
  13882. point = new THREE.Vector3(),
  13883. tmp = THREE.GeometryUtils.__v1;
  13884. a = THREE.GeometryUtils.random();
  13885. b = THREE.GeometryUtils.random();
  13886. if ( ( a + b ) > 1 ) {
  13887. a = 1 - a;
  13888. b = 1 - b;
  13889. }
  13890. c = 1 - a - b;
  13891. point.copy( vectorA );
  13892. point.multiplyScalar( a );
  13893. tmp.copy( vectorB );
  13894. tmp.multiplyScalar( b );
  13895. point.addSelf( tmp );
  13896. tmp.copy( vectorC );
  13897. tmp.multiplyScalar( c );
  13898. point.addSelf( tmp );
  13899. return point;
  13900. },
  13901. // Get random point in face (triangle / quad)
  13902. // (uniform distribution)
  13903. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13904. var vA, vB, vC, vD;
  13905. if ( face instanceof THREE.Face3 ) {
  13906. vA = geometry.vertices[ face.a ];
  13907. vB = geometry.vertices[ face.b ];
  13908. vC = geometry.vertices[ face.c ];
  13909. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13910. } else if ( face instanceof THREE.Face4 ) {
  13911. vA = geometry.vertices[ face.a ];
  13912. vB = geometry.vertices[ face.b ];
  13913. vC = geometry.vertices[ face.c ];
  13914. vD = geometry.vertices[ face.d ];
  13915. var area1, area2;
  13916. if ( useCachedAreas ) {
  13917. if ( face._area1 && face._area2 ) {
  13918. area1 = face._area1;
  13919. area2 = face._area2;
  13920. } else {
  13921. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13922. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13923. face._area1 = area1;
  13924. face._area2 = area2;
  13925. }
  13926. } else {
  13927. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13928. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13929. }
  13930. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13931. if ( r < area1 ) {
  13932. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13933. } else {
  13934. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13935. }
  13936. }
  13937. },
  13938. // Get uniformly distributed random points in mesh
  13939. // - create array with cumulative sums of face areas
  13940. // - pick random number from 0 to total area
  13941. // - find corresponding place in area array by binary search
  13942. // - get random point in face
  13943. randomPointsInGeometry: function ( geometry, n ) {
  13944. var face, i,
  13945. faces = geometry.faces,
  13946. vertices = geometry.vertices,
  13947. il = faces.length,
  13948. totalArea = 0,
  13949. cumulativeAreas = [],
  13950. vA, vB, vC, vD;
  13951. // precompute face areas
  13952. for ( i = 0; i < il; i ++ ) {
  13953. face = faces[ i ];
  13954. if ( face instanceof THREE.Face3 ) {
  13955. vA = vertices[ face.a ];
  13956. vB = vertices[ face.b ];
  13957. vC = vertices[ face.c ];
  13958. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13959. } else if ( face instanceof THREE.Face4 ) {
  13960. vA = vertices[ face.a ];
  13961. vB = vertices[ face.b ];
  13962. vC = vertices[ face.c ];
  13963. vD = vertices[ face.d ];
  13964. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13965. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13966. face._area = face._area1 + face._area2;
  13967. }
  13968. totalArea += face._area;
  13969. cumulativeAreas[ i ] = totalArea;
  13970. }
  13971. // binary search cumulative areas array
  13972. function binarySearchIndices( value ) {
  13973. function binarySearch( start, end ) {
  13974. // return closest larger index
  13975. // if exact number is not found
  13976. if ( end < start )
  13977. return start;
  13978. var mid = start + Math.floor( ( end - start ) / 2 );
  13979. if ( cumulativeAreas[ mid ] > value ) {
  13980. return binarySearch( start, mid - 1 );
  13981. } else if ( cumulativeAreas[ mid ] < value ) {
  13982. return binarySearch( mid + 1, end );
  13983. } else {
  13984. return mid;
  13985. }
  13986. }
  13987. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13988. return result;
  13989. }
  13990. // pick random face weighted by face area
  13991. var r, index,
  13992. result = [];
  13993. var stats = {};
  13994. for ( i = 0; i < n; i ++ ) {
  13995. r = THREE.GeometryUtils.random() * totalArea;
  13996. index = binarySearchIndices( r );
  13997. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13998. if ( ! stats[ index ] ) {
  13999. stats[ index ] = 1;
  14000. } else {
  14001. stats[ index ] += 1;
  14002. }
  14003. }
  14004. return result;
  14005. },
  14006. // Get triangle area (by Heron's formula)
  14007. // http://en.wikipedia.org/wiki/Heron%27s_formula
  14008. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14009. var s, a, b, c,
  14010. tmp = THREE.GeometryUtils.__v1;
  14011. tmp.sub( vectorA, vectorB );
  14012. a = tmp.length();
  14013. tmp.sub( vectorA, vectorC );
  14014. b = tmp.length();
  14015. tmp.sub( vectorB, vectorC );
  14016. c = tmp.length();
  14017. s = 0.5 * ( a + b + c );
  14018. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  14019. },
  14020. // Center geometry so that 0,0,0 is in center of bounding box
  14021. center: function ( geometry ) {
  14022. geometry.computeBoundingBox();
  14023. var bb = geometry.boundingBox;
  14024. var offset = new THREE.Vector3();
  14025. offset.add( bb.min, bb.max );
  14026. offset.multiplyScalar( -0.5 );
  14027. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  14028. geometry.computeBoundingBox();
  14029. return offset;
  14030. },
  14031. // Normalize UVs to be from <0,1>
  14032. // (for now just the first set of UVs)
  14033. normalizeUVs: function ( geometry ) {
  14034. var uvSet = geometry.faceVertexUvs[ 0 ];
  14035. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14036. var uvs = uvSet[ i ];
  14037. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14038. // texture repeat
  14039. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  14040. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  14041. }
  14042. }
  14043. },
  14044. triangulateQuads: function ( geometry ) {
  14045. var i, il, j, jl;
  14046. var faces = [];
  14047. var faceUvs = [];
  14048. var faceVertexUvs = [];
  14049. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14050. faceUvs[ i ] = [];
  14051. }
  14052. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14053. faceVertexUvs[ i ] = [];
  14054. }
  14055. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14056. var face = geometry.faces[ i ];
  14057. if ( face instanceof THREE.Face4 ) {
  14058. var a = face.a;
  14059. var b = face.b;
  14060. var c = face.c;
  14061. var d = face.d;
  14062. var triA = new THREE.Face3();
  14063. var triB = new THREE.Face3();
  14064. triA.color.copy( face.color );
  14065. triB.color.copy( face.color );
  14066. triA.materialIndex = face.materialIndex;
  14067. triB.materialIndex = face.materialIndex;
  14068. triA.a = a;
  14069. triA.b = b;
  14070. triA.c = d;
  14071. triB.a = b;
  14072. triB.b = c;
  14073. triB.c = d;
  14074. if ( face.vertexColors.length === 4 ) {
  14075. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14076. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14077. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14078. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14079. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14080. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14081. }
  14082. faces.push( triA, triB );
  14083. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14084. if ( geometry.faceVertexUvs[ j ].length ) {
  14085. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14086. var uvA = uvs[ 0 ];
  14087. var uvB = uvs[ 1 ];
  14088. var uvC = uvs[ 2 ];
  14089. var uvD = uvs[ 3 ];
  14090. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14091. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14092. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14093. }
  14094. }
  14095. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14096. if ( geometry.faceUvs[ j ].length ) {
  14097. var faceUv = geometry.faceUvs[ j ][ i ];
  14098. faceUvs[ j ].push( faceUv, faceUv );
  14099. }
  14100. }
  14101. } else {
  14102. faces.push( face );
  14103. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14104. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14105. }
  14106. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14107. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14108. }
  14109. }
  14110. }
  14111. geometry.faces = faces;
  14112. geometry.faceUvs = faceUvs;
  14113. geometry.faceVertexUvs = faceVertexUvs;
  14114. geometry.computeCentroids();
  14115. geometry.computeFaceNormals();
  14116. geometry.computeVertexNormals();
  14117. if ( geometry.hasTangents ) geometry.computeTangents();
  14118. },
  14119. // Make all faces use unique vertices
  14120. // so that each face can be separated from others
  14121. explode: function( geometry ) {
  14122. var vertices = [];
  14123. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14124. var n = vertices.length;
  14125. var face = geometry.faces[ i ];
  14126. if ( face instanceof THREE.Face4 ) {
  14127. var a = face.a;
  14128. var b = face.b;
  14129. var c = face.c;
  14130. var d = face.d;
  14131. var va = geometry.vertices[ a ];
  14132. var vb = geometry.vertices[ b ];
  14133. var vc = geometry.vertices[ c ];
  14134. var vd = geometry.vertices[ d ];
  14135. vertices.push( va.clone() );
  14136. vertices.push( vb.clone() );
  14137. vertices.push( vc.clone() );
  14138. vertices.push( vd.clone() );
  14139. face.a = n;
  14140. face.b = n + 1;
  14141. face.c = n + 2;
  14142. face.d = n + 3;
  14143. } else {
  14144. var a = face.a;
  14145. var b = face.b;
  14146. var c = face.c;
  14147. var va = geometry.vertices[ a ];
  14148. var vb = geometry.vertices[ b ];
  14149. var vc = geometry.vertices[ c ];
  14150. vertices.push( va.clone() );
  14151. vertices.push( vb.clone() );
  14152. vertices.push( vc.clone() );
  14153. face.a = n;
  14154. face.b = n + 1;
  14155. face.c = n + 2;
  14156. }
  14157. }
  14158. geometry.vertices = vertices;
  14159. delete geometry.__tmpVertices;
  14160. },
  14161. // Break faces with edges longer than maxEdgeLength
  14162. // - not recursive
  14163. tessellate: function ( geometry, maxEdgeLength ) {
  14164. var i, il, face,
  14165. a, b, c, d,
  14166. va, vb, vc, vd,
  14167. dab, dbc, dac, dcd, dad,
  14168. m, m1, m2,
  14169. vm, vm1, vm2,
  14170. vnm, vnm1, vnm2,
  14171. vcm, vcm1, vcm2,
  14172. triA, triB,
  14173. quadA, quadB,
  14174. edge;
  14175. var faces = [];
  14176. var faceVertexUvs = [];
  14177. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14178. faceVertexUvs[ i ] = [];
  14179. }
  14180. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14181. face = geometry.faces[ i ];
  14182. if ( face instanceof THREE.Face3 ) {
  14183. a = face.a;
  14184. b = face.b;
  14185. c = face.c;
  14186. va = geometry.vertices[ a ];
  14187. vb = geometry.vertices[ b ];
  14188. vc = geometry.vertices[ c ];
  14189. dab = va.distanceTo( vb );
  14190. dbc = vb.distanceTo( vc );
  14191. dac = va.distanceTo( vc );
  14192. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14193. m = geometry.vertices.length;
  14194. triA = face.clone();
  14195. triB = face.clone();
  14196. if ( dab >= dbc && dab >= dac ) {
  14197. vm = va.clone();
  14198. vm.lerpSelf( vb, 0.5 );
  14199. triA.a = a;
  14200. triA.b = m;
  14201. triA.c = c;
  14202. triB.a = m;
  14203. triB.b = b;
  14204. triB.c = c;
  14205. if ( face.vertexNormals.length === 3 ) {
  14206. vnm = face.vertexNormals[ 0 ].clone();
  14207. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14208. triA.vertexNormals[ 1 ].copy( vnm );
  14209. triB.vertexNormals[ 0 ].copy( vnm );
  14210. }
  14211. if ( face.vertexColors.length === 3 ) {
  14212. vcm = face.vertexColors[ 0 ].clone();
  14213. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14214. triA.vertexColors[ 1 ].copy( vcm );
  14215. triB.vertexColors[ 0 ].copy( vcm );
  14216. }
  14217. edge = 0;
  14218. } else if ( dbc >= dab && dbc >= dac ) {
  14219. vm = vb.clone();
  14220. vm.lerpSelf( vc, 0.5 );
  14221. triA.a = a;
  14222. triA.b = b;
  14223. triA.c = m;
  14224. triB.a = m;
  14225. triB.b = c;
  14226. triB.c = a;
  14227. if ( face.vertexNormals.length === 3 ) {
  14228. vnm = face.vertexNormals[ 1 ].clone();
  14229. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14230. triA.vertexNormals[ 2 ].copy( vnm );
  14231. triB.vertexNormals[ 0 ].copy( vnm );
  14232. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14233. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14234. }
  14235. if ( face.vertexColors.length === 3 ) {
  14236. vcm = face.vertexColors[ 1 ].clone();
  14237. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14238. triA.vertexColors[ 2 ].copy( vcm );
  14239. triB.vertexColors[ 0 ].copy( vcm );
  14240. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14241. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14242. }
  14243. edge = 1;
  14244. } else {
  14245. vm = va.clone();
  14246. vm.lerpSelf( vc, 0.5 );
  14247. triA.a = a;
  14248. triA.b = b;
  14249. triA.c = m;
  14250. triB.a = m;
  14251. triB.b = b;
  14252. triB.c = c;
  14253. if ( face.vertexNormals.length === 3 ) {
  14254. vnm = face.vertexNormals[ 0 ].clone();
  14255. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14256. triA.vertexNormals[ 2 ].copy( vnm );
  14257. triB.vertexNormals[ 0 ].copy( vnm );
  14258. }
  14259. if ( face.vertexColors.length === 3 ) {
  14260. vcm = face.vertexColors[ 0 ].clone();
  14261. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14262. triA.vertexColors[ 2 ].copy( vcm );
  14263. triB.vertexColors[ 0 ].copy( vcm );
  14264. }
  14265. edge = 2;
  14266. }
  14267. faces.push( triA, triB );
  14268. geometry.vertices.push( vm );
  14269. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14270. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14271. if ( geometry.faceVertexUvs[ j ].length ) {
  14272. uvs = geometry.faceVertexUvs[ j ][ i ];
  14273. uvA = uvs[ 0 ];
  14274. uvB = uvs[ 1 ];
  14275. uvC = uvs[ 2 ];
  14276. // AB
  14277. if ( edge === 0 ) {
  14278. uvM = uvA.clone();
  14279. uvM.lerpSelf( uvB, 0.5 );
  14280. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14281. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14282. // BC
  14283. } else if ( edge === 1 ) {
  14284. uvM = uvB.clone();
  14285. uvM.lerpSelf( uvC, 0.5 );
  14286. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14287. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14288. // AC
  14289. } else {
  14290. uvM = uvA.clone();
  14291. uvM.lerpSelf( uvC, 0.5 );
  14292. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14293. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14294. }
  14295. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14296. }
  14297. }
  14298. } else {
  14299. faces.push( face );
  14300. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14301. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14302. }
  14303. }
  14304. } else {
  14305. a = face.a;
  14306. b = face.b;
  14307. c = face.c;
  14308. d = face.d;
  14309. va = geometry.vertices[ a ];
  14310. vb = geometry.vertices[ b ];
  14311. vc = geometry.vertices[ c ];
  14312. vd = geometry.vertices[ d ];
  14313. dab = va.distanceTo( vb );
  14314. dbc = vb.distanceTo( vc );
  14315. dcd = vc.distanceTo( vd );
  14316. dad = va.distanceTo( vd );
  14317. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14318. m1 = geometry.vertices.length;
  14319. m2 = geometry.vertices.length + 1;
  14320. quadA = face.clone();
  14321. quadB = face.clone();
  14322. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14323. vm1 = va.clone();
  14324. vm1.lerpSelf( vb, 0.5 );
  14325. vm2 = vc.clone();
  14326. vm2.lerpSelf( vd, 0.5 );
  14327. quadA.a = a;
  14328. quadA.b = m1;
  14329. quadA.c = m2;
  14330. quadA.d = d;
  14331. quadB.a = m1;
  14332. quadB.b = b;
  14333. quadB.c = c;
  14334. quadB.d = m2;
  14335. if ( face.vertexNormals.length === 4 ) {
  14336. vnm1 = face.vertexNormals[ 0 ].clone();
  14337. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14338. vnm2 = face.vertexNormals[ 2 ].clone();
  14339. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  14340. quadA.vertexNormals[ 1 ].copy( vnm1 );
  14341. quadA.vertexNormals[ 2 ].copy( vnm2 );
  14342. quadB.vertexNormals[ 0 ].copy( vnm1 );
  14343. quadB.vertexNormals[ 3 ].copy( vnm2 );
  14344. }
  14345. if ( face.vertexColors.length === 4 ) {
  14346. vcm1 = face.vertexColors[ 0 ].clone();
  14347. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14348. vcm2 = face.vertexColors[ 2 ].clone();
  14349. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  14350. quadA.vertexColors[ 1 ].copy( vcm1 );
  14351. quadA.vertexColors[ 2 ].copy( vcm2 );
  14352. quadB.vertexColors[ 0 ].copy( vcm1 );
  14353. quadB.vertexColors[ 3 ].copy( vcm2 );
  14354. }
  14355. edge = 0;
  14356. } else {
  14357. vm1 = vb.clone();
  14358. vm1.lerpSelf( vc, 0.5 );
  14359. vm2 = vd.clone();
  14360. vm2.lerpSelf( va, 0.5 );
  14361. quadA.a = a;
  14362. quadA.b = b;
  14363. quadA.c = m1;
  14364. quadA.d = m2;
  14365. quadB.a = m2;
  14366. quadB.b = m1;
  14367. quadB.c = c;
  14368. quadB.d = d;
  14369. if ( face.vertexNormals.length === 4 ) {
  14370. vnm1 = face.vertexNormals[ 1 ].clone();
  14371. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14372. vnm2 = face.vertexNormals[ 3 ].clone();
  14373. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  14374. quadA.vertexNormals[ 2 ].copy( vnm1 );
  14375. quadA.vertexNormals[ 3 ].copy( vnm2 );
  14376. quadB.vertexNormals[ 0 ].copy( vnm2 );
  14377. quadB.vertexNormals[ 1 ].copy( vnm1 );
  14378. }
  14379. if ( face.vertexColors.length === 4 ) {
  14380. vcm1 = face.vertexColors[ 1 ].clone();
  14381. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14382. vcm2 = face.vertexColors[ 3 ].clone();
  14383. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  14384. quadA.vertexColors[ 2 ].copy( vcm1 );
  14385. quadA.vertexColors[ 3 ].copy( vcm2 );
  14386. quadB.vertexColors[ 0 ].copy( vcm2 );
  14387. quadB.vertexColors[ 1 ].copy( vcm1 );
  14388. }
  14389. edge = 1;
  14390. }
  14391. faces.push( quadA, quadB );
  14392. geometry.vertices.push( vm1, vm2 );
  14393. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  14394. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14395. if ( geometry.faceVertexUvs[ j ].length ) {
  14396. uvs = geometry.faceVertexUvs[ j ][ i ];
  14397. uvA = uvs[ 0 ];
  14398. uvB = uvs[ 1 ];
  14399. uvC = uvs[ 2 ];
  14400. uvD = uvs[ 3 ];
  14401. // AB + CD
  14402. if ( edge === 0 ) {
  14403. uvM1 = uvA.clone();
  14404. uvM1.lerpSelf( uvB, 0.5 );
  14405. uvM2 = uvC.clone();
  14406. uvM2.lerpSelf( uvD, 0.5 );
  14407. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  14408. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  14409. // BC + AD
  14410. } else {
  14411. uvM1 = uvB.clone();
  14412. uvM1.lerpSelf( uvC, 0.5 );
  14413. uvM2 = uvD.clone();
  14414. uvM2.lerpSelf( uvA, 0.5 );
  14415. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  14416. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  14417. }
  14418. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  14419. }
  14420. }
  14421. } else {
  14422. faces.push( face );
  14423. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14424. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14425. }
  14426. }
  14427. }
  14428. }
  14429. geometry.faces = faces;
  14430. geometry.faceVertexUvs = faceVertexUvs;
  14431. }
  14432. };
  14433. THREE.GeometryUtils.random = THREE.Math.random16;
  14434. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14435. /**
  14436. * @author alteredq / http://alteredqualia.com/
  14437. * @author mrdoob / http://mrdoob.com/
  14438. */
  14439. THREE.ImageUtils = {
  14440. crossOrigin: 'anonymous',
  14441. loadTexture: function ( url, mapping, onLoad, onError ) {
  14442. var image = new Image();
  14443. var texture = new THREE.Texture( image, mapping );
  14444. var loader = new THREE.ImageLoader();
  14445. loader.addEventListener( 'load', function ( event ) {
  14446. texture.image = event.content;
  14447. texture.needsUpdate = true;
  14448. if ( onLoad ) onLoad( texture );
  14449. } );
  14450. loader.addEventListener( 'error', function ( event ) {
  14451. if ( onError ) onError( event.message );
  14452. } );
  14453. loader.crossOrigin = this.crossOrigin;
  14454. loader.load( url, image );
  14455. texture.sourceFile = url;
  14456. return texture;
  14457. },
  14458. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14459. var texture = new THREE.CompressedTexture();
  14460. texture.mapping = mapping;
  14461. var request = new XMLHttpRequest();
  14462. request.onload = function () {
  14463. var buffer = request.response;
  14464. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14465. texture.format = dds.format;
  14466. texture.mipmaps = dds.mipmaps;
  14467. texture.image.width = dds.width;
  14468. texture.image.height = dds.height;
  14469. // gl.generateMipmap fails for compressed textures
  14470. // mipmaps must be embedded in the DDS file
  14471. // or texture filters must not use mipmapping
  14472. texture.generateMipmaps = false;
  14473. texture.needsUpdate = true;
  14474. if ( onLoad ) onLoad( texture );
  14475. }
  14476. request.onerror = onError;
  14477. request.open( 'GET', url, true );
  14478. request.responseType = "arraybuffer";
  14479. request.send( null );
  14480. return texture;
  14481. },
  14482. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14483. var images = [];
  14484. images.loadCount = 0;
  14485. var texture = new THREE.Texture();
  14486. texture.image = images;
  14487. if ( mapping !== undefined ) texture.mapping = mapping;
  14488. // no flipping needed for cube textures
  14489. texture.flipY = false;
  14490. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14491. var cubeImage = new Image();
  14492. images[ i ] = cubeImage;
  14493. cubeImage.onload = function () {
  14494. images.loadCount += 1;
  14495. if ( images.loadCount === 6 ) {
  14496. texture.needsUpdate = true;
  14497. if ( onLoad ) onLoad();
  14498. }
  14499. };
  14500. cubeImage.onerror = onError;
  14501. cubeImage.crossOrigin = this.crossOrigin;
  14502. cubeImage.src = array[ i ];
  14503. }
  14504. return texture;
  14505. },
  14506. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14507. var images = [];
  14508. images.loadCount = 0;
  14509. var texture = new THREE.CompressedTexture();
  14510. texture.image = images;
  14511. if ( mapping !== undefined ) texture.mapping = mapping;
  14512. // no flipping for cube textures
  14513. // (also flipping doesn't work for compressed textures )
  14514. texture.flipY = false;
  14515. // can't generate mipmaps for compressed textures
  14516. // mips must be embedded in DDS files
  14517. texture.generateMipmaps = false;
  14518. var generateCubeFaceCallback = function ( rq, img ) {
  14519. return function () {
  14520. var buffer = rq.response;
  14521. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14522. img.format = dds.format;
  14523. img.mipmaps = dds.mipmaps;
  14524. img.width = dds.width;
  14525. img.height = dds.height;
  14526. images.loadCount += 1;
  14527. if ( images.loadCount === 6 ) {
  14528. texture.format = dds.format;
  14529. texture.needsUpdate = true;
  14530. if ( onLoad ) onLoad();
  14531. }
  14532. }
  14533. }
  14534. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14535. var cubeImage = {};
  14536. images[ i ] = cubeImage;
  14537. var request = new XMLHttpRequest();
  14538. request.onload = generateCubeFaceCallback( request, cubeImage );
  14539. request.onerror = onError;
  14540. var url = array[ i ];
  14541. request.open( 'GET', url, true );
  14542. request.responseType = "arraybuffer";
  14543. request.send( null );
  14544. }
  14545. return texture;
  14546. },
  14547. parseDDS: function ( buffer, loadMipmaps ) {
  14548. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  14549. // Adapted from @toji's DDS utils
  14550. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  14551. // All values and structures referenced from:
  14552. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  14553. var DDS_MAGIC = 0x20534444;
  14554. var DDSD_CAPS = 0x1,
  14555. DDSD_HEIGHT = 0x2,
  14556. DDSD_WIDTH = 0x4,
  14557. DDSD_PITCH = 0x8,
  14558. DDSD_PIXELFORMAT = 0x1000,
  14559. DDSD_MIPMAPCOUNT = 0x20000,
  14560. DDSD_LINEARSIZE = 0x80000,
  14561. DDSD_DEPTH = 0x800000;
  14562. var DDSCAPS_COMPLEX = 0x8,
  14563. DDSCAPS_MIPMAP = 0x400000,
  14564. DDSCAPS_TEXTURE = 0x1000;
  14565. var DDSCAPS2_CUBEMAP = 0x200,
  14566. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  14567. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  14568. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  14569. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  14570. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  14571. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  14572. DDSCAPS2_VOLUME = 0x200000;
  14573. var DDPF_ALPHAPIXELS = 0x1,
  14574. DDPF_ALPHA = 0x2,
  14575. DDPF_FOURCC = 0x4,
  14576. DDPF_RGB = 0x40,
  14577. DDPF_YUV = 0x200,
  14578. DDPF_LUMINANCE = 0x20000;
  14579. function fourCCToInt32( value ) {
  14580. return value.charCodeAt(0) +
  14581. (value.charCodeAt(1) << 8) +
  14582. (value.charCodeAt(2) << 16) +
  14583. (value.charCodeAt(3) << 24);
  14584. }
  14585. function int32ToFourCC( value ) {
  14586. return String.fromCharCode(
  14587. value & 0xff,
  14588. (value >> 8) & 0xff,
  14589. (value >> 16) & 0xff,
  14590. (value >> 24) & 0xff
  14591. );
  14592. }
  14593. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  14594. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  14595. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  14596. var headerLengthInt = 31; // The header length in 32 bit ints
  14597. // Offsets into the header array
  14598. var off_magic = 0;
  14599. var off_size = 1;
  14600. var off_flags = 2;
  14601. var off_height = 3;
  14602. var off_width = 4;
  14603. var off_mipmapCount = 7;
  14604. var off_pfFlags = 20;
  14605. var off_pfFourCC = 21;
  14606. // Parse header
  14607. var header = new Int32Array( buffer, 0, headerLengthInt );
  14608. if ( header[ off_magic ] !== DDS_MAGIC ) {
  14609. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  14610. return dds;
  14611. }
  14612. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  14613. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  14614. return dds;
  14615. }
  14616. var blockBytes;
  14617. var fourCC = header[ off_pfFourCC ];
  14618. switch ( fourCC ) {
  14619. case FOURCC_DXT1:
  14620. blockBytes = 8;
  14621. dds.format = THREE.RGB_S3TC_DXT1_Format;
  14622. break;
  14623. case FOURCC_DXT3:
  14624. blockBytes = 16;
  14625. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  14626. break;
  14627. case FOURCC_DXT5:
  14628. blockBytes = 16;
  14629. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  14630. break;
  14631. default:
  14632. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  14633. return dds;
  14634. }
  14635. dds.mipmapCount = 1;
  14636. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  14637. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  14638. }
  14639. dds.width = header[ off_width ];
  14640. dds.height = header[ off_height ];
  14641. var dataOffset = header[ off_size ] + 4;
  14642. // Extract mipmaps buffers
  14643. var width = dds.width;
  14644. var height = dds.height;
  14645. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14646. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  14647. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  14648. var mipmap = { "data": byteArray, "width": width, "height": height };
  14649. dds.mipmaps.push( mipmap );
  14650. dataOffset += dataLength;
  14651. width = Math.max( width * 0.5, 1 );
  14652. height = Math.max( height * 0.5, 1 );
  14653. }
  14654. return dds;
  14655. },
  14656. getNormalMap: function ( image, depth ) {
  14657. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  14658. var cross = function ( a, b ) {
  14659. 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 ] ];
  14660. }
  14661. var subtract = function ( a, b ) {
  14662. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  14663. }
  14664. var normalize = function ( a ) {
  14665. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  14666. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  14667. }
  14668. depth = depth | 1;
  14669. var width = image.width;
  14670. var height = image.height;
  14671. var canvas = document.createElement( 'canvas' );
  14672. canvas.width = width;
  14673. canvas.height = height;
  14674. var context = canvas.getContext( '2d' );
  14675. context.drawImage( image, 0, 0 );
  14676. var data = context.getImageData( 0, 0, width, height ).data;
  14677. var imageData = context.createImageData( width, height );
  14678. var output = imageData.data;
  14679. for ( var x = 0; x < width; x ++ ) {
  14680. for ( var y = 0; y < height; y ++ ) {
  14681. var ly = y - 1 < 0 ? 0 : y - 1;
  14682. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  14683. var lx = x - 1 < 0 ? 0 : x - 1;
  14684. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  14685. var points = [];
  14686. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  14687. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  14688. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  14689. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  14690. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  14691. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  14692. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  14693. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  14694. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  14695. var normals = [];
  14696. var num_points = points.length;
  14697. for ( var i = 0; i < num_points; i ++ ) {
  14698. var v1 = points[ i ];
  14699. var v2 = points[ ( i + 1 ) % num_points ];
  14700. v1 = subtract( v1, origin );
  14701. v2 = subtract( v2, origin );
  14702. normals.push( normalize( cross( v1, v2 ) ) );
  14703. }
  14704. var normal = [ 0, 0, 0 ];
  14705. for ( var i = 0; i < normals.length; i ++ ) {
  14706. normal[ 0 ] += normals[ i ][ 0 ];
  14707. normal[ 1 ] += normals[ i ][ 1 ];
  14708. normal[ 2 ] += normals[ i ][ 2 ];
  14709. }
  14710. normal[ 0 ] /= normals.length;
  14711. normal[ 1 ] /= normals.length;
  14712. normal[ 2 ] /= normals.length;
  14713. var idx = ( y * width + x ) * 4;
  14714. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14715. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14716. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  14717. output[ idx + 3 ] = 255;
  14718. }
  14719. }
  14720. context.putImageData( imageData, 0, 0 );
  14721. return canvas;
  14722. },
  14723. generateDataTexture: function ( width, height, color ) {
  14724. var size = width * height;
  14725. var data = new Uint8Array( 3 * size );
  14726. var r = Math.floor( color.r * 255 );
  14727. var g = Math.floor( color.g * 255 );
  14728. var b = Math.floor( color.b * 255 );
  14729. for ( var i = 0; i < size; i ++ ) {
  14730. data[ i * 3 ] = r;
  14731. data[ i * 3 + 1 ] = g;
  14732. data[ i * 3 + 2 ] = b;
  14733. }
  14734. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  14735. texture.needsUpdate = true;
  14736. return texture;
  14737. }
  14738. };
  14739. /**
  14740. * @author alteredq / http://alteredqualia.com/
  14741. */
  14742. THREE.SceneUtils = {
  14743. createMultiMaterialObject: function ( geometry, materials ) {
  14744. var group = new THREE.Object3D();
  14745. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14746. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  14747. }
  14748. return group;
  14749. },
  14750. detach : function ( child, parent, scene ) {
  14751. child.applyMatrix( parent.matrixWorld );
  14752. parent.remove( child );
  14753. scene.add( child );
  14754. },
  14755. attach: function ( child, scene, parent ) {
  14756. var matrixWorldInverse = new THREE.Matrix4();
  14757. matrixWorldInverse.getInverse( parent.matrixWorld );
  14758. child.applyMatrix( matrixWorldInverse );
  14759. scene.remove( child );
  14760. parent.add( child );
  14761. }
  14762. };
  14763. /**
  14764. * @author alteredq / http://alteredqualia.com/
  14765. * @author mrdoob / http://mrdoob.com/
  14766. *
  14767. * ShaderUtils currently contains:
  14768. *
  14769. * fresnel
  14770. * normal
  14771. * cube
  14772. *
  14773. */
  14774. THREE.ShaderUtils = {
  14775. lib: {
  14776. /* -------------------------------------------------------------------------
  14777. // Fresnel shader
  14778. // - based on Nvidia Cg tutorial
  14779. ------------------------------------------------------------------------- */
  14780. 'fresnel': {
  14781. uniforms: {
  14782. "mRefractionRatio": { type: "f", value: 1.02 },
  14783. "mFresnelBias": { type: "f", value: 0.1 },
  14784. "mFresnelPower": { type: "f", value: 2.0 },
  14785. "mFresnelScale": { type: "f", value: 1.0 },
  14786. "tCube": { type: "t", value: null }
  14787. },
  14788. fragmentShader: [
  14789. "uniform samplerCube tCube;",
  14790. "varying vec3 vReflect;",
  14791. "varying vec3 vRefract[3];",
  14792. "varying float vReflectionFactor;",
  14793. "void main() {",
  14794. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14795. "vec4 refractedColor = vec4( 1.0 );",
  14796. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  14797. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  14798. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  14799. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14800. "}"
  14801. ].join("\n"),
  14802. vertexShader: [
  14803. "uniform float mRefractionRatio;",
  14804. "uniform float mFresnelBias;",
  14805. "uniform float mFresnelScale;",
  14806. "uniform float mFresnelPower;",
  14807. "varying vec3 vReflect;",
  14808. "varying vec3 vRefract[3];",
  14809. "varying float vReflectionFactor;",
  14810. "void main() {",
  14811. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14812. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  14813. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14814. "vec3 I = worldPosition.xyz - cameraPosition;",
  14815. "vReflect = reflect( I, worldNormal );",
  14816. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  14817. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  14818. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  14819. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  14820. "gl_Position = projectionMatrix * mvPosition;",
  14821. "}"
  14822. ].join("\n")
  14823. },
  14824. /* -------------------------------------------------------------------------
  14825. // Normal map shader
  14826. // - Blinn-Phong
  14827. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14828. // - point and directional lights (use with "lights: true" material option)
  14829. ------------------------------------------------------------------------- */
  14830. 'normal' : {
  14831. uniforms: THREE.UniformsUtils.merge( [
  14832. THREE.UniformsLib[ "fog" ],
  14833. THREE.UniformsLib[ "lights" ],
  14834. THREE.UniformsLib[ "shadowmap" ],
  14835. {
  14836. "enableAO" : { type: "i", value: 0 },
  14837. "enableDiffuse" : { type: "i", value: 0 },
  14838. "enableSpecular" : { type: "i", value: 0 },
  14839. "enableReflection": { type: "i", value: 0 },
  14840. "enableDisplacement": { type: "i", value: 0 },
  14841. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  14842. "tDiffuse" : { type: "t", value: null },
  14843. "tCube" : { type: "t", value: null },
  14844. "tNormal" : { type: "t", value: null },
  14845. "tSpecular" : { type: "t", value: null },
  14846. "tAO" : { type: "t", value: null },
  14847. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14848. "uDisplacementBias": { type: "f", value: 0.0 },
  14849. "uDisplacementScale": { type: "f", value: 1.0 },
  14850. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14851. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14852. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14853. "uShininess": { type: "f", value: 30 },
  14854. "uOpacity": { type: "f", value: 1 },
  14855. "useRefract": { type: "i", value: 0 },
  14856. "uRefractionRatio": { type: "f", value: 0.98 },
  14857. "uReflectivity": { type: "f", value: 0.5 },
  14858. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14859. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14860. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14861. }
  14862. ] ),
  14863. fragmentShader: [
  14864. "uniform vec3 uAmbientColor;",
  14865. "uniform vec3 uDiffuseColor;",
  14866. "uniform vec3 uSpecularColor;",
  14867. "uniform float uShininess;",
  14868. "uniform float uOpacity;",
  14869. "uniform bool enableDiffuse;",
  14870. "uniform bool enableSpecular;",
  14871. "uniform bool enableAO;",
  14872. "uniform bool enableReflection;",
  14873. "uniform sampler2D tDiffuse;",
  14874. "uniform sampler2D tNormal;",
  14875. "uniform sampler2D tSpecular;",
  14876. "uniform sampler2D tAO;",
  14877. "uniform samplerCube tCube;",
  14878. "uniform vec2 uNormalScale;",
  14879. "uniform bool useRefract;",
  14880. "uniform float uRefractionRatio;",
  14881. "uniform float uReflectivity;",
  14882. "varying vec3 vTangent;",
  14883. "varying vec3 vBinormal;",
  14884. "varying vec3 vNormal;",
  14885. "varying vec2 vUv;",
  14886. "uniform vec3 ambientLightColor;",
  14887. "#if MAX_DIR_LIGHTS > 0",
  14888. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14889. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14890. "#endif",
  14891. "#if MAX_HEMI_LIGHTS > 0",
  14892. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  14893. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  14894. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  14895. "#endif",
  14896. "#if MAX_POINT_LIGHTS > 0",
  14897. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14898. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14899. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14900. "#endif",
  14901. "#if MAX_SPOT_LIGHTS > 0",
  14902. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14903. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14904. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14905. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  14906. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14907. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14908. "#endif",
  14909. "#ifdef WRAP_AROUND",
  14910. "uniform vec3 wrapRGB;",
  14911. "#endif",
  14912. "varying vec3 vWorldPosition;",
  14913. "varying vec3 vViewPosition;",
  14914. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14915. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14916. "void main() {",
  14917. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14918. "vec3 specularTex = vec3( 1.0 );",
  14919. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14920. "normalTex.xy *= uNormalScale;",
  14921. "normalTex = normalize( normalTex );",
  14922. "if( enableDiffuse ) {",
  14923. "#ifdef GAMMA_INPUT",
  14924. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14925. "texelColor.xyz *= texelColor.xyz;",
  14926. "gl_FragColor = gl_FragColor * texelColor;",
  14927. "#else",
  14928. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14929. "#endif",
  14930. "}",
  14931. "if( enableAO ) {",
  14932. "#ifdef GAMMA_INPUT",
  14933. "vec4 aoColor = texture2D( tAO, vUv );",
  14934. "aoColor.xyz *= aoColor.xyz;",
  14935. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14936. "#else",
  14937. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14938. "#endif",
  14939. "}",
  14940. "if( enableSpecular )",
  14941. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14942. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14943. "vec3 finalNormal = tsb * normalTex;",
  14944. "#ifdef FLIP_SIDED",
  14945. "finalNormal = -finalNormal;",
  14946. "#endif",
  14947. "vec3 normal = normalize( finalNormal );",
  14948. "vec3 viewPosition = normalize( vViewPosition );",
  14949. // point lights
  14950. "#if MAX_POINT_LIGHTS > 0",
  14951. "vec3 pointDiffuse = vec3( 0.0 );",
  14952. "vec3 pointSpecular = vec3( 0.0 );",
  14953. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14954. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14955. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14956. "float pointDistance = 1.0;",
  14957. "if ( pointLightDistance[ i ] > 0.0 )",
  14958. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14959. "pointVector = normalize( pointVector );",
  14960. // diffuse
  14961. "#ifdef WRAP_AROUND",
  14962. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14963. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14964. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14965. "#else",
  14966. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14967. "#endif",
  14968. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14969. // specular
  14970. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14971. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14972. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  14973. "#ifdef PHYSICALLY_BASED_SHADING",
  14974. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14975. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14976. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  14977. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14978. "#else",
  14979. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14980. "#endif",
  14981. "}",
  14982. "#endif",
  14983. // spot lights
  14984. "#if MAX_SPOT_LIGHTS > 0",
  14985. "vec3 spotDiffuse = vec3( 0.0 );",
  14986. "vec3 spotSpecular = vec3( 0.0 );",
  14987. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14988. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14989. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14990. "float spotDistance = 1.0;",
  14991. "if ( spotLightDistance[ i ] > 0.0 )",
  14992. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14993. "spotVector = normalize( spotVector );",
  14994. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14995. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  14996. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  14997. // diffuse
  14998. "#ifdef WRAP_AROUND",
  14999. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15000. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15001. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15002. "#else",
  15003. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15004. "#endif",
  15005. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15006. // specular
  15007. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15008. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15009. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15010. "#ifdef PHYSICALLY_BASED_SHADING",
  15011. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15012. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15013. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15014. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15015. "#else",
  15016. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15017. "#endif",
  15018. "}",
  15019. "}",
  15020. "#endif",
  15021. // directional lights
  15022. "#if MAX_DIR_LIGHTS > 0",
  15023. "vec3 dirDiffuse = vec3( 0.0 );",
  15024. "vec3 dirSpecular = vec3( 0.0 );",
  15025. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15026. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15027. "vec3 dirVector = normalize( lDirection.xyz );",
  15028. // diffuse
  15029. "#ifdef WRAP_AROUND",
  15030. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15031. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15032. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15033. "#else",
  15034. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15035. "#endif",
  15036. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15037. // specular
  15038. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15039. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15040. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15041. "#ifdef PHYSICALLY_BASED_SHADING",
  15042. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15043. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15044. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15045. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15046. "#else",
  15047. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15048. "#endif",
  15049. "}",
  15050. "#endif",
  15051. // hemisphere lights
  15052. "#if MAX_HEMI_LIGHTS > 0",
  15053. "vec3 hemiDiffuse = vec3( 0.0 );",
  15054. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15055. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15056. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15057. "vec3 lVector = normalize( lDirection.xyz );",
  15058. // diffuse
  15059. "float dotProduct = dot( normal, lVector );",
  15060. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15061. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15062. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15063. // specular (sky light)
  15064. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15065. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15066. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15067. // specular (ground light)
  15068. "vec3 lVectorGround = -lVector;",
  15069. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15070. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15071. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15072. "#ifdef PHYSICALLY_BASED_SHADING",
  15073. "float dotProductGround = dot( normal, lVectorGround );",
  15074. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15075. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15076. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15077. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15078. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15079. "#else",
  15080. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15081. "#endif",
  15082. "}",
  15083. "#endif",
  15084. // all lights contribution summation
  15085. "vec3 totalDiffuse = vec3( 0.0 );",
  15086. "vec3 totalSpecular = vec3( 0.0 );",
  15087. "#if MAX_DIR_LIGHTS > 0",
  15088. "totalDiffuse += dirDiffuse;",
  15089. "totalSpecular += dirSpecular;",
  15090. "#endif",
  15091. "#if MAX_HEMI_LIGHTS > 0",
  15092. "totalDiffuse += hemiDiffuse;",
  15093. "totalSpecular += hemiSpecular;",
  15094. "#endif",
  15095. "#if MAX_POINT_LIGHTS > 0",
  15096. "totalDiffuse += pointDiffuse;",
  15097. "totalSpecular += pointSpecular;",
  15098. "#endif",
  15099. "#if MAX_SPOT_LIGHTS > 0",
  15100. "totalDiffuse += spotDiffuse;",
  15101. "totalSpecular += spotSpecular;",
  15102. "#endif",
  15103. "#ifdef METAL",
  15104. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15105. "#else",
  15106. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15107. "#endif",
  15108. "if ( enableReflection ) {",
  15109. "vec3 vReflect;",
  15110. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15111. "if ( useRefract ) {",
  15112. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15113. "} else {",
  15114. "vReflect = reflect( cameraToVertex, normal );",
  15115. "}",
  15116. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15117. "#ifdef GAMMA_INPUT",
  15118. "cubeColor.xyz *= cubeColor.xyz;",
  15119. "#endif",
  15120. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15121. "}",
  15122. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15123. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15124. THREE.ShaderChunk[ "fog_fragment" ],
  15125. "}"
  15126. ].join("\n"),
  15127. vertexShader: [
  15128. "attribute vec4 tangent;",
  15129. "uniform vec2 uOffset;",
  15130. "uniform vec2 uRepeat;",
  15131. "uniform bool enableDisplacement;",
  15132. "#ifdef VERTEX_TEXTURES",
  15133. "uniform sampler2D tDisplacement;",
  15134. "uniform float uDisplacementScale;",
  15135. "uniform float uDisplacementBias;",
  15136. "#endif",
  15137. "varying vec3 vTangent;",
  15138. "varying vec3 vBinormal;",
  15139. "varying vec3 vNormal;",
  15140. "varying vec2 vUv;",
  15141. "varying vec3 vWorldPosition;",
  15142. "varying vec3 vViewPosition;",
  15143. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15144. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15145. "void main() {",
  15146. THREE.ShaderChunk[ "skinbase_vertex" ],
  15147. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15148. // normal, tangent and binormal vectors
  15149. "#ifdef USE_SKINNING",
  15150. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15151. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15152. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15153. "#else",
  15154. "vNormal = normalize( normalMatrix * normal );",
  15155. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15156. "#endif",
  15157. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15158. "vUv = uv * uRepeat + uOffset;",
  15159. // displacement mapping
  15160. "vec3 displacedPosition;",
  15161. "#ifdef VERTEX_TEXTURES",
  15162. "if ( enableDisplacement ) {",
  15163. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15164. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15165. "displacedPosition = position + normalize( normal ) * df;",
  15166. "} else {",
  15167. "#ifdef USE_SKINNING",
  15168. "vec4 skinVertex = vec4( position, 1.0 );",
  15169. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15170. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15171. "displacedPosition = skinned.xyz;",
  15172. "#else",
  15173. "displacedPosition = position;",
  15174. "#endif",
  15175. "}",
  15176. "#else",
  15177. "#ifdef USE_SKINNING",
  15178. "vec4 skinVertex = vec4( position, 1.0 );",
  15179. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15180. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15181. "displacedPosition = skinned.xyz;",
  15182. "#else",
  15183. "displacedPosition = position;",
  15184. "#endif",
  15185. "#endif",
  15186. //
  15187. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15188. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15189. "gl_Position = projectionMatrix * mvPosition;",
  15190. //
  15191. "vWorldPosition = worldPosition.xyz;",
  15192. "vViewPosition = -mvPosition.xyz;",
  15193. // shadows
  15194. "#ifdef USE_SHADOWMAP",
  15195. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15196. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15197. "}",
  15198. "#endif",
  15199. "}"
  15200. ].join("\n")
  15201. },
  15202. /* -------------------------------------------------------------------------
  15203. // Cube map shader
  15204. ------------------------------------------------------------------------- */
  15205. 'cube': {
  15206. uniforms: { "tCube": { type: "t", value: null },
  15207. "tFlip": { type: "f", value: -1 } },
  15208. vertexShader: [
  15209. "varying vec3 vWorldPosition;",
  15210. "void main() {",
  15211. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15212. "vWorldPosition = worldPosition.xyz;",
  15213. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15214. "}"
  15215. ].join("\n"),
  15216. fragmentShader: [
  15217. "uniform samplerCube tCube;",
  15218. "uniform float tFlip;",
  15219. "varying vec3 vWorldPosition;",
  15220. "void main() {",
  15221. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15222. "}"
  15223. ].join("\n")
  15224. }
  15225. }
  15226. };
  15227. /**
  15228. * @author zz85 / http://www.lab4games.net/zz85/blog
  15229. * @author alteredq / http://alteredqualia.com/
  15230. *
  15231. * For Text operations in three.js (See TextGeometry)
  15232. *
  15233. * It uses techniques used in:
  15234. *
  15235. * typeface.js and canvastext
  15236. * For converting fonts and rendering with javascript
  15237. * http://typeface.neocracy.org
  15238. *
  15239. * Triangulation ported from AS3
  15240. * Simple Polygon Triangulation
  15241. * http://actionsnippet.com/?p=1462
  15242. *
  15243. * A Method to triangulate shapes with holes
  15244. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15245. *
  15246. */
  15247. THREE.FontUtils = {
  15248. faces : {},
  15249. // Just for now. face[weight][style]
  15250. face : "helvetiker",
  15251. weight: "normal",
  15252. style : "normal",
  15253. size : 150,
  15254. divisions : 10,
  15255. getFace : function() {
  15256. return this.faces[ this.face ][ this.weight ][ this.style ];
  15257. },
  15258. loadFace : function( data ) {
  15259. var family = data.familyName.toLowerCase();
  15260. var ThreeFont = this;
  15261. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15262. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15263. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15264. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15265. return data;
  15266. },
  15267. drawText : function( text ) {
  15268. var characterPts = [], allPts = [];
  15269. // RenderText
  15270. var i, p,
  15271. face = this.getFace(),
  15272. scale = this.size / face.resolution,
  15273. offset = 0,
  15274. chars = String( text ).split( '' ),
  15275. length = chars.length;
  15276. var fontPaths = [];
  15277. for ( i = 0; i < length; i ++ ) {
  15278. var path = new THREE.Path();
  15279. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15280. offset += ret.offset;
  15281. fontPaths.push( ret.path );
  15282. }
  15283. // get the width
  15284. var width = offset / 2;
  15285. //
  15286. // for ( p = 0; p < allPts.length; p++ ) {
  15287. //
  15288. // allPts[ p ].x -= width;
  15289. //
  15290. // }
  15291. //var extract = this.extractPoints( allPts, characterPts );
  15292. //extract.contour = allPts;
  15293. //extract.paths = fontPaths;
  15294. //extract.offset = width;
  15295. return { paths : fontPaths, offset : width };
  15296. },
  15297. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15298. var pts = [];
  15299. var i, i2, divisions,
  15300. outline, action, length,
  15301. scaleX, scaleY,
  15302. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15303. laste,
  15304. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15305. if ( !glyph ) return;
  15306. if ( glyph.o ) {
  15307. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15308. length = outline.length;
  15309. scaleX = scale;
  15310. scaleY = scale;
  15311. for ( i = 0; i < length; ) {
  15312. action = outline[ i ++ ];
  15313. //console.log( action );
  15314. switch( action ) {
  15315. case 'm':
  15316. // Move To
  15317. x = outline[ i++ ] * scaleX + offset;
  15318. y = outline[ i++ ] * scaleY;
  15319. path.moveTo( x, y );
  15320. break;
  15321. case 'l':
  15322. // Line To
  15323. x = outline[ i++ ] * scaleX + offset;
  15324. y = outline[ i++ ] * scaleY;
  15325. path.lineTo(x,y);
  15326. break;
  15327. case 'q':
  15328. // QuadraticCurveTo
  15329. cpx = outline[ i++ ] * scaleX + offset;
  15330. cpy = outline[ i++ ] * scaleY;
  15331. cpx1 = outline[ i++ ] * scaleX + offset;
  15332. cpy1 = outline[ i++ ] * scaleY;
  15333. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15334. laste = pts[ pts.length - 1 ];
  15335. if ( laste ) {
  15336. cpx0 = laste.x;
  15337. cpy0 = laste.y;
  15338. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15339. var t = i2 / divisions;
  15340. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15341. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15342. }
  15343. }
  15344. break;
  15345. case 'b':
  15346. // Cubic Bezier Curve
  15347. cpx = outline[ i++ ] * scaleX + offset;
  15348. cpy = outline[ i++ ] * scaleY;
  15349. cpx1 = outline[ i++ ] * scaleX + offset;
  15350. cpy1 = outline[ i++ ] * -scaleY;
  15351. cpx2 = outline[ i++ ] * scaleX + offset;
  15352. cpy2 = outline[ i++ ] * -scaleY;
  15353. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15354. laste = pts[ pts.length - 1 ];
  15355. if ( laste ) {
  15356. cpx0 = laste.x;
  15357. cpy0 = laste.y;
  15358. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15359. var t = i2 / divisions;
  15360. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15361. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15362. }
  15363. }
  15364. break;
  15365. }
  15366. }
  15367. }
  15368. return { offset: glyph.ha*scale, path:path};
  15369. }
  15370. };
  15371. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15372. // Parameters
  15373. parameters = parameters || {};
  15374. var size = parameters.size !== undefined ? parameters.size : 100;
  15375. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15376. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15377. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15378. var style = parameters.style !== undefined ? parameters.style : "normal";
  15379. THREE.FontUtils.size = size;
  15380. THREE.FontUtils.divisions = curveSegments;
  15381. THREE.FontUtils.face = font;
  15382. THREE.FontUtils.weight = weight;
  15383. THREE.FontUtils.style = style;
  15384. // Get a Font data json object
  15385. var data = THREE.FontUtils.drawText( text );
  15386. var paths = data.paths;
  15387. var shapes = [];
  15388. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15389. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15390. }
  15391. return shapes;
  15392. };
  15393. /**
  15394. * This code is a quick port of code written in C++ which was submitted to
  15395. * flipcode.com by John W. Ratcliff // July 22, 2000
  15396. * See original code and more information here:
  15397. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15398. *
  15399. * ported to actionscript by Zevan Rosser
  15400. * www.actionsnippet.com
  15401. *
  15402. * ported to javascript by Joshua Koo
  15403. * http://www.lab4games.net/zz85/blog
  15404. *
  15405. */
  15406. ( function( namespace ) {
  15407. var EPSILON = 0.0000000001;
  15408. // takes in an contour array and returns
  15409. var process = function( contour, indices ) {
  15410. var n = contour.length;
  15411. if ( n < 3 ) return null;
  15412. var result = [],
  15413. verts = [],
  15414. vertIndices = [];
  15415. /* we want a counter-clockwise polygon in verts */
  15416. var u, v, w;
  15417. if ( area( contour ) > 0.0 ) {
  15418. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15419. } else {
  15420. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15421. }
  15422. var nv = n;
  15423. /* remove nv - 2 vertices, creating 1 triangle every time */
  15424. var count = 2 * nv; /* error detection */
  15425. for( v = nv - 1; nv > 2; ) {
  15426. /* if we loop, it is probably a non-simple polygon */
  15427. if ( ( count-- ) <= 0 ) {
  15428. //** Triangulate: ERROR - probable bad polygon!
  15429. //throw ( "Warning, unable to triangulate polygon!" );
  15430. //return null;
  15431. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15432. console.log( "Warning, unable to triangulate polygon!" );
  15433. if ( indices ) return vertIndices;
  15434. return result;
  15435. }
  15436. /* three consecutive vertices in current polygon, <u,v,w> */
  15437. u = v; if ( nv <= u ) u = 0; /* previous */
  15438. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15439. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15440. if ( snip( contour, u, v, w, nv, verts ) ) {
  15441. var a, b, c, s, t;
  15442. /* true names of the vertices */
  15443. a = verts[ u ];
  15444. b = verts[ v ];
  15445. c = verts[ w ];
  15446. /* output Triangle */
  15447. /*
  15448. result.push( contour[ a ] );
  15449. result.push( contour[ b ] );
  15450. result.push( contour[ c ] );
  15451. */
  15452. result.push( [ contour[ a ],
  15453. contour[ b ],
  15454. contour[ c ] ] );
  15455. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15456. /* remove v from the remaining polygon */
  15457. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15458. verts[ s ] = verts[ t ];
  15459. }
  15460. nv--;
  15461. /* reset error detection counter */
  15462. count = 2 * nv;
  15463. }
  15464. }
  15465. if ( indices ) return vertIndices;
  15466. return result;
  15467. };
  15468. // calculate area of the contour polygon
  15469. var area = function ( contour ) {
  15470. var n = contour.length;
  15471. var a = 0.0;
  15472. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15473. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15474. }
  15475. return a * 0.5;
  15476. };
  15477. // see if p is inside triangle abc
  15478. var insideTriangle = function( ax, ay,
  15479. bx, by,
  15480. cx, cy,
  15481. px, py ) {
  15482. var aX, aY, bX, bY;
  15483. var cX, cY, apx, apy;
  15484. var bpx, bpy, cpx, cpy;
  15485. var cCROSSap, bCROSScp, aCROSSbp;
  15486. aX = cx - bx; aY = cy - by;
  15487. bX = ax - cx; bY = ay - cy;
  15488. cX = bx - ax; cY = by - ay;
  15489. apx= px -ax; apy= py - ay;
  15490. bpx= px - bx; bpy= py - by;
  15491. cpx= px - cx; cpy= py - cy;
  15492. aCROSSbp = aX*bpy - aY*bpx;
  15493. cCROSSap = cX*apy - cY*apx;
  15494. bCROSScp = bX*cpy - bY*cpx;
  15495. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15496. };
  15497. var snip = function ( contour, u, v, w, n, verts ) {
  15498. var p;
  15499. var ax, ay, bx, by;
  15500. var cx, cy, px, py;
  15501. ax = contour[ verts[ u ] ].x;
  15502. ay = contour[ verts[ u ] ].y;
  15503. bx = contour[ verts[ v ] ].x;
  15504. by = contour[ verts[ v ] ].y;
  15505. cx = contour[ verts[ w ] ].x;
  15506. cy = contour[ verts[ w ] ].y;
  15507. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15508. for ( p = 0; p < n; p++ ) {
  15509. if( (p == u) || (p == v) || (p == w) ) continue;
  15510. px = contour[ verts[ p ] ].x
  15511. py = contour[ verts[ p ] ].y
  15512. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15513. }
  15514. return true;
  15515. };
  15516. namespace.Triangulate = process;
  15517. namespace.Triangulate.area = area;
  15518. return namespace;
  15519. })(THREE.FontUtils);
  15520. // To use the typeface.js face files, hook up the API
  15521. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  15522. * @author zz85 / http://www.lab4games.net/zz85/blog
  15523. * Extensible curve object
  15524. *
  15525. * Some common of Curve methods
  15526. * .getPoint(t), getTangent(t)
  15527. * .getPointAt(u), getTagentAt(u)
  15528. * .getPoints(), .getSpacedPoints()
  15529. * .getLength()
  15530. * .updateArcLengths()
  15531. *
  15532. * This file contains following classes:
  15533. *
  15534. * -- 2d classes --
  15535. * THREE.Curve
  15536. * THREE.LineCurve
  15537. * THREE.QuadraticBezierCurve
  15538. * THREE.CubicBezierCurve
  15539. * THREE.SplineCurve
  15540. * THREE.ArcCurve
  15541. * THREE.EllipseCurve
  15542. *
  15543. * -- 3d classes --
  15544. * THREE.LineCurve3
  15545. * THREE.QuadraticBezierCurve3
  15546. * THREE.CubicBezierCurve3
  15547. * THREE.SplineCurve3
  15548. * THREE.ClosedSplineCurve3
  15549. *
  15550. * A series of curves can be represented as a THREE.CurvePath
  15551. *
  15552. **/
  15553. /**************************************************************
  15554. * Abstract Curve base class
  15555. **************************************************************/
  15556. THREE.Curve = function () {
  15557. };
  15558. // Virtual base class method to overwrite and implement in subclasses
  15559. // - t [0 .. 1]
  15560. THREE.Curve.prototype.getPoint = function ( t ) {
  15561. console.log( "Warning, getPoint() not implemented!" );
  15562. return null;
  15563. };
  15564. // Get point at relative position in curve according to arc length
  15565. // - u [0 .. 1]
  15566. THREE.Curve.prototype.getPointAt = function ( u ) {
  15567. var t = this.getUtoTmapping( u );
  15568. return this.getPoint( t );
  15569. };
  15570. // Get sequence of points using getPoint( t )
  15571. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15572. if ( !divisions ) divisions = 5;
  15573. var d, pts = [];
  15574. for ( d = 0; d <= divisions; d ++ ) {
  15575. pts.push( this.getPoint( d / divisions ) );
  15576. }
  15577. return pts;
  15578. };
  15579. // Get sequence of points using getPointAt( u )
  15580. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15581. if ( !divisions ) divisions = 5;
  15582. var d, pts = [];
  15583. for ( d = 0; d <= divisions; d ++ ) {
  15584. pts.push( this.getPointAt( d / divisions ) );
  15585. }
  15586. return pts;
  15587. };
  15588. // Get total curve arc length
  15589. THREE.Curve.prototype.getLength = function () {
  15590. var lengths = this.getLengths();
  15591. return lengths[ lengths.length - 1 ];
  15592. };
  15593. // Get list of cumulative segment lengths
  15594. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15595. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  15596. if ( this.cacheArcLengths
  15597. && ( this.cacheArcLengths.length == divisions + 1 )
  15598. && !this.needsUpdate) {
  15599. //console.log( "cached", this.cacheArcLengths );
  15600. return this.cacheArcLengths;
  15601. }
  15602. this.needsUpdate = false;
  15603. var cache = [];
  15604. var current, last = this.getPoint( 0 );
  15605. var p, sum = 0;
  15606. cache.push( 0 );
  15607. for ( p = 1; p <= divisions; p ++ ) {
  15608. current = this.getPoint ( p / divisions );
  15609. sum += current.distanceTo( last );
  15610. cache.push( sum );
  15611. last = current;
  15612. }
  15613. this.cacheArcLengths = cache;
  15614. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15615. };
  15616. THREE.Curve.prototype.updateArcLengths = function() {
  15617. this.needsUpdate = true;
  15618. this.getLengths();
  15619. };
  15620. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15621. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15622. var arcLengths = this.getLengths();
  15623. var i = 0, il = arcLengths.length;
  15624. var targetArcLength; // The targeted u distance value to get
  15625. if ( distance ) {
  15626. targetArcLength = distance;
  15627. } else {
  15628. targetArcLength = u * arcLengths[ il - 1 ];
  15629. }
  15630. //var time = Date.now();
  15631. // binary search for the index with largest value smaller than target u distance
  15632. var low = 0, high = il - 1, comparison;
  15633. while ( low <= high ) {
  15634. 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
  15635. comparison = arcLengths[ i ] - targetArcLength;
  15636. if ( comparison < 0 ) {
  15637. low = i + 1;
  15638. continue;
  15639. } else if ( comparison > 0 ) {
  15640. high = i - 1;
  15641. continue;
  15642. } else {
  15643. high = i;
  15644. break;
  15645. // DONE
  15646. }
  15647. }
  15648. i = high;
  15649. //console.log('b' , i, low, high, Date.now()- time);
  15650. if ( arcLengths[ i ] == targetArcLength ) {
  15651. var t = i / ( il - 1 );
  15652. return t;
  15653. }
  15654. // we could get finer grain at lengths, or use simple interpolatation between two points
  15655. var lengthBefore = arcLengths[ i ];
  15656. var lengthAfter = arcLengths[ i + 1 ];
  15657. var segmentLength = lengthAfter - lengthBefore;
  15658. // determine where we are between the 'before' and 'after' points
  15659. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15660. // add that fractional amount to t
  15661. var t = ( i + segmentFraction ) / ( il -1 );
  15662. return t;
  15663. };
  15664. // In 2D space, there are actually 2 normal vectors,
  15665. // and in 3D space, infinte
  15666. // TODO this should be depreciated.
  15667. THREE.Curve.prototype.getNormalVector = function( t ) {
  15668. var vec = this.getTangent( t );
  15669. return new THREE.Vector2( -vec.y , vec.x );
  15670. };
  15671. // Returns a unit vector tangent at t
  15672. // In case any sub curve does not implement its tangent / normal finding,
  15673. // we get 2 points with a small delta and find a gradient of the 2 points
  15674. // which seems to make a reasonable approximation
  15675. THREE.Curve.prototype.getTangent = function( t ) {
  15676. var delta = 0.0001;
  15677. var t1 = t - delta;
  15678. var t2 = t + delta;
  15679. // Capping in case of danger
  15680. if ( t1 < 0 ) t1 = 0;
  15681. if ( t2 > 1 ) t2 = 1;
  15682. var pt1 = this.getPoint( t1 );
  15683. var pt2 = this.getPoint( t2 );
  15684. var vec = pt2.clone().subSelf(pt1);
  15685. return vec.normalize();
  15686. };
  15687. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15688. var t = this.getUtoTmapping( u );
  15689. return this.getTangent( t );
  15690. };
  15691. /**************************************************************
  15692. * Line
  15693. **************************************************************/
  15694. THREE.LineCurve = function ( v1, v2 ) {
  15695. this.v1 = v1;
  15696. this.v2 = v2;
  15697. };
  15698. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  15699. THREE.LineCurve.prototype.getPoint = function ( t ) {
  15700. var point = this.v2.clone().subSelf(this.v1);
  15701. point.multiplyScalar( t ).addSelf( this.v1 );
  15702. return point;
  15703. };
  15704. // Line curve is linear, so we can overwrite default getPointAt
  15705. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  15706. return this.getPoint( u );
  15707. };
  15708. THREE.LineCurve.prototype.getTangent = function( t ) {
  15709. var tangent = this.v2.clone().subSelf(this.v1);
  15710. return tangent.normalize();
  15711. };
  15712. /**************************************************************
  15713. * Quadratic Bezier curve
  15714. **************************************************************/
  15715. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  15716. this.v0 = v0;
  15717. this.v1 = v1;
  15718. this.v2 = v2;
  15719. };
  15720. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15721. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  15722. var tx, ty;
  15723. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15724. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15725. return new THREE.Vector2( tx, ty );
  15726. };
  15727. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  15728. var tx, ty;
  15729. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  15730. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  15731. // returns unit vector
  15732. var tangent = new THREE.Vector2( tx, ty );
  15733. tangent.normalize();
  15734. return tangent;
  15735. };
  15736. /**************************************************************
  15737. * Cubic Bezier curve
  15738. **************************************************************/
  15739. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  15740. this.v0 = v0;
  15741. this.v1 = v1;
  15742. this.v2 = v2;
  15743. this.v3 = v3;
  15744. };
  15745. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15746. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  15747. var tx, ty;
  15748. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15749. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15750. return new THREE.Vector2( tx, ty );
  15751. };
  15752. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  15753. var tx, ty;
  15754. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15755. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15756. var tangent = new THREE.Vector2( tx, ty );
  15757. tangent.normalize();
  15758. return tangent;
  15759. };
  15760. /**************************************************************
  15761. * Spline curve
  15762. **************************************************************/
  15763. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  15764. this.points = (points == undefined) ? [] : points;
  15765. };
  15766. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  15767. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  15768. var v = new THREE.Vector2();
  15769. var c = [];
  15770. var points = this.points, point, intPoint, weight;
  15771. point = ( points.length - 1 ) * t;
  15772. intPoint = Math.floor( point );
  15773. weight = point - intPoint;
  15774. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15775. c[ 1 ] = intPoint;
  15776. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  15777. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  15778. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15779. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15780. return v;
  15781. };
  15782. /**************************************************************
  15783. * Ellipse curve
  15784. **************************************************************/
  15785. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  15786. aStartAngle, aEndAngle,
  15787. aClockwise ) {
  15788. this.aX = aX;
  15789. this.aY = aY;
  15790. this.xRadius = xRadius;
  15791. this.yRadius = yRadius;
  15792. this.aStartAngle = aStartAngle;
  15793. this.aEndAngle = aEndAngle;
  15794. this.aClockwise = aClockwise;
  15795. };
  15796. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  15797. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  15798. var deltaAngle = this.aEndAngle - this.aStartAngle;
  15799. if ( !this.aClockwise ) {
  15800. t = 1 - t;
  15801. }
  15802. var angle = this.aStartAngle + t * deltaAngle;
  15803. var tx = this.aX + this.xRadius * Math.cos( angle );
  15804. var ty = this.aY + this.yRadius * Math.sin( angle );
  15805. return new THREE.Vector2( tx, ty );
  15806. };
  15807. /**************************************************************
  15808. * Arc curve
  15809. **************************************************************/
  15810. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  15811. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  15812. };
  15813. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  15814. /**************************************************************
  15815. * Utils
  15816. **************************************************************/
  15817. THREE.Curve.Utils = {
  15818. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15819. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15820. },
  15821. // Puay Bing, thanks for helping with this derivative!
  15822. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15823. return -3 * p0 * (1 - t) * (1 - t) +
  15824. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  15825. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  15826. 3 * t * t * p3;
  15827. },
  15828. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15829. // To check if my formulas are correct
  15830. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15831. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15832. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  15833. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15834. return h00 + h10 + h01 + h11;
  15835. },
  15836. // Catmull-Rom
  15837. interpolate: function( p0, p1, p2, p3, t ) {
  15838. var v0 = ( p2 - p0 ) * 0.5;
  15839. var v1 = ( p3 - p1 ) * 0.5;
  15840. var t2 = t * t;
  15841. var t3 = t * t2;
  15842. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15843. }
  15844. };
  15845. // TODO: Transformation for Curves?
  15846. /**************************************************************
  15847. * 3D Curves
  15848. **************************************************************/
  15849. // A Factory method for creating new curve subclasses
  15850. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15851. constructor.prototype = Object.create( THREE.Curve.prototype );
  15852. constructor.prototype.getPoint = getPointFunc;
  15853. return constructor;
  15854. };
  15855. /**************************************************************
  15856. * Line3D
  15857. **************************************************************/
  15858. THREE.LineCurve3 = THREE.Curve.create(
  15859. function ( v1, v2 ) {
  15860. this.v1 = v1;
  15861. this.v2 = v2;
  15862. },
  15863. function ( t ) {
  15864. var r = new THREE.Vector3();
  15865. r.sub( this.v2, this.v1 ); // diff
  15866. r.multiplyScalar( t );
  15867. r.addSelf( this.v1 );
  15868. return r;
  15869. }
  15870. );
  15871. /**************************************************************
  15872. * Quadratic Bezier 3D curve
  15873. **************************************************************/
  15874. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15875. function ( v0, v1, v2 ) {
  15876. this.v0 = v0;
  15877. this.v1 = v1;
  15878. this.v2 = v2;
  15879. },
  15880. function ( t ) {
  15881. var tx, ty, tz;
  15882. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15883. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15884. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  15885. return new THREE.Vector3( tx, ty, tz );
  15886. }
  15887. );
  15888. /**************************************************************
  15889. * Cubic Bezier 3D curve
  15890. **************************************************************/
  15891. THREE.CubicBezierCurve3 = THREE.Curve.create(
  15892. function ( v0, v1, v2, v3 ) {
  15893. this.v0 = v0;
  15894. this.v1 = v1;
  15895. this.v2 = v2;
  15896. this.v3 = v3;
  15897. },
  15898. function ( t ) {
  15899. var tx, ty, tz;
  15900. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15901. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15902. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  15903. return new THREE.Vector3( tx, ty, tz );
  15904. }
  15905. );
  15906. /**************************************************************
  15907. * Spline 3D curve
  15908. **************************************************************/
  15909. THREE.SplineCurve3 = THREE.Curve.create(
  15910. function ( points /* array of Vector3 */) {
  15911. this.points = (points == undefined) ? [] : points;
  15912. },
  15913. function ( t ) {
  15914. var v = new THREE.Vector3();
  15915. var c = [];
  15916. var points = this.points, point, intPoint, weight;
  15917. point = ( points.length - 1 ) * t;
  15918. intPoint = Math.floor( point );
  15919. weight = point - intPoint;
  15920. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15921. c[ 1 ] = intPoint;
  15922. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15923. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15924. var pt0 = points[ c[0] ],
  15925. pt1 = points[ c[1] ],
  15926. pt2 = points[ c[2] ],
  15927. pt3 = points[ c[3] ];
  15928. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15929. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15930. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15931. return v;
  15932. }
  15933. );
  15934. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15935. // var v = new THREE.Vector3();
  15936. // var c = [];
  15937. // var points = this.points, point, intPoint, weight;
  15938. // point = ( points.length - 1 ) * t;
  15939. // intPoint = Math.floor( point );
  15940. // weight = point - intPoint;
  15941. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15942. // c[ 1 ] = intPoint;
  15943. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15944. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15945. // var pt0 = points[ c[0] ],
  15946. // pt1 = points[ c[1] ],
  15947. // pt2 = points[ c[2] ],
  15948. // pt3 = points[ c[3] ];
  15949. // // t = weight;
  15950. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15951. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15952. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15953. // return v;
  15954. // }
  15955. /**************************************************************
  15956. * Closed Spline 3D curve
  15957. **************************************************************/
  15958. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15959. function ( points /* array of Vector3 */) {
  15960. this.points = (points == undefined) ? [] : points;
  15961. },
  15962. function ( t ) {
  15963. var v = new THREE.Vector3();
  15964. var c = [];
  15965. var points = this.points, point, intPoint, weight;
  15966. point = ( points.length - 0 ) * t;
  15967. // This needs to be from 0-length +1
  15968. intPoint = Math.floor( point );
  15969. weight = point - intPoint;
  15970. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15971. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15972. c[ 1 ] = ( intPoint ) % points.length;
  15973. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15974. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15975. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15976. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15977. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15978. return v;
  15979. }
  15980. );
  15981. /**
  15982. * @author zz85 / http://www.lab4games.net/zz85/blog
  15983. *
  15984. **/
  15985. /**************************************************************
  15986. * Curved Path - a curve path is simply a array of connected
  15987. * curves, but retains the api of a curve
  15988. **************************************************************/
  15989. THREE.CurvePath = function () {
  15990. this.curves = [];
  15991. this.bends = [];
  15992. this.autoClose = false; // Automatically closes the path
  15993. };
  15994. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15995. THREE.CurvePath.prototype.add = function ( curve ) {
  15996. this.curves.push( curve );
  15997. };
  15998. THREE.CurvePath.prototype.checkConnection = function() {
  15999. // TODO
  16000. // If the ending of curve is not connected to the starting
  16001. // or the next curve, then, this is not a real path
  16002. };
  16003. THREE.CurvePath.prototype.closePath = function() {
  16004. // TODO Test
  16005. // and verify for vector3 (needs to implement equals)
  16006. // Add a line curve if start and end of lines are not connected
  16007. var startPoint = this.curves[0].getPoint(0);
  16008. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16009. if (!startPoint.equals(endPoint)) {
  16010. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16011. }
  16012. };
  16013. // To get accurate point with reference to
  16014. // entire path distance at time t,
  16015. // following has to be done:
  16016. // 1. Length of each sub path have to be known
  16017. // 2. Locate and identify type of curve
  16018. // 3. Get t for the curve
  16019. // 4. Return curve.getPointAt(t')
  16020. THREE.CurvePath.prototype.getPoint = function( t ) {
  16021. var d = t * this.getLength();
  16022. var curveLengths = this.getCurveLengths();
  16023. var i = 0, diff, curve;
  16024. // To think about boundaries points.
  16025. while ( i < curveLengths.length ) {
  16026. if ( curveLengths[ i ] >= d ) {
  16027. diff = curveLengths[ i ] - d;
  16028. curve = this.curves[ i ];
  16029. var u = 1 - diff / curve.getLength();
  16030. return curve.getPointAt( u );
  16031. break;
  16032. }
  16033. i ++;
  16034. }
  16035. return null;
  16036. // loop where sum != 0, sum > d , sum+1 <d
  16037. };
  16038. /*
  16039. THREE.CurvePath.prototype.getTangent = function( t ) {
  16040. };*/
  16041. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16042. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16043. // getPoint() depends on getLength
  16044. THREE.CurvePath.prototype.getLength = function() {
  16045. var lens = this.getCurveLengths();
  16046. return lens[ lens.length - 1 ];
  16047. };
  16048. // Compute lengths and cache them
  16049. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16050. THREE.CurvePath.prototype.getCurveLengths = function() {
  16051. // We use cache values if curves and cache array are same length
  16052. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16053. return this.cacheLengths;
  16054. };
  16055. // Get length of subsurve
  16056. // Push sums into cached array
  16057. var lengths = [], sums = 0;
  16058. var i, il = this.curves.length;
  16059. for ( i = 0; i < il; i ++ ) {
  16060. sums += this.curves[ i ].getLength();
  16061. lengths.push( sums );
  16062. }
  16063. this.cacheLengths = lengths;
  16064. return lengths;
  16065. };
  16066. // Returns min and max coordinates, as well as centroid
  16067. THREE.CurvePath.prototype.getBoundingBox = function () {
  16068. var points = this.getPoints();
  16069. var maxX, maxY, maxZ;
  16070. var minX, minY, minZ;
  16071. maxX = maxY = Number.NEGATIVE_INFINITY;
  16072. minX = minY = Number.POSITIVE_INFINITY;
  16073. var p, i, il, sum;
  16074. var v3 = points[0] instanceof THREE.Vector3;
  16075. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16076. for ( i = 0, il = points.length; i < il; i ++ ) {
  16077. p = points[ i ];
  16078. if ( p.x > maxX ) maxX = p.x;
  16079. else if ( p.x < minX ) minX = p.x;
  16080. if ( p.y > maxY ) maxY = p.y;
  16081. else if ( p.y < minY ) minY = p.y;
  16082. if (v3) {
  16083. if ( p.z > maxZ ) maxZ = p.z;
  16084. else if ( p.z < minZ ) minZ = p.z;
  16085. }
  16086. sum.addSelf( p );
  16087. }
  16088. var ret = {
  16089. minX: minX,
  16090. minY: minY,
  16091. maxX: maxX,
  16092. maxY: maxY,
  16093. centroid: sum.divideScalar( il )
  16094. };
  16095. if (v3) {
  16096. ret.maxZ = maxZ;
  16097. ret.minZ = minZ;
  16098. }
  16099. return ret;
  16100. };
  16101. /**************************************************************
  16102. * Create Geometries Helpers
  16103. **************************************************************/
  16104. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16105. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16106. var pts = this.getPoints( divisions, true );
  16107. return this.createGeometry( pts );
  16108. };
  16109. // Generate geometry from equidistance sampling along the path
  16110. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16111. var pts = this.getSpacedPoints( divisions, true );
  16112. return this.createGeometry( pts );
  16113. };
  16114. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16115. var geometry = new THREE.Geometry();
  16116. for ( var i = 0; i < points.length; i ++ ) {
  16117. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16118. }
  16119. return geometry;
  16120. };
  16121. /**************************************************************
  16122. * Bend / Wrap Helper Methods
  16123. **************************************************************/
  16124. // Wrap path / Bend modifiers?
  16125. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16126. this.bends.push( bendpath );
  16127. };
  16128. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16129. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16130. var i, il;
  16131. if ( !bends ) {
  16132. bends = this.bends;
  16133. }
  16134. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16135. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16136. }
  16137. return oldPts;
  16138. };
  16139. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16140. var oldPts = this.getSpacedPoints( segments );
  16141. var i, il;
  16142. if ( !bends ) {
  16143. bends = this.bends;
  16144. }
  16145. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16146. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16147. }
  16148. return oldPts;
  16149. };
  16150. // This returns getPoints() bend/wrapped around the contour of a path.
  16151. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16152. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16153. var bounds = this.getBoundingBox();
  16154. var i, il, p, oldX, oldY, xNorm;
  16155. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16156. p = oldPts[ i ];
  16157. oldX = p.x;
  16158. oldY = p.y;
  16159. xNorm = oldX / bounds.maxX;
  16160. // If using actual distance, for length > path, requires line extrusions
  16161. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16162. xNorm = path.getUtoTmapping( xNorm, oldX );
  16163. // check for out of bounds?
  16164. var pathPt = path.getPoint( xNorm );
  16165. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16166. p.x = pathPt.x + normal.x;
  16167. p.y = pathPt.y + normal.y;
  16168. }
  16169. return oldPts;
  16170. };
  16171. /**
  16172. * @author alteredq / http://alteredqualia.com/
  16173. */
  16174. THREE.Gyroscope = function () {
  16175. THREE.Object3D.call( this );
  16176. };
  16177. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16178. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16179. this.matrixAutoUpdate && this.updateMatrix();
  16180. // update matrixWorld
  16181. if ( this.matrixWorldNeedsUpdate || force ) {
  16182. if ( this.parent ) {
  16183. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  16184. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16185. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16186. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16187. } else {
  16188. this.matrixWorld.copy( this.matrix );
  16189. }
  16190. this.matrixWorldNeedsUpdate = false;
  16191. force = true;
  16192. }
  16193. // update children
  16194. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16195. this.children[ i ].updateMatrixWorld( force );
  16196. }
  16197. };
  16198. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16199. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16200. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16201. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16202. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16203. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16204. /**
  16205. * @author zz85 / http://www.lab4games.net/zz85/blog
  16206. * Creates free form 2d path using series of points, lines or curves.
  16207. *
  16208. **/
  16209. THREE.Path = function ( points ) {
  16210. THREE.CurvePath.call(this);
  16211. this.actions = [];
  16212. if ( points ) {
  16213. this.fromPoints( points );
  16214. }
  16215. };
  16216. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16217. THREE.PathActions = {
  16218. MOVE_TO: 'moveTo',
  16219. LINE_TO: 'lineTo',
  16220. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16221. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16222. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16223. ARC: 'arc', // Circle
  16224. ELLIPSE: 'ellipse'
  16225. };
  16226. // TODO Clean up PATH API
  16227. // Create path using straight lines to connect all points
  16228. // - vectors: array of Vector2
  16229. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16230. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16231. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16232. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16233. };
  16234. };
  16235. // startPath() endPath()?
  16236. THREE.Path.prototype.moveTo = function ( x, y ) {
  16237. var args = Array.prototype.slice.call( arguments );
  16238. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16239. };
  16240. THREE.Path.prototype.lineTo = function ( x, y ) {
  16241. var args = Array.prototype.slice.call( arguments );
  16242. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16243. var x0 = lastargs[ lastargs.length - 2 ];
  16244. var y0 = lastargs[ lastargs.length - 1 ];
  16245. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16246. this.curves.push( curve );
  16247. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16248. };
  16249. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16250. var args = Array.prototype.slice.call( arguments );
  16251. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16252. var x0 = lastargs[ lastargs.length - 2 ];
  16253. var y0 = lastargs[ lastargs.length - 1 ];
  16254. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16255. new THREE.Vector2( aCPx, aCPy ),
  16256. new THREE.Vector2( aX, aY ) );
  16257. this.curves.push( curve );
  16258. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16259. };
  16260. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16261. aCP2x, aCP2y,
  16262. aX, aY ) {
  16263. var args = Array.prototype.slice.call( arguments );
  16264. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16265. var x0 = lastargs[ lastargs.length - 2 ];
  16266. var y0 = lastargs[ lastargs.length - 1 ];
  16267. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16268. new THREE.Vector2( aCP1x, aCP1y ),
  16269. new THREE.Vector2( aCP2x, aCP2y ),
  16270. new THREE.Vector2( aX, aY ) );
  16271. this.curves.push( curve );
  16272. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16273. };
  16274. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16275. var args = Array.prototype.slice.call( arguments );
  16276. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16277. var x0 = lastargs[ lastargs.length - 2 ];
  16278. var y0 = lastargs[ lastargs.length - 1 ];
  16279. //---
  16280. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16281. Array.prototype.push.apply( npts, pts );
  16282. var curve = new THREE.SplineCurve( npts );
  16283. this.curves.push( curve );
  16284. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16285. };
  16286. // FUTURE: Change the API or follow canvas API?
  16287. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16288. aStartAngle, aEndAngle, aClockwise ) {
  16289. var lastargs = this.actions[ this.actions.length - 1].args;
  16290. var x0 = lastargs[ lastargs.length - 2 ];
  16291. var y0 = lastargs[ lastargs.length - 1 ];
  16292. this.absarc(aX + x0, aY + y0, aRadius,
  16293. aStartAngle, aEndAngle, aClockwise );
  16294. };
  16295. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16296. aStartAngle, aEndAngle, aClockwise ) {
  16297. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16298. };
  16299. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16300. aStartAngle, aEndAngle, aClockwise ) {
  16301. var lastargs = this.actions[ this.actions.length - 1].args;
  16302. var x0 = lastargs[ lastargs.length - 2 ];
  16303. var y0 = lastargs[ lastargs.length - 1 ];
  16304. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16305. aStartAngle, aEndAngle, aClockwise );
  16306. };
  16307. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16308. aStartAngle, aEndAngle, aClockwise ) {
  16309. var args = Array.prototype.slice.call( arguments );
  16310. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16311. aStartAngle, aEndAngle, aClockwise );
  16312. this.curves.push( curve );
  16313. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16314. args.push(lastPoint.x);
  16315. args.push(lastPoint.y);
  16316. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16317. };
  16318. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16319. if ( ! divisions ) divisions = 40;
  16320. var points = [];
  16321. for ( var i = 0; i < divisions; i ++ ) {
  16322. points.push( this.getPoint( i / divisions ) );
  16323. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16324. }
  16325. // if ( closedPath ) {
  16326. //
  16327. // points.push( points[ 0 ] );
  16328. //
  16329. // }
  16330. return points;
  16331. };
  16332. /* Return an array of vectors based on contour of the path */
  16333. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16334. if (this.useSpacedPoints) {
  16335. console.log('tata');
  16336. return this.getSpacedPoints( divisions, closedPath );
  16337. }
  16338. divisions = divisions || 12;
  16339. var points = [];
  16340. var i, il, item, action, args;
  16341. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16342. laste, j,
  16343. t, tx, ty;
  16344. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16345. item = this.actions[ i ];
  16346. action = item.action;
  16347. args = item.args;
  16348. switch( action ) {
  16349. case THREE.PathActions.MOVE_TO:
  16350. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16351. break;
  16352. case THREE.PathActions.LINE_TO:
  16353. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16354. break;
  16355. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16356. cpx = args[ 2 ];
  16357. cpy = args[ 3 ];
  16358. cpx1 = args[ 0 ];
  16359. cpy1 = args[ 1 ];
  16360. if ( points.length > 0 ) {
  16361. laste = points[ points.length - 1 ];
  16362. cpx0 = laste.x;
  16363. cpy0 = laste.y;
  16364. } else {
  16365. laste = this.actions[ i - 1 ].args;
  16366. cpx0 = laste[ laste.length - 2 ];
  16367. cpy0 = laste[ laste.length - 1 ];
  16368. }
  16369. for ( j = 1; j <= divisions; j ++ ) {
  16370. t = j / divisions;
  16371. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16372. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16373. points.push( new THREE.Vector2( tx, ty ) );
  16374. }
  16375. break;
  16376. case THREE.PathActions.BEZIER_CURVE_TO:
  16377. cpx = args[ 4 ];
  16378. cpy = args[ 5 ];
  16379. cpx1 = args[ 0 ];
  16380. cpy1 = args[ 1 ];
  16381. cpx2 = args[ 2 ];
  16382. cpy2 = args[ 3 ];
  16383. if ( points.length > 0 ) {
  16384. laste = points[ points.length - 1 ];
  16385. cpx0 = laste.x;
  16386. cpy0 = laste.y;
  16387. } else {
  16388. laste = this.actions[ i - 1 ].args;
  16389. cpx0 = laste[ laste.length - 2 ];
  16390. cpy0 = laste[ laste.length - 1 ];
  16391. }
  16392. for ( j = 1; j <= divisions; j ++ ) {
  16393. t = j / divisions;
  16394. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16395. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16396. points.push( new THREE.Vector2( tx, ty ) );
  16397. }
  16398. break;
  16399. case THREE.PathActions.CSPLINE_THRU:
  16400. laste = this.actions[ i - 1 ].args;
  16401. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16402. var spts = [ last ];
  16403. var n = divisions * args[ 0 ].length;
  16404. spts = spts.concat( args[ 0 ] );
  16405. var spline = new THREE.SplineCurve( spts );
  16406. for ( j = 1; j <= n; j ++ ) {
  16407. points.push( spline.getPointAt( j / n ) ) ;
  16408. }
  16409. break;
  16410. case THREE.PathActions.ARC:
  16411. var aX = args[ 0 ], aY = args[ 1 ],
  16412. aRadius = args[ 2 ],
  16413. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16414. aClockwise = !!args[ 5 ];
  16415. var deltaAngle = aEndAngle - aStartAngle;
  16416. var angle;
  16417. var tdivisions = divisions * 2;
  16418. for ( j = 1; j <= tdivisions; j ++ ) {
  16419. t = j / tdivisions;
  16420. if ( ! aClockwise ) {
  16421. t = 1 - t;
  16422. }
  16423. angle = aStartAngle + t * deltaAngle;
  16424. tx = aX + aRadius * Math.cos( angle );
  16425. ty = aY + aRadius * Math.sin( angle );
  16426. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16427. points.push( new THREE.Vector2( tx, ty ) );
  16428. }
  16429. //console.log(points);
  16430. break;
  16431. case THREE.PathActions.ELLIPSE:
  16432. var aX = args[ 0 ], aY = args[ 1 ],
  16433. xRadius = args[ 2 ],
  16434. yRadius = args[ 3 ],
  16435. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16436. aClockwise = !!args[ 6 ];
  16437. var deltaAngle = aEndAngle - aStartAngle;
  16438. var angle;
  16439. var tdivisions = divisions * 2;
  16440. for ( j = 1; j <= tdivisions; j ++ ) {
  16441. t = j / tdivisions;
  16442. if ( ! aClockwise ) {
  16443. t = 1 - t;
  16444. }
  16445. angle = aStartAngle + t * deltaAngle;
  16446. tx = aX + xRadius * Math.cos( angle );
  16447. ty = aY + yRadius * Math.sin( angle );
  16448. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16449. points.push( new THREE.Vector2( tx, ty ) );
  16450. }
  16451. //console.log(points);
  16452. break;
  16453. } // end switch
  16454. }
  16455. // Normalize to remove the closing point by default.
  16456. var lastPoint = points[ points.length - 1];
  16457. var EPSILON = 0.0000000001;
  16458. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16459. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16460. points.splice( points.length - 1, 1);
  16461. if ( closedPath ) {
  16462. points.push( points[ 0 ] );
  16463. }
  16464. return points;
  16465. };
  16466. // Breaks path into shapes
  16467. THREE.Path.prototype.toShapes = function() {
  16468. var i, il, item, action, args;
  16469. var subPaths = [], lastPath = new THREE.Path();
  16470. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16471. item = this.actions[ i ];
  16472. args = item.args;
  16473. action = item.action;
  16474. if ( action == THREE.PathActions.MOVE_TO ) {
  16475. if ( lastPath.actions.length != 0 ) {
  16476. subPaths.push( lastPath );
  16477. lastPath = new THREE.Path();
  16478. }
  16479. }
  16480. lastPath[ action ].apply( lastPath, args );
  16481. }
  16482. if ( lastPath.actions.length != 0 ) {
  16483. subPaths.push( lastPath );
  16484. }
  16485. // console.log(subPaths);
  16486. if ( subPaths.length == 0 ) return [];
  16487. var tmpPath, tmpShape, shapes = [];
  16488. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16489. // console.log("Holes first", holesFirst);
  16490. if ( subPaths.length == 1) {
  16491. tmpPath = subPaths[0];
  16492. tmpShape = new THREE.Shape();
  16493. tmpShape.actions = tmpPath.actions;
  16494. tmpShape.curves = tmpPath.curves;
  16495. shapes.push( tmpShape );
  16496. return shapes;
  16497. };
  16498. if ( holesFirst ) {
  16499. tmpShape = new THREE.Shape();
  16500. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16501. tmpPath = subPaths[ i ];
  16502. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16503. tmpShape.actions = tmpPath.actions;
  16504. tmpShape.curves = tmpPath.curves;
  16505. shapes.push( tmpShape );
  16506. tmpShape = new THREE.Shape();
  16507. //console.log('cw', i);
  16508. } else {
  16509. tmpShape.holes.push( tmpPath );
  16510. //console.log('ccw', i);
  16511. }
  16512. }
  16513. } else {
  16514. // Shapes first
  16515. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16516. tmpPath = subPaths[ i ];
  16517. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16518. if ( tmpShape ) shapes.push( tmpShape );
  16519. tmpShape = new THREE.Shape();
  16520. tmpShape.actions = tmpPath.actions;
  16521. tmpShape.curves = tmpPath.curves;
  16522. } else {
  16523. tmpShape.holes.push( tmpPath );
  16524. }
  16525. }
  16526. shapes.push( tmpShape );
  16527. }
  16528. //console.log("shape", shapes);
  16529. return shapes;
  16530. };
  16531. /**
  16532. * @author zz85 / http://www.lab4games.net/zz85/blog
  16533. * Defines a 2d shape plane using paths.
  16534. **/
  16535. // STEP 1 Create a path.
  16536. // STEP 2 Turn path into shape.
  16537. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16538. // STEP 3a - Extract points from each shape, turn to vertices
  16539. // STEP 3b - Triangulate each shape, add faces.
  16540. THREE.Shape = function ( ) {
  16541. THREE.Path.apply( this, arguments );
  16542. this.holes = [];
  16543. };
  16544. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16545. // Convenience method to return ExtrudeGeometry
  16546. THREE.Shape.prototype.extrude = function ( options ) {
  16547. var extruded = new THREE.ExtrudeGeometry( this, options );
  16548. return extruded;
  16549. };
  16550. // Convenience method to return ShapeGeometry
  16551. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16552. var geometry = new THREE.ShapeGeometry( this, options );
  16553. return geometry;
  16554. };
  16555. // Get points of holes
  16556. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16557. var i, il = this.holes.length, holesPts = [];
  16558. for ( i = 0; i < il; i ++ ) {
  16559. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16560. }
  16561. return holesPts;
  16562. };
  16563. // Get points of holes (spaced by regular distance)
  16564. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16565. var i, il = this.holes.length, holesPts = [];
  16566. for ( i = 0; i < il; i ++ ) {
  16567. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16568. }
  16569. return holesPts;
  16570. };
  16571. // Get points of shape and holes (keypoints based on segments parameter)
  16572. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16573. return {
  16574. shape: this.getTransformedPoints( divisions ),
  16575. holes: this.getPointsHoles( divisions )
  16576. };
  16577. };
  16578. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16579. if (this.useSpacedPoints) {
  16580. return this.extractAllSpacedPoints(divisions);
  16581. }
  16582. return this.extractAllPoints(divisions);
  16583. };
  16584. //
  16585. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16586. //
  16587. // return {
  16588. //
  16589. // shape: this.transform( bend, divisions ),
  16590. // holes: this.getPointsHoles( divisions, bend )
  16591. //
  16592. // };
  16593. //
  16594. // };
  16595. // Get points of shape and holes (spaced by regular distance)
  16596. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16597. return {
  16598. shape: this.getTransformedSpacedPoints( divisions ),
  16599. holes: this.getSpacedPointsHoles( divisions )
  16600. };
  16601. };
  16602. /**************************************************************
  16603. * Utils
  16604. **************************************************************/
  16605. THREE.Shape.Utils = {
  16606. /*
  16607. contour - array of vector2 for contour
  16608. holes - array of array of vector2
  16609. */
  16610. removeHoles: function ( contour, holes ) {
  16611. var shape = contour.concat(); // work on this shape
  16612. var allpoints = shape.concat();
  16613. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  16614. var prevShapeVert, nextShapeVert,
  16615. prevHoleVert, nextHoleVert,
  16616. holeIndex, shapeIndex,
  16617. shapeId, shapeGroup,
  16618. h, h2,
  16619. hole, shortest, d,
  16620. p, pts1, pts2,
  16621. tmpShape1, tmpShape2,
  16622. tmpHole1, tmpHole2,
  16623. verts = [];
  16624. for ( h = 0; h < holes.length; h ++ ) {
  16625. hole = holes[ h ];
  16626. /*
  16627. shapeholes[ h ].concat(); // preserves original
  16628. holes.push( hole );
  16629. */
  16630. Array.prototype.push.apply( allpoints, hole );
  16631. shortest = Number.POSITIVE_INFINITY;
  16632. // Find the shortest pair of pts between shape and hole
  16633. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  16634. // Using distanceToSquared() intead of distanceTo() should speed a little
  16635. // since running square roots operations are reduced.
  16636. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  16637. pts1 = hole[ h2 ];
  16638. var dist = [];
  16639. for ( p = 0; p < shape.length; p++ ) {
  16640. pts2 = shape[ p ];
  16641. d = pts1.distanceToSquared( pts2 );
  16642. dist.push( d );
  16643. if ( d < shortest ) {
  16644. shortest = d;
  16645. holeIndex = h2;
  16646. shapeIndex = p;
  16647. }
  16648. }
  16649. }
  16650. //console.log("shortest", shortest, dist);
  16651. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16652. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16653. var areaapts = [
  16654. hole[ holeIndex ],
  16655. shape[ shapeIndex ],
  16656. shape[ prevShapeVert ]
  16657. ];
  16658. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  16659. var areabpts = [
  16660. hole[ holeIndex ],
  16661. hole[ prevHoleVert ],
  16662. shape[ shapeIndex ]
  16663. ];
  16664. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  16665. var shapeOffset = 1;
  16666. var holeOffset = -1;
  16667. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  16668. shapeIndex += shapeOffset;
  16669. holeIndex += holeOffset;
  16670. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16671. shapeIndex %= shape.length;
  16672. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16673. holeIndex %= hole.length;
  16674. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16675. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16676. areaapts = [
  16677. hole[ holeIndex ],
  16678. shape[ shapeIndex ],
  16679. shape[ prevShapeVert ]
  16680. ];
  16681. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  16682. areabpts = [
  16683. hole[ holeIndex ],
  16684. hole[ prevHoleVert ],
  16685. shape[ shapeIndex ]
  16686. ];
  16687. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  16688. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  16689. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  16690. // In case areas are not correct.
  16691. //console.log("USE THIS");
  16692. shapeIndex = oldShapeIndex;
  16693. holeIndex = oldHoleIndex ;
  16694. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16695. shapeIndex %= shape.length;
  16696. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16697. holeIndex %= hole.length;
  16698. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16699. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16700. } else {
  16701. //console.log("USE THAT ")
  16702. }
  16703. tmpShape1 = shape.slice( 0, shapeIndex );
  16704. tmpShape2 = shape.slice( shapeIndex );
  16705. tmpHole1 = hole.slice( holeIndex );
  16706. tmpHole2 = hole.slice( 0, holeIndex );
  16707. // Should check orders here again?
  16708. var trianglea = [
  16709. hole[ holeIndex ],
  16710. shape[ shapeIndex ],
  16711. shape[ prevShapeVert ]
  16712. ];
  16713. var triangleb = [
  16714. hole[ holeIndex ] ,
  16715. hole[ prevHoleVert ],
  16716. shape[ shapeIndex ]
  16717. ];
  16718. verts.push( trianglea );
  16719. verts.push( triangleb );
  16720. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16721. }
  16722. return {
  16723. shape:shape, /* shape with no holes */
  16724. isolatedPts: verts, /* isolated faces */
  16725. allpoints: allpoints
  16726. }
  16727. },
  16728. triangulateShape: function ( contour, holes ) {
  16729. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  16730. var shape = shapeWithoutHoles.shape,
  16731. allpoints = shapeWithoutHoles.allpoints,
  16732. isolatedPts = shapeWithoutHoles.isolatedPts;
  16733. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  16734. // 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.
  16735. //console.log( "triangles",triangles, triangles.length );
  16736. //console.log( "allpoints",allpoints, allpoints.length );
  16737. var i, il, f, face,
  16738. key, index,
  16739. allPointsMap = {},
  16740. isolatedPointsMap = {};
  16741. // prepare all points map
  16742. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16743. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  16744. if ( allPointsMap[ key ] !== undefined ) {
  16745. console.log( "Duplicate point", key );
  16746. }
  16747. allPointsMap[ key ] = i;
  16748. }
  16749. // check all face vertices against all points map
  16750. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16751. face = triangles[ i ];
  16752. for ( f = 0; f < 3; f ++ ) {
  16753. key = face[ f ].x + ":" + face[ f ].y;
  16754. index = allPointsMap[ key ];
  16755. if ( index !== undefined ) {
  16756. face[ f ] = index;
  16757. }
  16758. }
  16759. }
  16760. // check isolated points vertices against all points map
  16761. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  16762. face = isolatedPts[ i ];
  16763. for ( f = 0; f < 3; f ++ ) {
  16764. key = face[ f ].x + ":" + face[ f ].y;
  16765. index = allPointsMap[ key ];
  16766. if ( index !== undefined ) {
  16767. face[ f ] = index;
  16768. }
  16769. }
  16770. }
  16771. return triangles.concat( isolatedPts );
  16772. }, // end triangulate shapes
  16773. /*
  16774. triangulate2 : function( pts, holes ) {
  16775. // For use with Poly2Tri.js
  16776. var allpts = pts.concat();
  16777. var shape = [];
  16778. for (var p in pts) {
  16779. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  16780. }
  16781. var swctx = new js.poly2tri.SweepContext(shape);
  16782. for (var h in holes) {
  16783. var aHole = holes[h];
  16784. var newHole = []
  16785. for (i in aHole) {
  16786. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  16787. allpts.push(aHole[i]);
  16788. }
  16789. swctx.AddHole(newHole);
  16790. }
  16791. var find;
  16792. var findIndexForPt = function (pt) {
  16793. find = new THREE.Vector2(pt.x, pt.y);
  16794. var p;
  16795. for (p=0, pl = allpts.length; p<pl; p++) {
  16796. if (allpts[p].equals(find)) return p;
  16797. }
  16798. return -1;
  16799. };
  16800. // triangulate
  16801. js.poly2tri.sweep.Triangulate(swctx);
  16802. var triangles = swctx.GetTriangles();
  16803. var tr ;
  16804. var facesPts = [];
  16805. for (var t in triangles) {
  16806. tr = triangles[t];
  16807. facesPts.push([
  16808. findIndexForPt(tr.GetPoint(0)),
  16809. findIndexForPt(tr.GetPoint(1)),
  16810. findIndexForPt(tr.GetPoint(2))
  16811. ]);
  16812. }
  16813. // console.log(facesPts);
  16814. // console.log("triangles", triangles.length, triangles);
  16815. // Returns array of faces with 3 element each
  16816. return facesPts;
  16817. },
  16818. */
  16819. isClockWise: function ( pts ) {
  16820. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  16821. },
  16822. // Bezier Curves formulas obtained from
  16823. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  16824. // Quad Bezier Functions
  16825. b2p0: function ( t, p ) {
  16826. var k = 1 - t;
  16827. return k * k * p;
  16828. },
  16829. b2p1: function ( t, p ) {
  16830. return 2 * ( 1 - t ) * t * p;
  16831. },
  16832. b2p2: function ( t, p ) {
  16833. return t * t * p;
  16834. },
  16835. b2: function ( t, p0, p1, p2 ) {
  16836. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  16837. },
  16838. // Cubic Bezier Functions
  16839. b3p0: function ( t, p ) {
  16840. var k = 1 - t;
  16841. return k * k * k * p;
  16842. },
  16843. b3p1: function ( t, p ) {
  16844. var k = 1 - t;
  16845. return 3 * k * k * t * p;
  16846. },
  16847. b3p2: function ( t, p ) {
  16848. var k = 1 - t;
  16849. return 3 * k * t * t * p;
  16850. },
  16851. b3p3: function ( t, p ) {
  16852. return t * t * t * p;
  16853. },
  16854. b3: function ( t, p0, p1, p2, p3 ) {
  16855. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16856. }
  16857. };
  16858. /**
  16859. * @author mikael emtinger / http://gomo.se/
  16860. */
  16861. THREE.AnimationHandler = (function() {
  16862. var playing = [];
  16863. var library = {};
  16864. var that = {};
  16865. //--- update ---
  16866. that.update = function( deltaTimeMS ) {
  16867. for( var i = 0; i < playing.length; i ++ )
  16868. playing[ i ].update( deltaTimeMS );
  16869. };
  16870. //--- add ---
  16871. that.addToUpdate = function( animation ) {
  16872. if ( playing.indexOf( animation ) === -1 )
  16873. playing.push( animation );
  16874. };
  16875. //--- remove ---
  16876. that.removeFromUpdate = function( animation ) {
  16877. var index = playing.indexOf( animation );
  16878. if( index !== -1 )
  16879. playing.splice( index, 1 );
  16880. };
  16881. //--- add ---
  16882. that.add = function( data ) {
  16883. if ( library[ data.name ] !== undefined )
  16884. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  16885. library[ data.name ] = data;
  16886. initData( data );
  16887. };
  16888. //--- get ---
  16889. that.get = function( name ) {
  16890. if ( typeof name === "string" ) {
  16891. if ( library[ name ] ) {
  16892. return library[ name ];
  16893. } else {
  16894. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  16895. return null;
  16896. }
  16897. } else {
  16898. // todo: add simple tween library
  16899. }
  16900. };
  16901. //--- parse ---
  16902. that.parse = function( root ) {
  16903. // setup hierarchy
  16904. var hierarchy = [];
  16905. if ( root instanceof THREE.SkinnedMesh ) {
  16906. for( var b = 0; b < root.bones.length; b++ ) {
  16907. hierarchy.push( root.bones[ b ] );
  16908. }
  16909. } else {
  16910. parseRecurseHierarchy( root, hierarchy );
  16911. }
  16912. return hierarchy;
  16913. };
  16914. var parseRecurseHierarchy = function( root, hierarchy ) {
  16915. hierarchy.push( root );
  16916. for( var c = 0; c < root.children.length; c++ )
  16917. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16918. }
  16919. //--- init data ---
  16920. var initData = function( data ) {
  16921. if( data.initialized === true )
  16922. return;
  16923. // loop through all keys
  16924. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16925. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16926. // remove minus times
  16927. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16928. data.hierarchy[ h ].keys[ k ].time = 0;
  16929. // create quaternions
  16930. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16931. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16932. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16933. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16934. }
  16935. }
  16936. // prepare morph target keys
  16937. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16938. // get all used
  16939. var usedMorphTargets = {};
  16940. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16941. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16942. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16943. usedMorphTargets[ morphTargetName ] = -1;
  16944. }
  16945. }
  16946. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16947. // set all used on all frames
  16948. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16949. var influences = {};
  16950. for ( var morphTargetName in usedMorphTargets ) {
  16951. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16952. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16953. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16954. break;
  16955. }
  16956. }
  16957. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16958. influences[ morphTargetName ] = 0;
  16959. }
  16960. }
  16961. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16962. }
  16963. }
  16964. // remove all keys that are on the same time
  16965. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16966. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16967. data.hierarchy[ h ].keys.splice( k, 1 );
  16968. k --;
  16969. }
  16970. }
  16971. // set index
  16972. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16973. data.hierarchy[ h ].keys[ k ].index = k;
  16974. }
  16975. }
  16976. // JIT
  16977. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16978. data.JIT = {};
  16979. data.JIT.hierarchy = [];
  16980. for( var h = 0; h < data.hierarchy.length; h ++ )
  16981. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16982. // done
  16983. data.initialized = true;
  16984. };
  16985. // interpolation types
  16986. that.LINEAR = 0;
  16987. that.CATMULLROM = 1;
  16988. that.CATMULLROM_FORWARD = 2;
  16989. return that;
  16990. }());
  16991. /**
  16992. * @author mikael emtinger / http://gomo.se/
  16993. * @author mrdoob / http://mrdoob.com/
  16994. * @author alteredq / http://alteredqualia.com/
  16995. */
  16996. THREE.Animation = function ( root, name, interpolationType ) {
  16997. this.root = root;
  16998. this.data = THREE.AnimationHandler.get( name );
  16999. this.hierarchy = THREE.AnimationHandler.parse( root );
  17000. this.currentTime = 0;
  17001. this.timeScale = 1;
  17002. this.isPlaying = false;
  17003. this.isPaused = true;
  17004. this.loop = true;
  17005. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17006. this.points = [];
  17007. this.target = new THREE.Vector3();
  17008. };
  17009. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17010. if ( this.isPlaying === false ) {
  17011. this.isPlaying = true;
  17012. this.loop = loop !== undefined ? loop : true;
  17013. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17014. // reset key cache
  17015. var h, hl = this.hierarchy.length,
  17016. object;
  17017. for ( h = 0; h < hl; h ++ ) {
  17018. object = this.hierarchy[ h ];
  17019. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17020. object.useQuaternion = true;
  17021. }
  17022. object.matrixAutoUpdate = true;
  17023. if ( object.animationCache === undefined ) {
  17024. object.animationCache = {};
  17025. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17026. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17027. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17028. }
  17029. var prevKey = object.animationCache.prevKey;
  17030. var nextKey = object.animationCache.nextKey;
  17031. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17032. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17033. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17034. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17035. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17036. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17037. }
  17038. this.update( 0 );
  17039. }
  17040. this.isPaused = false;
  17041. THREE.AnimationHandler.addToUpdate( this );
  17042. };
  17043. THREE.Animation.prototype.pause = function() {
  17044. if ( this.isPaused === true ) {
  17045. THREE.AnimationHandler.addToUpdate( this );
  17046. } else {
  17047. THREE.AnimationHandler.removeFromUpdate( this );
  17048. }
  17049. this.isPaused = !this.isPaused;
  17050. };
  17051. THREE.Animation.prototype.stop = function() {
  17052. this.isPlaying = false;
  17053. this.isPaused = false;
  17054. THREE.AnimationHandler.removeFromUpdate( this );
  17055. };
  17056. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17057. // early out
  17058. if ( this.isPlaying === false ) return;
  17059. // vars
  17060. var types = [ "pos", "rot", "scl" ];
  17061. var type;
  17062. var scale;
  17063. var vector;
  17064. var prevXYZ, nextXYZ;
  17065. var prevKey, nextKey;
  17066. var object;
  17067. var animationCache;
  17068. var frame;
  17069. var JIThierarchy = this.data.JIT.hierarchy;
  17070. var currentTime, unloopedCurrentTime;
  17071. var currentPoint, forwardPoint, angle;
  17072. this.currentTime += deltaTimeMS * this.timeScale;
  17073. unloopedCurrentTime = this.currentTime;
  17074. currentTime = this.currentTime = this.currentTime % this.data.length;
  17075. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17076. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17077. object = this.hierarchy[ h ];
  17078. animationCache = object.animationCache;
  17079. // loop through pos/rot/scl
  17080. for ( var t = 0; t < 3; t ++ ) {
  17081. // get keys
  17082. type = types[ t ];
  17083. prevKey = animationCache.prevKey[ type ];
  17084. nextKey = animationCache.nextKey[ type ];
  17085. // switch keys?
  17086. if ( nextKey.time <= unloopedCurrentTime ) {
  17087. // did we loop?
  17088. if ( currentTime < unloopedCurrentTime ) {
  17089. if ( this.loop ) {
  17090. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17091. nextKey = this.getNextKeyWith( type, h, 1 );
  17092. while( nextKey.time < currentTime ) {
  17093. prevKey = nextKey;
  17094. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17095. }
  17096. } else {
  17097. this.stop();
  17098. return;
  17099. }
  17100. } else {
  17101. do {
  17102. prevKey = nextKey;
  17103. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17104. } while( nextKey.time < currentTime )
  17105. }
  17106. animationCache.prevKey[ type ] = prevKey;
  17107. animationCache.nextKey[ type ] = nextKey;
  17108. }
  17109. object.matrixAutoUpdate = true;
  17110. object.matrixWorldNeedsUpdate = true;
  17111. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17112. prevXYZ = prevKey[ type ];
  17113. nextXYZ = nextKey[ type ];
  17114. // check scale error
  17115. if ( scale < 0 || scale > 1 ) {
  17116. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17117. scale = scale < 0 ? 0 : 1;
  17118. }
  17119. // interpolate
  17120. if ( type === "pos" ) {
  17121. vector = object.position;
  17122. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17123. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17124. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17125. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17126. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17127. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17128. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17129. this.points[ 1 ] = prevXYZ;
  17130. this.points[ 2 ] = nextXYZ;
  17131. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17132. scale = scale * 0.33 + 0.33;
  17133. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17134. vector.x = currentPoint[ 0 ];
  17135. vector.y = currentPoint[ 1 ];
  17136. vector.z = currentPoint[ 2 ];
  17137. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17138. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17139. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17140. this.target.subSelf( vector );
  17141. this.target.y = 0;
  17142. this.target.normalize();
  17143. angle = Math.atan2( this.target.x, this.target.z );
  17144. object.rotation.set( 0, angle, 0 );
  17145. }
  17146. }
  17147. } else if ( type === "rot" ) {
  17148. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17149. } else if ( type === "scl" ) {
  17150. vector = object.scale;
  17151. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17152. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17153. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17154. }
  17155. }
  17156. }
  17157. };
  17158. // Catmull-Rom spline
  17159. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17160. var c = [], v3 = [],
  17161. point, intPoint, weight, w2, w3,
  17162. pa, pb, pc, pd;
  17163. point = ( points.length - 1 ) * scale;
  17164. intPoint = Math.floor( point );
  17165. weight = point - intPoint;
  17166. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17167. c[ 1 ] = intPoint;
  17168. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17169. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17170. pa = points[ c[ 0 ] ];
  17171. pb = points[ c[ 1 ] ];
  17172. pc = points[ c[ 2 ] ];
  17173. pd = points[ c[ 3 ] ];
  17174. w2 = weight * weight;
  17175. w3 = weight * w2;
  17176. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17177. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17178. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17179. return v3;
  17180. };
  17181. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17182. var v0 = ( p2 - p0 ) * 0.5,
  17183. v1 = ( p3 - p1 ) * 0.5;
  17184. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17185. };
  17186. // Get next key with
  17187. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17188. var keys = this.data.hierarchy[ h ].keys;
  17189. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17190. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17191. key = key < keys.length - 1 ? key : keys.length - 1;
  17192. } else {
  17193. key = key % keys.length;
  17194. }
  17195. for ( ; key < keys.length; key++ ) {
  17196. if ( keys[ key ][ type ] !== undefined ) {
  17197. return keys[ key ];
  17198. }
  17199. }
  17200. return this.data.hierarchy[ h ].keys[ 0 ];
  17201. };
  17202. // Get previous key with
  17203. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17204. var keys = this.data.hierarchy[ h ].keys;
  17205. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17206. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17207. key = key > 0 ? key : 0;
  17208. } else {
  17209. key = key >= 0 ? key : key + keys.length;
  17210. }
  17211. for ( ; key >= 0; key -- ) {
  17212. if ( keys[ key ][ type ] !== undefined ) {
  17213. return keys[ key ];
  17214. }
  17215. }
  17216. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17217. };
  17218. /**
  17219. * @author mikael emtinger / http://gomo.se/
  17220. * @author mrdoob / http://mrdoob.com/
  17221. * @author alteredq / http://alteredqualia.com/
  17222. * @author khang duong
  17223. * @author erik kitson
  17224. */
  17225. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17226. this.root = root;
  17227. this.data = THREE.AnimationHandler.get( data );
  17228. this.hierarchy = THREE.AnimationHandler.parse( root );
  17229. this.currentTime = 0;
  17230. this.timeScale = 0.001;
  17231. this.isPlaying = false;
  17232. this.isPaused = true;
  17233. this.loop = true;
  17234. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17235. // initialize to first keyframes
  17236. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17237. var keys = this.data.hierarchy[h].keys,
  17238. sids = this.data.hierarchy[h].sids,
  17239. obj = this.hierarchy[h];
  17240. if ( keys.length && sids ) {
  17241. for ( var s = 0; s < sids.length; s++ ) {
  17242. var sid = sids[ s ],
  17243. next = this.getNextKeyWith( sid, h, 0 );
  17244. if ( next ) {
  17245. next.apply( sid );
  17246. }
  17247. }
  17248. obj.matrixAutoUpdate = false;
  17249. this.data.hierarchy[h].node.updateMatrix();
  17250. obj.matrixWorldNeedsUpdate = true;
  17251. }
  17252. }
  17253. };
  17254. // Play
  17255. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17256. if( !this.isPlaying ) {
  17257. this.isPlaying = true;
  17258. this.loop = loop !== undefined ? loop : true;
  17259. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17260. this.startTimeMs = startTimeMS;
  17261. this.startTime = 10000000;
  17262. this.endTime = -this.startTime;
  17263. // reset key cache
  17264. var h, hl = this.hierarchy.length,
  17265. object,
  17266. node;
  17267. for ( h = 0; h < hl; h++ ) {
  17268. object = this.hierarchy[ h ];
  17269. node = this.data.hierarchy[ h ];
  17270. object.useQuaternion = true;
  17271. if ( node.animationCache === undefined ) {
  17272. node.animationCache = {};
  17273. node.animationCache.prevKey = null;
  17274. node.animationCache.nextKey = null;
  17275. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17276. }
  17277. var keys = this.data.hierarchy[h].keys;
  17278. if (keys.length) {
  17279. node.animationCache.prevKey = keys[ 0 ];
  17280. node.animationCache.nextKey = keys[ 1 ];
  17281. this.startTime = Math.min( keys[0].time, this.startTime );
  17282. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17283. }
  17284. }
  17285. this.update( 0 );
  17286. }
  17287. this.isPaused = false;
  17288. THREE.AnimationHandler.addToUpdate( this );
  17289. };
  17290. // Pause
  17291. THREE.KeyFrameAnimation.prototype.pause = function() {
  17292. if( this.isPaused ) {
  17293. THREE.AnimationHandler.addToUpdate( this );
  17294. } else {
  17295. THREE.AnimationHandler.removeFromUpdate( this );
  17296. }
  17297. this.isPaused = !this.isPaused;
  17298. };
  17299. // Stop
  17300. THREE.KeyFrameAnimation.prototype.stop = function() {
  17301. this.isPlaying = false;
  17302. this.isPaused = false;
  17303. THREE.AnimationHandler.removeFromUpdate( this );
  17304. // reset JIT matrix and remove cache
  17305. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17306. var obj = this.hierarchy[ h ];
  17307. var node = this.data.hierarchy[ h ];
  17308. if ( node.animationCache !== undefined ) {
  17309. var original = node.animationCache.originalMatrix;
  17310. if( obj instanceof THREE.Bone ) {
  17311. original.copy( obj.skinMatrix );
  17312. obj.skinMatrix = original;
  17313. } else {
  17314. original.copy( obj.matrix );
  17315. obj.matrix = original;
  17316. }
  17317. delete node.animationCache;
  17318. }
  17319. }
  17320. };
  17321. // Update
  17322. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17323. // early out
  17324. if( !this.isPlaying ) return;
  17325. // vars
  17326. var prevKey, nextKey;
  17327. var object;
  17328. var node;
  17329. var frame;
  17330. var JIThierarchy = this.data.JIT.hierarchy;
  17331. var currentTime, unloopedCurrentTime;
  17332. var looped;
  17333. // update
  17334. this.currentTime += deltaTimeMS * this.timeScale;
  17335. unloopedCurrentTime = this.currentTime;
  17336. currentTime = this.currentTime = this.currentTime % this.data.length;
  17337. // if looped around, the current time should be based on the startTime
  17338. if ( currentTime < this.startTimeMs ) {
  17339. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17340. }
  17341. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17342. looped = currentTime < unloopedCurrentTime;
  17343. if ( looped && !this.loop ) {
  17344. // Set the animation to the last keyframes and stop
  17345. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17346. var keys = this.data.hierarchy[h].keys,
  17347. sids = this.data.hierarchy[h].sids,
  17348. end = keys.length-1,
  17349. obj = this.hierarchy[h];
  17350. if ( keys.length ) {
  17351. for ( var s = 0; s < sids.length; s++ ) {
  17352. var sid = sids[ s ],
  17353. prev = this.getPrevKeyWith( sid, h, end );
  17354. if ( prev ) {
  17355. prev.apply( sid );
  17356. }
  17357. }
  17358. this.data.hierarchy[h].node.updateMatrix();
  17359. obj.matrixWorldNeedsUpdate = true;
  17360. }
  17361. }
  17362. this.stop();
  17363. return;
  17364. }
  17365. // check pre-infinity
  17366. if ( currentTime < this.startTime ) {
  17367. return;
  17368. }
  17369. // update
  17370. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17371. object = this.hierarchy[ h ];
  17372. node = this.data.hierarchy[ h ];
  17373. var keys = node.keys,
  17374. animationCache = node.animationCache;
  17375. // use JIT?
  17376. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17377. if( object instanceof THREE.Bone ) {
  17378. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17379. object.matrixWorldNeedsUpdate = false;
  17380. } else {
  17381. object.matrix = JIThierarchy[ h ][ frame ];
  17382. object.matrixWorldNeedsUpdate = true;
  17383. }
  17384. // use interpolation
  17385. } else if ( keys.length ) {
  17386. // make sure so original matrix and not JIT matrix is set
  17387. if ( this.JITCompile && animationCache ) {
  17388. if( object instanceof THREE.Bone ) {
  17389. object.skinMatrix = animationCache.originalMatrix;
  17390. } else {
  17391. object.matrix = animationCache.originalMatrix;
  17392. }
  17393. }
  17394. prevKey = animationCache.prevKey;
  17395. nextKey = animationCache.nextKey;
  17396. if ( prevKey && nextKey ) {
  17397. // switch keys?
  17398. if ( nextKey.time <= unloopedCurrentTime ) {
  17399. // did we loop?
  17400. if ( looped && this.loop ) {
  17401. prevKey = keys[ 0 ];
  17402. nextKey = keys[ 1 ];
  17403. while ( nextKey.time < currentTime ) {
  17404. prevKey = nextKey;
  17405. nextKey = keys[ prevKey.index + 1 ];
  17406. }
  17407. } else if ( !looped ) {
  17408. var lastIndex = keys.length - 1;
  17409. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17410. prevKey = nextKey;
  17411. nextKey = keys[ prevKey.index + 1 ];
  17412. }
  17413. }
  17414. animationCache.prevKey = prevKey;
  17415. animationCache.nextKey = nextKey;
  17416. }
  17417. if(nextKey.time >= currentTime)
  17418. prevKey.interpolate( nextKey, currentTime );
  17419. else
  17420. prevKey.interpolate( nextKey, nextKey.time);
  17421. }
  17422. this.data.hierarchy[h].node.updateMatrix();
  17423. object.matrixWorldNeedsUpdate = true;
  17424. }
  17425. }
  17426. // update JIT?
  17427. if ( this.JITCompile ) {
  17428. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17429. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17430. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17431. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17432. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17433. } else {
  17434. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17435. }
  17436. }
  17437. }
  17438. }
  17439. };
  17440. // Get next key with
  17441. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17442. var keys = this.data.hierarchy[ h ].keys;
  17443. key = key % keys.length;
  17444. for ( ; key < keys.length; key++ ) {
  17445. if ( keys[ key ].hasTarget( sid ) ) {
  17446. return keys[ key ];
  17447. }
  17448. }
  17449. return keys[ 0 ];
  17450. };
  17451. // Get previous key with
  17452. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17453. var keys = this.data.hierarchy[ h ].keys;
  17454. key = key >= 0 ? key : key + keys.length;
  17455. for ( ; key >= 0; key-- ) {
  17456. if ( keys[ key ].hasTarget( sid ) ) {
  17457. return keys[ key ];
  17458. }
  17459. }
  17460. return keys[ keys.length - 1 ];
  17461. };
  17462. /**
  17463. * Camera for rendering cube maps
  17464. * - renders scene into axis-aligned cube
  17465. *
  17466. * @author alteredq / http://alteredqualia.com/
  17467. */
  17468. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17469. THREE.Object3D.call( this );
  17470. var fov = 90, aspect = 1;
  17471. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17472. cameraPX.up.set( 0, -1, 0 );
  17473. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17474. this.add( cameraPX );
  17475. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17476. cameraNX.up.set( 0, -1, 0 );
  17477. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17478. this.add( cameraNX );
  17479. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17480. cameraPY.up.set( 0, 0, 1 );
  17481. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17482. this.add( cameraPY );
  17483. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17484. cameraNY.up.set( 0, 0, -1 );
  17485. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17486. this.add( cameraNY );
  17487. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17488. cameraPZ.up.set( 0, -1, 0 );
  17489. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17490. this.add( cameraPZ );
  17491. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17492. cameraNZ.up.set( 0, -1, 0 );
  17493. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  17494. this.add( cameraNZ );
  17495. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  17496. this.updateCubeMap = function ( renderer, scene ) {
  17497. var renderTarget = this.renderTarget;
  17498. var generateMipmaps = renderTarget.generateMipmaps;
  17499. renderTarget.generateMipmaps = false;
  17500. renderTarget.activeCubeFace = 0;
  17501. renderer.render( scene, cameraPX, renderTarget );
  17502. renderTarget.activeCubeFace = 1;
  17503. renderer.render( scene, cameraNX, renderTarget );
  17504. renderTarget.activeCubeFace = 2;
  17505. renderer.render( scene, cameraPY, renderTarget );
  17506. renderTarget.activeCubeFace = 3;
  17507. renderer.render( scene, cameraNY, renderTarget );
  17508. renderTarget.activeCubeFace = 4;
  17509. renderer.render( scene, cameraPZ, renderTarget );
  17510. renderTarget.generateMipmaps = generateMipmaps;
  17511. renderTarget.activeCubeFace = 5;
  17512. renderer.render( scene, cameraNZ, renderTarget );
  17513. };
  17514. };
  17515. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  17516. /*
  17517. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  17518. *
  17519. * A general perpose camera, for setting FOV, Lens Focal Length,
  17520. * and switching between perspective and orthographic views easily.
  17521. * Use this only if you do not wish to manage
  17522. * both a Orthographic and Perspective Camera
  17523. *
  17524. */
  17525. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  17526. THREE.Camera.call( this );
  17527. this.fov = fov;
  17528. this.left = -width / 2;
  17529. this.right = width / 2
  17530. this.top = height / 2;
  17531. this.bottom = -height / 2;
  17532. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  17533. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  17534. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  17535. this.zoom = 1;
  17536. this.toPerspective();
  17537. var aspect = width/height;
  17538. };
  17539. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  17540. THREE.CombinedCamera.prototype.toPerspective = function () {
  17541. // Switches to the Perspective Camera
  17542. this.near = this.cameraP.near;
  17543. this.far = this.cameraP.far;
  17544. this.cameraP.fov = this.fov / this.zoom ;
  17545. this.cameraP.updateProjectionMatrix();
  17546. this.projectionMatrix = this.cameraP.projectionMatrix;
  17547. this.inPerspectiveMode = true;
  17548. this.inOrthographicMode = false;
  17549. };
  17550. THREE.CombinedCamera.prototype.toOrthographic = function () {
  17551. // Switches to the Orthographic camera estimating viewport from Perspective
  17552. var fov = this.fov;
  17553. var aspect = this.cameraP.aspect;
  17554. var near = this.cameraP.near;
  17555. var far = this.cameraP.far;
  17556. // The size that we set is the mid plane of the viewing frustum
  17557. var hyperfocus = ( near + far ) / 2;
  17558. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  17559. var planeHeight = 2 * halfHeight;
  17560. var planeWidth = planeHeight * aspect;
  17561. var halfWidth = planeWidth / 2;
  17562. halfHeight /= this.zoom;
  17563. halfWidth /= this.zoom;
  17564. this.cameraO.left = -halfWidth;
  17565. this.cameraO.right = halfWidth;
  17566. this.cameraO.top = halfHeight;
  17567. this.cameraO.bottom = -halfHeight;
  17568. // this.cameraO.left = -farHalfWidth;
  17569. // this.cameraO.right = farHalfWidth;
  17570. // this.cameraO.top = farHalfHeight;
  17571. // this.cameraO.bottom = -farHalfHeight;
  17572. // this.cameraO.left = this.left / this.zoom;
  17573. // this.cameraO.right = this.right / this.zoom;
  17574. // this.cameraO.top = this.top / this.zoom;
  17575. // this.cameraO.bottom = this.bottom / this.zoom;
  17576. this.cameraO.updateProjectionMatrix();
  17577. this.near = this.cameraO.near;
  17578. this.far = this.cameraO.far;
  17579. this.projectionMatrix = this.cameraO.projectionMatrix;
  17580. this.inPerspectiveMode = false;
  17581. this.inOrthographicMode = true;
  17582. };
  17583. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  17584. this.cameraP.aspect = width / height;
  17585. this.left = -width / 2;
  17586. this.right = width / 2
  17587. this.top = height / 2;
  17588. this.bottom = -height / 2;
  17589. };
  17590. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  17591. this.fov = fov;
  17592. if ( this.inPerspectiveMode ) {
  17593. this.toPerspective();
  17594. } else {
  17595. this.toOrthographic();
  17596. }
  17597. };
  17598. // For mantaining similar API with PerspectiveCamera
  17599. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  17600. if ( this.inPerspectiveMode ) {
  17601. this.toPerspective();
  17602. } else {
  17603. this.toPerspective();
  17604. this.toOrthographic();
  17605. }
  17606. };
  17607. /*
  17608. * Uses Focal Length (in mm) to estimate and set FOV
  17609. * 35mm (fullframe) camera is used if frame size is not specified;
  17610. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  17611. */
  17612. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  17613. if ( frameHeight === undefined ) frameHeight = 24;
  17614. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  17615. this.setFov( fov );
  17616. return fov;
  17617. };
  17618. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  17619. this.zoom = zoom;
  17620. if ( this.inPerspectiveMode ) {
  17621. this.toPerspective();
  17622. } else {
  17623. this.toOrthographic();
  17624. }
  17625. };
  17626. THREE.CombinedCamera.prototype.toFrontView = function() {
  17627. this.rotation.x = 0;
  17628. this.rotation.y = 0;
  17629. this.rotation.z = 0;
  17630. // should we be modifing the matrix instead?
  17631. this.rotationAutoUpdate = false;
  17632. };
  17633. THREE.CombinedCamera.prototype.toBackView = function() {
  17634. this.rotation.x = 0;
  17635. this.rotation.y = Math.PI;
  17636. this.rotation.z = 0;
  17637. this.rotationAutoUpdate = false;
  17638. };
  17639. THREE.CombinedCamera.prototype.toLeftView = function() {
  17640. this.rotation.x = 0;
  17641. this.rotation.y = - Math.PI / 2;
  17642. this.rotation.z = 0;
  17643. this.rotationAutoUpdate = false;
  17644. };
  17645. THREE.CombinedCamera.prototype.toRightView = function() {
  17646. this.rotation.x = 0;
  17647. this.rotation.y = Math.PI / 2;
  17648. this.rotation.z = 0;
  17649. this.rotationAutoUpdate = false;
  17650. };
  17651. THREE.CombinedCamera.prototype.toTopView = function() {
  17652. this.rotation.x = - Math.PI / 2;
  17653. this.rotation.y = 0;
  17654. this.rotation.z = 0;
  17655. this.rotationAutoUpdate = false;
  17656. };
  17657. THREE.CombinedCamera.prototype.toBottomView = function() {
  17658. this.rotation.x = Math.PI / 2;
  17659. this.rotation.y = 0;
  17660. this.rotation.z = 0;
  17661. this.rotationAutoUpdate = false;
  17662. };
  17663. /**
  17664. * @author alteredq / http://alteredqualia.com/
  17665. *
  17666. * - 3d asterisk shape (for line pieces THREE.Line)
  17667. */
  17668. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  17669. THREE.Geometry.call( this );
  17670. var sd = innerRadius;
  17671. var ed = outerRadius;
  17672. var sd2 = 0.707 * sd;
  17673. var ed2 = 0.707 * ed;
  17674. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  17675. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  17676. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  17677. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  17678. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  17679. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  17680. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  17681. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  17682. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  17683. ];
  17684. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  17685. var x = rays[ i ][ 0 ];
  17686. var y = rays[ i ][ 1 ];
  17687. var z = rays[ i ][ 2 ];
  17688. this.vertices.push( new THREE.Vector3( x, y, z ) );
  17689. }
  17690. };
  17691. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  17692. * @author hughes
  17693. */
  17694. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17695. THREE.Geometry.call( this );
  17696. radius = radius || 50;
  17697. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17698. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17699. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17700. var i, uvs = [],
  17701. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17702. this.vertices.push(center);
  17703. uvs.push( centerUV );
  17704. for ( i = 0; i <= segments; i ++ ) {
  17705. var vertex = new THREE.Vector3();
  17706. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17707. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17708. this.vertices.push( vertex );
  17709. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17710. }
  17711. var n = new THREE.Vector3( 0, 0, -1 );
  17712. for ( i = 1; i <= segments; i ++ ) {
  17713. var v1 = i;
  17714. var v2 = i + 1 ;
  17715. var v3 = 0;
  17716. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17717. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17718. }
  17719. this.computeCentroids();
  17720. this.computeFaceNormals();
  17721. this.boundingSphere = { radius: radius };
  17722. };
  17723. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17724. /**
  17725. * @author mrdoob / http://mrdoob.com/
  17726. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17727. */
  17728. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  17729. THREE.Geometry.call( this );
  17730. var scope = this;
  17731. this.width = width;
  17732. this.height = height;
  17733. this.depth = depth;
  17734. this.widthSegments = widthSegments || 1;
  17735. this.heightSegments = heightSegments || 1;
  17736. this.depthSegments = depthSegments || 1;
  17737. var width_half = this.width / 2;
  17738. var height_half = this.height / 2;
  17739. var depth_half = this.depth / 2;
  17740. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  17741. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  17742. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  17743. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  17744. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  17745. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  17746. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  17747. var w, ix, iy,
  17748. gridX = scope.widthSegments,
  17749. gridY = scope.heightSegments,
  17750. width_half = width / 2,
  17751. height_half = height / 2,
  17752. offset = scope.vertices.length;
  17753. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17754. w = 'z';
  17755. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17756. w = 'y';
  17757. gridY = scope.depthSegments;
  17758. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17759. w = 'x';
  17760. gridX = scope.depthSegments;
  17761. }
  17762. var gridX1 = gridX + 1,
  17763. gridY1 = gridY + 1,
  17764. segment_width = width / gridX,
  17765. segment_height = height / gridY,
  17766. normal = new THREE.Vector3();
  17767. normal[ w ] = depth > 0 ? 1 : - 1;
  17768. for ( iy = 0; iy < gridY1; iy ++ ) {
  17769. for ( ix = 0; ix < gridX1; ix ++ ) {
  17770. var vector = new THREE.Vector3();
  17771. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17772. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17773. vector[ w ] = depth;
  17774. scope.vertices.push( vector );
  17775. }
  17776. }
  17777. for ( iy = 0; iy < gridY; iy++ ) {
  17778. for ( ix = 0; ix < gridX; ix++ ) {
  17779. var a = ix + gridX1 * iy;
  17780. var b = ix + gridX1 * ( iy + 1 );
  17781. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17782. var d = ( ix + 1 ) + gridX1 * iy;
  17783. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17784. face.normal.copy( normal );
  17785. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17786. face.materialIndex = materialIndex;
  17787. scope.faces.push( face );
  17788. scope.faceVertexUvs[ 0 ].push( [
  17789. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  17790. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  17791. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  17792. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  17793. ] );
  17794. }
  17795. }
  17796. }
  17797. this.computeCentroids();
  17798. this.mergeVertices();
  17799. };
  17800. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17801. /**
  17802. * @author mrdoob / http://mrdoob.com/
  17803. */
  17804. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  17805. THREE.Geometry.call( this );
  17806. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17807. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17808. height = height !== undefined ? height : 100;
  17809. var heightHalf = height / 2;
  17810. var segmentsX = radiusSegments || 8;
  17811. var segmentsY = heightSegments || 1;
  17812. var x, y, vertices = [], uvs = [];
  17813. for ( y = 0; y <= segmentsY; y ++ ) {
  17814. var verticesRow = [];
  17815. var uvsRow = [];
  17816. var v = y / segmentsY;
  17817. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17818. for ( x = 0; x <= segmentsX; x ++ ) {
  17819. var u = x / segmentsX;
  17820. var vertex = new THREE.Vector3();
  17821. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  17822. vertex.y = - v * height + heightHalf;
  17823. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  17824. this.vertices.push( vertex );
  17825. verticesRow.push( this.vertices.length - 1 );
  17826. uvsRow.push( new THREE.UV( u, 1 - v ) );
  17827. }
  17828. vertices.push( verticesRow );
  17829. uvs.push( uvsRow );
  17830. }
  17831. var tanTheta = ( radiusBottom - radiusTop ) / height;
  17832. var na, nb;
  17833. for ( x = 0; x < segmentsX; x ++ ) {
  17834. if ( radiusTop !== 0 ) {
  17835. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  17836. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  17837. } else {
  17838. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  17839. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  17840. }
  17841. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  17842. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  17843. for ( y = 0; y < segmentsY; y ++ ) {
  17844. var v1 = vertices[ y ][ x ];
  17845. var v2 = vertices[ y + 1 ][ x ];
  17846. var v3 = vertices[ y + 1 ][ x + 1 ];
  17847. var v4 = vertices[ y ][ x + 1 ];
  17848. var n1 = na.clone();
  17849. var n2 = na.clone();
  17850. var n3 = nb.clone();
  17851. var n4 = nb.clone();
  17852. var uv1 = uvs[ y ][ x ].clone();
  17853. var uv2 = uvs[ y + 1 ][ x ].clone();
  17854. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  17855. var uv4 = uvs[ y ][ x + 1 ].clone();
  17856. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  17857. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  17858. }
  17859. }
  17860. // top cap
  17861. if ( !openEnded && radiusTop > 0 ) {
  17862. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  17863. for ( x = 0; x < segmentsX; x ++ ) {
  17864. var v1 = vertices[ 0 ][ x ];
  17865. var v2 = vertices[ 0 ][ x + 1 ];
  17866. var v3 = this.vertices.length - 1;
  17867. var n1 = new THREE.Vector3( 0, 1, 0 );
  17868. var n2 = new THREE.Vector3( 0, 1, 0 );
  17869. var n3 = new THREE.Vector3( 0, 1, 0 );
  17870. var uv1 = uvs[ 0 ][ x ].clone();
  17871. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  17872. var uv3 = new THREE.UV( uv2.u, 0 );
  17873. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17874. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17875. }
  17876. }
  17877. // bottom cap
  17878. if ( !openEnded && radiusBottom > 0 ) {
  17879. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  17880. for ( x = 0; x < segmentsX; x ++ ) {
  17881. var v1 = vertices[ y ][ x + 1 ];
  17882. var v2 = vertices[ y ][ x ];
  17883. var v3 = this.vertices.length - 1;
  17884. var n1 = new THREE.Vector3( 0, - 1, 0 );
  17885. var n2 = new THREE.Vector3( 0, - 1, 0 );
  17886. var n3 = new THREE.Vector3( 0, - 1, 0 );
  17887. var uv1 = uvs[ y ][ x + 1 ].clone();
  17888. var uv2 = uvs[ y ][ x ].clone();
  17889. var uv3 = new THREE.UV( uv2.u, 1 );
  17890. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17891. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17892. }
  17893. }
  17894. this.computeCentroids();
  17895. this.computeFaceNormals();
  17896. }
  17897. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17898. /**
  17899. * @author zz85 / http://www.lab4games.net/zz85/blog
  17900. *
  17901. * Creates extruded geometry from a path shape.
  17902. *
  17903. * parameters = {
  17904. *
  17905. * size: <float>, // size of the text
  17906. * height: <float>, // thickness to extrude text
  17907. * curveSegments: <int>, // number of points on the curves
  17908. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  17909. * amount: <int>, // Amount
  17910. *
  17911. * bevelEnabled: <bool>, // turn on bevel
  17912. * bevelThickness: <float>, // how deep into text bevel goes
  17913. * bevelSize: <float>, // how far from text outline is bevel
  17914. * bevelSegments: <int>, // number of bevel layers
  17915. *
  17916. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  17917. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  17918. *
  17919. * material: <int> // material index for front and back faces
  17920. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  17921. * uvGenerator: <Object> // object that provides UV generator functions
  17922. *
  17923. * }
  17924. **/
  17925. THREE.ExtrudeGeometry = function ( shapes, options ) {
  17926. if ( typeof( shapes ) === "undefined" ) {
  17927. shapes = [];
  17928. return;
  17929. }
  17930. THREE.Geometry.call( this );
  17931. shapes = shapes instanceof Array ? shapes : [ shapes ];
  17932. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  17933. this.addShapeList( shapes, options );
  17934. this.computeCentroids();
  17935. this.computeFaceNormals();
  17936. // can't really use automatic vertex normals
  17937. // as then front and back sides get smoothed too
  17938. // should do separate smoothing just for sides
  17939. //this.computeVertexNormals();
  17940. //console.log( "took", ( Date.now() - startTime ) );
  17941. };
  17942. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17943. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  17944. var sl = shapes.length;
  17945. for ( var s = 0; s < sl; s ++ ) {
  17946. var shape = shapes[ s ];
  17947. this.addShape( shape, options );
  17948. }
  17949. };
  17950. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  17951. var amount = options.amount !== undefined ? options.amount : 100;
  17952. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  17953. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  17954. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17955. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  17956. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17957. var steps = options.steps !== undefined ? options.steps : 1;
  17958. var extrudePath = options.extrudePath;
  17959. var extrudePts, extrudeByPath = false;
  17960. var material = options.material;
  17961. var extrudeMaterial = options.extrudeMaterial;
  17962. // Use default WorldUVGenerator if no UV generators are specified.
  17963. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  17964. var shapebb = this.shapebb;
  17965. //shapebb = shape.getBoundingBox();
  17966. var splineTube, binormal, normal, position2;
  17967. if ( extrudePath ) {
  17968. extrudePts = extrudePath.getSpacedPoints( steps );
  17969. extrudeByPath = true;
  17970. bevelEnabled = false; // bevels not supported for path extrusion
  17971. // SETUP TNB variables
  17972. // Reuse TNB from TubeGeomtry for now.
  17973. // TODO1 - have a .isClosed in spline?
  17974. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  17975. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17976. binormal = new THREE.Vector3();
  17977. normal = new THREE.Vector3();
  17978. position2 = new THREE.Vector3();
  17979. }
  17980. // Safeguards if bevels are not enabled
  17981. if ( ! bevelEnabled ) {
  17982. bevelSegments = 0;
  17983. bevelThickness = 0;
  17984. bevelSize = 0;
  17985. }
  17986. // Variables initalization
  17987. var ahole, h, hl; // looping of holes
  17988. var scope = this;
  17989. var bevelPoints = [];
  17990. var shapesOffset = this.vertices.length;
  17991. var shapePoints = shape.extractPoints();
  17992. var vertices = shapePoints.shape;
  17993. var holes = shapePoints.holes;
  17994. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  17995. if ( reverse ) {
  17996. vertices = vertices.reverse();
  17997. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17998. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17999. ahole = holes[ h ];
  18000. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18001. holes[ h ] = ahole.reverse();
  18002. }
  18003. }
  18004. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18005. }
  18006. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18007. /* Vertices */
  18008. var contour = vertices; // vertices has all points but contour has only points of circumference
  18009. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18010. ahole = holes[ h ];
  18011. vertices = vertices.concat( ahole );
  18012. }
  18013. function scalePt2 ( pt, vec, size ) {
  18014. if ( !vec ) console.log( "die" );
  18015. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18016. }
  18017. var b, bs, t, z,
  18018. vert, vlen = vertices.length,
  18019. face, flen = faces.length,
  18020. cont, clen = contour.length;
  18021. // Find directions for point movement
  18022. var RAD_TO_DEGREES = 180 / Math.PI;
  18023. function getBevelVec( pt_i, pt_j, pt_k ) {
  18024. // Algorithm 2
  18025. return getBevelVec2( pt_i, pt_j, pt_k );
  18026. }
  18027. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18028. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18029. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18030. if ( anglea > angleb ) {
  18031. angleb += Math.PI * 2;
  18032. }
  18033. var anglec = ( anglea + angleb ) / 2;
  18034. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18035. var x = - Math.cos( anglec );
  18036. var y = - Math.sin( anglec );
  18037. var vec = new THREE.Vector2( x, y ); //.normalize();
  18038. return vec;
  18039. }
  18040. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18041. var a = THREE.ExtrudeGeometry.__v1,
  18042. b = THREE.ExtrudeGeometry.__v2,
  18043. v_hat = THREE.ExtrudeGeometry.__v3,
  18044. w_hat = THREE.ExtrudeGeometry.__v4,
  18045. p = THREE.ExtrudeGeometry.__v5,
  18046. q = THREE.ExtrudeGeometry.__v6,
  18047. v, w,
  18048. v_dot_w_hat, q_sub_p_dot_w_hat,
  18049. s, intersection;
  18050. // good reading for line-line intersection
  18051. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18052. // define a as vector j->i
  18053. // define b as vectot k->i
  18054. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18055. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18056. // get unit vectors
  18057. v = a.normalize();
  18058. w = b.normalize();
  18059. // normals from pt i
  18060. v_hat.set( -v.y, v.x );
  18061. w_hat.set( w.y, -w.x );
  18062. // pts from i
  18063. p.copy( pt_i ).addSelf( v_hat );
  18064. q.copy( pt_i ).addSelf( w_hat );
  18065. if ( p.equals( q ) ) {
  18066. //console.log("Warning: lines are straight");
  18067. return w_hat.clone();
  18068. }
  18069. // Points from j, k. helps prevents points cross overover most of the time
  18070. p.copy( pt_j ).addSelf( v_hat );
  18071. q.copy( pt_k ).addSelf( w_hat );
  18072. v_dot_w_hat = v.dot( w_hat );
  18073. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18074. // We should not reach these conditions
  18075. if ( v_dot_w_hat === 0 ) {
  18076. console.log( "Either infinite or no solutions!" );
  18077. if ( q_sub_p_dot_w_hat === 0 ) {
  18078. console.log( "Its finite solutions." );
  18079. } else {
  18080. console.log( "Too bad, no solutions." );
  18081. }
  18082. }
  18083. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18084. if ( s < 0 ) {
  18085. // in case of emergecy, revert to algorithm 1.
  18086. return getBevelVec1( pt_i, pt_j, pt_k );
  18087. }
  18088. intersection = v.multiplyScalar( s ).addSelf( p );
  18089. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18090. }
  18091. var contourMovements = [];
  18092. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18093. if ( j === il ) j = 0;
  18094. if ( k === il ) k = 0;
  18095. // (j)---(i)---(k)
  18096. // console.log('i,j,k', i, j , k)
  18097. var pt_i = contour[ i ];
  18098. var pt_j = contour[ j ];
  18099. var pt_k = contour[ k ];
  18100. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18101. }
  18102. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18103. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18104. ahole = holes[ h ];
  18105. oneHoleMovements = [];
  18106. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18107. if ( j === il ) j = 0;
  18108. if ( k === il ) k = 0;
  18109. // (j)---(i)---(k)
  18110. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18111. }
  18112. holesMovements.push( oneHoleMovements );
  18113. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18114. }
  18115. // Loop bevelSegments, 1 for the front, 1 for the back
  18116. for ( b = 0; b < bevelSegments; b ++ ) {
  18117. //for ( b = bevelSegments; b > 0; b -- ) {
  18118. t = b / bevelSegments;
  18119. z = bevelThickness * ( 1 - t );
  18120. //z = bevelThickness * t;
  18121. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18122. //bs = bevelSize * t ; // linear
  18123. // contract shape
  18124. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18125. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18126. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18127. v( vert.x, vert.y, - z );
  18128. }
  18129. // expand holes
  18130. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18131. ahole = holes[ h ];
  18132. oneHoleMovements = holesMovements[ h ];
  18133. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18134. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18135. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18136. v( vert.x, vert.y, -z );
  18137. }
  18138. }
  18139. }
  18140. bs = bevelSize;
  18141. // Back facing vertices
  18142. for ( i = 0; i < vlen; i ++ ) {
  18143. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18144. if ( !extrudeByPath ) {
  18145. v( vert.x, vert.y, 0 );
  18146. } else {
  18147. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18148. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18149. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18150. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18151. v( position2.x, position2.y, position2.z );
  18152. }
  18153. }
  18154. // Add stepped vertices...
  18155. // Including front facing vertices
  18156. var s;
  18157. for ( s = 1; s <= steps; s ++ ) {
  18158. for ( i = 0; i < vlen; i ++ ) {
  18159. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18160. if ( !extrudeByPath ) {
  18161. v( vert.x, vert.y, amount / steps * s );
  18162. } else {
  18163. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18164. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18165. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18166. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18167. v( position2.x, position2.y, position2.z );
  18168. }
  18169. }
  18170. }
  18171. // Add bevel segments planes
  18172. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18173. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18174. t = b / bevelSegments;
  18175. z = bevelThickness * ( 1 - t );
  18176. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18177. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18178. // contract shape
  18179. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18180. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18181. v( vert.x, vert.y, amount + z );
  18182. }
  18183. // expand holes
  18184. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18185. ahole = holes[ h ];
  18186. oneHoleMovements = holesMovements[ h ];
  18187. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18188. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18189. if ( !extrudeByPath ) {
  18190. v( vert.x, vert.y, amount + z );
  18191. } else {
  18192. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18193. }
  18194. }
  18195. }
  18196. }
  18197. /* Faces */
  18198. // Top and bottom faces
  18199. buildLidFaces();
  18200. // Sides faces
  18201. buildSideFaces();
  18202. ///// Internal functions
  18203. function buildLidFaces() {
  18204. if ( bevelEnabled ) {
  18205. var layer = 0 ; // steps + 1
  18206. var offset = vlen * layer;
  18207. // Bottom faces
  18208. for ( i = 0; i < flen; i ++ ) {
  18209. face = faces[ i ];
  18210. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18211. }
  18212. layer = steps + bevelSegments * 2;
  18213. offset = vlen * layer;
  18214. // Top faces
  18215. for ( i = 0; i < flen; i ++ ) {
  18216. face = faces[ i ];
  18217. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18218. }
  18219. } else {
  18220. // Bottom faces
  18221. for ( i = 0; i < flen; i++ ) {
  18222. face = faces[ i ];
  18223. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18224. }
  18225. // Top faces
  18226. for ( i = 0; i < flen; i ++ ) {
  18227. face = faces[ i ];
  18228. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18229. }
  18230. }
  18231. }
  18232. // Create faces for the z-sides of the shape
  18233. function buildSideFaces() {
  18234. var layeroffset = 0;
  18235. sidewalls( contour, layeroffset );
  18236. layeroffset += contour.length;
  18237. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18238. ahole = holes[ h ];
  18239. sidewalls( ahole, layeroffset );
  18240. //, true
  18241. layeroffset += ahole.length;
  18242. }
  18243. }
  18244. function sidewalls( contour, layeroffset ) {
  18245. var j, k;
  18246. i = contour.length;
  18247. while ( --i >= 0 ) {
  18248. j = i;
  18249. k = i - 1;
  18250. if ( k < 0 ) k = contour.length - 1;
  18251. //console.log('b', i,j, i-1, k,vertices.length);
  18252. var s = 0, sl = steps + bevelSegments * 2;
  18253. for ( s = 0; s < sl; s ++ ) {
  18254. var slen1 = vlen * s;
  18255. var slen2 = vlen * ( s + 1 );
  18256. var a = layeroffset + j + slen1,
  18257. b = layeroffset + k + slen1,
  18258. c = layeroffset + k + slen2,
  18259. d = layeroffset + j + slen2;
  18260. f4( a, b, c, d, contour, s, sl, j, k );
  18261. }
  18262. }
  18263. }
  18264. function v( x, y, z ) {
  18265. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18266. }
  18267. function f3( a, b, c, isBottom ) {
  18268. a += shapesOffset;
  18269. b += shapesOffset;
  18270. c += shapesOffset;
  18271. // normal, color, material
  18272. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18273. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18274. scope.faceVertexUvs[ 0 ].push( uvs );
  18275. }
  18276. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18277. a += shapesOffset;
  18278. b += shapesOffset;
  18279. c += shapesOffset;
  18280. d += shapesOffset;
  18281. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18282. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18283. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18284. scope.faceVertexUvs[ 0 ].push( uvs );
  18285. }
  18286. };
  18287. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18288. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18289. var ax = geometry.vertices[ indexA ].x,
  18290. ay = geometry.vertices[ indexA ].y,
  18291. bx = geometry.vertices[ indexB ].x,
  18292. by = geometry.vertices[ indexB ].y,
  18293. cx = geometry.vertices[ indexC ].x,
  18294. cy = geometry.vertices[ indexC ].y;
  18295. return [
  18296. new THREE.UV( ax, ay ),
  18297. new THREE.UV( bx, by ),
  18298. new THREE.UV( cx, cy )
  18299. ];
  18300. },
  18301. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18302. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18303. },
  18304. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18305. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18306. contourIndex1, contourIndex2 ) {
  18307. var ax = geometry.vertices[ indexA ].x,
  18308. ay = geometry.vertices[ indexA ].y,
  18309. az = geometry.vertices[ indexA ].z,
  18310. bx = geometry.vertices[ indexB ].x,
  18311. by = geometry.vertices[ indexB ].y,
  18312. bz = geometry.vertices[ indexB ].z,
  18313. cx = geometry.vertices[ indexC ].x,
  18314. cy = geometry.vertices[ indexC ].y,
  18315. cz = geometry.vertices[ indexC ].z,
  18316. dx = geometry.vertices[ indexD ].x,
  18317. dy = geometry.vertices[ indexD ].y,
  18318. dz = geometry.vertices[ indexD ].z;
  18319. if ( Math.abs( ay - by ) < 0.01 ) {
  18320. return [
  18321. new THREE.UV( ax, 1 - az ),
  18322. new THREE.UV( bx, 1 - bz ),
  18323. new THREE.UV( cx, 1 - cz ),
  18324. new THREE.UV( dx, 1 - dz )
  18325. ];
  18326. } else {
  18327. return [
  18328. new THREE.UV( ay, 1 - az ),
  18329. new THREE.UV( by, 1 - bz ),
  18330. new THREE.UV( cy, 1 - cz ),
  18331. new THREE.UV( dy, 1 - dz )
  18332. ];
  18333. }
  18334. }
  18335. };
  18336. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18337. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18338. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18339. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18340. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18341. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18342. /**
  18343. * @author jonobr1 / http://jonobr1.com
  18344. *
  18345. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18346. * ExtrudeGeometry.
  18347. *
  18348. * parameters = {
  18349. *
  18350. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18351. *
  18352. * material: <int> // material index for front and back faces
  18353. * uvGenerator: <Object> // object that provides UV generator functions
  18354. *
  18355. * }
  18356. **/
  18357. THREE.ShapeGeometry = function ( shapes, options ) {
  18358. THREE.Geometry.call( this );
  18359. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18360. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18361. this.addShapeList( shapes, options );
  18362. this.computeCentroids();
  18363. this.computeFaceNormals();
  18364. };
  18365. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18366. /**
  18367. * Add an array of shapes to THREE.ShapeGeometry.
  18368. */
  18369. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18370. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18371. this.addShape( shapes[ i ], options );
  18372. }
  18373. return this;
  18374. };
  18375. /**
  18376. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18377. */
  18378. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18379. if ( options === undefined ) options = {};
  18380. var material = options.material;
  18381. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18382. var shapebb = this.shapebb;
  18383. //
  18384. var i, l, hole, s;
  18385. var shapesOffset = this.vertices.length;
  18386. var shapePoints = shape.extractPoints();
  18387. var vertices = shapePoints.shape;
  18388. var holes = shapePoints.holes;
  18389. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18390. if ( reverse ) {
  18391. vertices = vertices.reverse();
  18392. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18393. for ( i = 0, l = holes.length; i < l; i++ ) {
  18394. hole = holes[ i ];
  18395. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18396. holes[ i ] = hole.reverse();
  18397. }
  18398. }
  18399. reverse = false;
  18400. }
  18401. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18402. // Vertices
  18403. var contour = vertices;
  18404. for ( i = 0, l = holes.length; i < l; i++ ) {
  18405. hole = holes[ i ];
  18406. vertices = vertices.concat( hole );
  18407. }
  18408. //
  18409. var vert, vlen = vertices.length;
  18410. var face, flen = faces.length;
  18411. var cont, clen = contour.length;
  18412. for ( i = 0; i < vlen; i++ ) {
  18413. vert = vertices[ i ];
  18414. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18415. }
  18416. for ( i = 0; i < flen; i++ ) {
  18417. face = faces[ i ];
  18418. var a = face[ 0 ] + shapesOffset;
  18419. var b = face[ 1 ] + shapesOffset;
  18420. var c = face[ 2 ] + shapesOffset;
  18421. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18422. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18423. }
  18424. };
  18425. /**
  18426. * @author astrodud / http://astrodud.isgreat.org/
  18427. * @author zz85 / https://github.com/zz85
  18428. */
  18429. THREE.LatheGeometry = function ( points, steps, angle ) {
  18430. THREE.Geometry.call( this );
  18431. var _steps = steps || 12;
  18432. var _angle = angle || 2 * Math.PI;
  18433. var _newV = [];
  18434. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18435. for ( var j = 0; j < points.length; j ++ ) {
  18436. _newV[ j ] = points[ j ].clone();
  18437. this.vertices.push( _newV[ j ] );
  18438. }
  18439. var i, il = _steps + 1;
  18440. for ( i = 0; i < il; i ++ ) {
  18441. for ( var j = 0; j < _newV.length; j ++ ) {
  18442. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18443. this.vertices.push( _newV[ j ] );
  18444. }
  18445. }
  18446. for ( i = 0; i < _steps; i ++ ) {
  18447. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18448. var a = i * kl + k;
  18449. var b = ( ( i + 1 ) % il ) * kl + k;
  18450. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18451. var d = i * kl + ( k + 1 ) % kl;
  18452. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18453. this.faceVertexUvs[ 0 ].push( [
  18454. new THREE.UV( 1 - i / _steps, k / kl ),
  18455. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18456. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18457. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18458. ] );
  18459. }
  18460. }
  18461. this.computeCentroids();
  18462. this.computeFaceNormals();
  18463. this.computeVertexNormals();
  18464. };
  18465. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18466. /**
  18467. * @author mrdoob / http://mrdoob.com/
  18468. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18469. */
  18470. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18471. THREE.Geometry.call( this );
  18472. this.width = width;
  18473. this.height = height;
  18474. this.widthSegments = widthSegments || 1;
  18475. this.heightSegments = heightSegments || 1;
  18476. var ix, iz;
  18477. var width_half = width / 2;
  18478. var height_half = height / 2;
  18479. var gridX = this.widthSegments;
  18480. var gridZ = this.heightSegments;
  18481. var gridX1 = gridX + 1;
  18482. var gridZ1 = gridZ + 1;
  18483. var segment_width = this.width / gridX;
  18484. var segment_height = this.height / gridZ;
  18485. var normal = new THREE.Vector3( 0, 0, 1 );
  18486. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18487. for ( ix = 0; ix < gridX1; ix ++ ) {
  18488. var x = ix * segment_width - width_half;
  18489. var y = iz * segment_height - height_half;
  18490. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18491. }
  18492. }
  18493. for ( iz = 0; iz < gridZ; iz ++ ) {
  18494. for ( ix = 0; ix < gridX; ix ++ ) {
  18495. var a = ix + gridX1 * iz;
  18496. var b = ix + gridX1 * ( iz + 1 );
  18497. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18498. var d = ( ix + 1 ) + gridX1 * iz;
  18499. var face = new THREE.Face4( a, b, c, d );
  18500. face.normal.copy( normal );
  18501. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18502. this.faces.push( face );
  18503. this.faceVertexUvs[ 0 ].push( [
  18504. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18505. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18506. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18507. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18508. ] );
  18509. }
  18510. }
  18511. this.computeCentroids();
  18512. };
  18513. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18514. /**
  18515. * @author mrdoob / http://mrdoob.com/
  18516. */
  18517. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18518. THREE.Geometry.call( this );
  18519. this.radius = radius || 50;
  18520. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18521. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18522. phiStart = phiStart !== undefined ? phiStart : 0;
  18523. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18524. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18525. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18526. var x, y, vertices = [], uvs = [];
  18527. for ( y = 0; y <= this.heightSegments; y ++ ) {
  18528. var verticesRow = [];
  18529. var uvsRow = [];
  18530. for ( x = 0; x <= this.widthSegments; x ++ ) {
  18531. var u = x / this.widthSegments;
  18532. var v = y / this.heightSegments;
  18533. var vertex = new THREE.Vector3();
  18534. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18535. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  18536. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18537. this.vertices.push( vertex );
  18538. verticesRow.push( this.vertices.length - 1 );
  18539. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18540. }
  18541. vertices.push( verticesRow );
  18542. uvs.push( uvsRow );
  18543. }
  18544. for ( y = 0; y < this.heightSegments; y ++ ) {
  18545. for ( x = 0; x < this.widthSegments; x ++ ) {
  18546. var v1 = vertices[ y ][ x + 1 ];
  18547. var v2 = vertices[ y ][ x ];
  18548. var v3 = vertices[ y + 1 ][ x ];
  18549. var v4 = vertices[ y + 1 ][ x + 1 ];
  18550. var n1 = this.vertices[ v1 ].clone().normalize();
  18551. var n2 = this.vertices[ v2 ].clone().normalize();
  18552. var n3 = this.vertices[ v3 ].clone().normalize();
  18553. var n4 = this.vertices[ v4 ].clone().normalize();
  18554. var uv1 = uvs[ y ][ x + 1 ].clone();
  18555. var uv2 = uvs[ y ][ x ].clone();
  18556. var uv3 = uvs[ y + 1 ][ x ].clone();
  18557. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18558. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  18559. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18560. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18561. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  18562. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18563. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18564. } else {
  18565. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18566. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18567. }
  18568. }
  18569. }
  18570. this.computeCentroids();
  18571. this.computeFaceNormals();
  18572. this.boundingSphere = { radius: this.radius };
  18573. };
  18574. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18575. /**
  18576. * @author zz85 / http://www.lab4games.net/zz85/blog
  18577. * @author alteredq / http://alteredqualia.com/
  18578. *
  18579. * For creating 3D text geometry in three.js
  18580. *
  18581. * Text = 3D Text
  18582. *
  18583. * parameters = {
  18584. * size: <float>, // size of the text
  18585. * height: <float>, // thickness to extrude text
  18586. * curveSegments: <int>, // number of points on the curves
  18587. *
  18588. * font: <string>, // font name
  18589. * weight: <string>, // font weight (normal, bold)
  18590. * style: <string>, // font style (normal, italics)
  18591. *
  18592. * bevelEnabled: <bool>, // turn on bevel
  18593. * bevelThickness: <float>, // how deep into text bevel goes
  18594. * bevelSize: <float>, // how far from text outline is bevel
  18595. * }
  18596. *
  18597. */
  18598. /* Usage Examples
  18599. // TextGeometry wrapper
  18600. var text3d = new TextGeometry( text, options );
  18601. // Complete manner
  18602. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18603. var text3d = new ExtrudeGeometry( textShapes, options );
  18604. */
  18605. THREE.TextGeometry = function ( text, parameters ) {
  18606. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18607. // translate parameters to ExtrudeGeometry API
  18608. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18609. // defaults
  18610. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18611. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18612. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18613. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18614. };
  18615. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18616. /**
  18617. * @author oosmoxiecode
  18618. * @author mrdoob / http://mrdoob.com/
  18619. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18620. */
  18621. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  18622. THREE.Geometry.call( this );
  18623. var scope = this;
  18624. this.radius = radius || 100;
  18625. this.tube = tube || 40;
  18626. this.radialSegments = radialSegments || 8;
  18627. this.tubularSegments = tubularSegments || 6;
  18628. this.arc = arc || Math.PI * 2;
  18629. var center = new THREE.Vector3(), uvs = [], normals = [];
  18630. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  18631. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  18632. var u = i / this.tubularSegments * this.arc;
  18633. var v = j / this.radialSegments * Math.PI * 2;
  18634. center.x = this.radius * Math.cos( u );
  18635. center.y = this.radius * Math.sin( u );
  18636. var vertex = new THREE.Vector3();
  18637. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18638. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18639. vertex.z = this.tube * Math.sin( v );
  18640. this.vertices.push( vertex );
  18641. uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
  18642. normals.push( vertex.clone().subSelf( center ).normalize() );
  18643. }
  18644. }
  18645. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  18646. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  18647. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  18648. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18649. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  18650. var d = ( this.tubularSegments + 1 ) * j + i;
  18651. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18652. face.normal.addSelf( normals[ a ] );
  18653. face.normal.addSelf( normals[ b ] );
  18654. face.normal.addSelf( normals[ c ] );
  18655. face.normal.addSelf( normals[ d ] );
  18656. face.normal.normalize();
  18657. this.faces.push( face );
  18658. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18659. }
  18660. }
  18661. this.computeCentroids();
  18662. };
  18663. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18664. /**
  18665. * @author oosmoxiecode
  18666. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18667. */
  18668. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  18669. THREE.Geometry.call( this );
  18670. var scope = this;
  18671. this.radius = radius || 200;
  18672. this.tube = tube || 40;
  18673. this.radialSegments = radialSegments || 64;
  18674. this.tubularSegments = tubularSegments || 8;
  18675. this.p = p || 2;
  18676. this.q = q || 3;
  18677. this.heightScale = heightScale || 1;
  18678. this.grid = new Array(this.radialSegments);
  18679. var tang = new THREE.Vector3();
  18680. var n = new THREE.Vector3();
  18681. var bitan = new THREE.Vector3();
  18682. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18683. this.grid[ i ] = new Array( this.tubularSegments );
  18684. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18685. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  18686. var v = j / this.tubularSegments * 2 * Math.PI;
  18687. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18688. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18689. var cx, cy;
  18690. tang.sub( p2, p1 );
  18691. n.add( p2, p1 );
  18692. bitan.cross( tang, n );
  18693. n.cross( bitan, tang );
  18694. bitan.normalize();
  18695. n.normalize();
  18696. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18697. cy = this.tube * Math.sin( v );
  18698. p1.x += cx * n.x + cy * bitan.x;
  18699. p1.y += cx * n.y + cy * bitan.y;
  18700. p1.z += cx * n.z + cy * bitan.z;
  18701. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18702. }
  18703. }
  18704. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18705. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18706. var ip = ( i + 1 ) % this.radialSegments;
  18707. var jp = ( j + 1 ) % this.tubularSegments;
  18708. var a = this.grid[ i ][ j ];
  18709. var b = this.grid[ ip ][ j ];
  18710. var c = this.grid[ ip ][ jp ];
  18711. var d = this.grid[ i ][ jp ];
  18712. var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
  18713. var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  18714. var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18715. var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18716. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18717. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18718. }
  18719. }
  18720. this.computeCentroids();
  18721. this.computeFaceNormals();
  18722. this.computeVertexNormals();
  18723. function vert( x, y, z ) {
  18724. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18725. }
  18726. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18727. var cu = Math.cos( u );
  18728. var cv = Math.cos( v );
  18729. var su = Math.sin( u );
  18730. var quOverP = in_q / in_p * u;
  18731. var cs = Math.cos( quOverP );
  18732. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18733. var ty = radius * ( 2 + cs ) * su * 0.5;
  18734. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18735. return new THREE.Vector3( tx, ty, tz );
  18736. }
  18737. };
  18738. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18739. /**
  18740. * @author WestLangley / https://github.com/WestLangley
  18741. * @author zz85 / https://github.com/zz85
  18742. * @author miningold / https://github.com/miningold
  18743. *
  18744. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18745. *
  18746. * Creates a tube which extrudes along a 3d spline
  18747. *
  18748. * Uses parallel transport frames as described in
  18749. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18750. */
  18751. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  18752. THREE.Geometry.call( this );
  18753. this.path = path;
  18754. this.segments = segments || 64;
  18755. this.radius = radius || 1;
  18756. this.radiusSegments = radiusSegments || 8;
  18757. this.closed = closed || false;
  18758. if ( debug ) this.debug = new THREE.Object3D();
  18759. this.grid = [];
  18760. var scope = this,
  18761. tangent,
  18762. normal,
  18763. binormal,
  18764. numpoints = this.segments + 1,
  18765. x, y, z,
  18766. tx, ty, tz,
  18767. u, v,
  18768. cx, cy,
  18769. pos, pos2 = new THREE.Vector3(),
  18770. i, j,
  18771. ip, jp,
  18772. a, b, c, d,
  18773. uva, uvb, uvc, uvd;
  18774. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  18775. tangents = frames.tangents,
  18776. normals = frames.normals,
  18777. binormals = frames.binormals;
  18778. // proxy internals
  18779. this.tangents = tangents;
  18780. this.normals = normals;
  18781. this.binormals = binormals;
  18782. function vert( x, y, z ) {
  18783. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18784. }
  18785. // consruct the grid
  18786. for ( i = 0; i < numpoints; i++ ) {
  18787. this.grid[ i ] = [];
  18788. u = i / ( numpoints - 1 );
  18789. pos = path.getPointAt( u );
  18790. tangent = tangents[ i ];
  18791. normal = normals[ i ];
  18792. binormal = binormals[ i ];
  18793. if ( this.debug ) {
  18794. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  18795. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  18796. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  18797. }
  18798. for ( j = 0; j < this.radiusSegments; j++ ) {
  18799. v = j / this.radiusSegments * 2 * Math.PI;
  18800. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18801. cy = this.radius * Math.sin( v );
  18802. pos2.copy( pos );
  18803. pos2.x += cx * normal.x + cy * binormal.x;
  18804. pos2.y += cx * normal.y + cy * binormal.y;
  18805. pos2.z += cx * normal.z + cy * binormal.z;
  18806. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18807. }
  18808. }
  18809. // construct the mesh
  18810. for ( i = 0; i < this.segments; i++ ) {
  18811. for ( j = 0; j < this.radiusSegments; j++ ) {
  18812. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  18813. jp = (j + 1) % this.radiusSegments;
  18814. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18815. b = this.grid[ ip ][ j ];
  18816. c = this.grid[ ip ][ jp ];
  18817. d = this.grid[ i ][ jp ];
  18818. uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
  18819. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
  18820. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  18821. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
  18822. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18823. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18824. }
  18825. }
  18826. this.computeCentroids();
  18827. this.computeFaceNormals();
  18828. this.computeVertexNormals();
  18829. };
  18830. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18831. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18832. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18833. var
  18834. tangent = new THREE.Vector3(),
  18835. normal = new THREE.Vector3(),
  18836. binormal = new THREE.Vector3(),
  18837. tangents = [],
  18838. normals = [],
  18839. binormals = [],
  18840. vec = new THREE.Vector3(),
  18841. mat = new THREE.Matrix4(),
  18842. numpoints = segments + 1,
  18843. theta,
  18844. epsilon = 0.0001,
  18845. smallest,
  18846. tx, ty, tz,
  18847. i, u, v;
  18848. // expose internals
  18849. this.tangents = tangents;
  18850. this.normals = normals;
  18851. this.binormals = binormals;
  18852. // compute the tangent vectors for each segment on the path
  18853. for ( i = 0; i < numpoints; i++ ) {
  18854. u = i / ( numpoints - 1 );
  18855. tangents[ i ] = path.getTangentAt( u );
  18856. tangents[ i ].normalize();
  18857. }
  18858. initialNormal3();
  18859. function initialNormal1(lastBinormal) {
  18860. // fixed start binormal. Has dangers of 0 vectors
  18861. normals[ 0 ] = new THREE.Vector3();
  18862. binormals[ 0 ] = new THREE.Vector3();
  18863. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18864. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  18865. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18866. }
  18867. function initialNormal2() {
  18868. // This uses the Frenet-Serret formula for deriving binormal
  18869. var t2 = path.getTangentAt( epsilon );
  18870. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  18871. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  18872. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18873. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18874. }
  18875. function initialNormal3() {
  18876. // select an initial normal vector perpenicular to the first tangent vector,
  18877. // and in the direction of the smallest tangent xyz component
  18878. normals[ 0 ] = new THREE.Vector3();
  18879. binormals[ 0 ] = new THREE.Vector3();
  18880. smallest = Number.MAX_VALUE;
  18881. tx = Math.abs( tangents[ 0 ].x );
  18882. ty = Math.abs( tangents[ 0 ].y );
  18883. tz = Math.abs( tangents[ 0 ].z );
  18884. if ( tx <= smallest ) {
  18885. smallest = tx;
  18886. normal.set( 1, 0, 0 );
  18887. }
  18888. if ( ty <= smallest ) {
  18889. smallest = ty;
  18890. normal.set( 0, 1, 0 );
  18891. }
  18892. if ( tz <= smallest ) {
  18893. normal.set( 0, 0, 1 );
  18894. }
  18895. vec.cross( tangents[ 0 ], normal ).normalize();
  18896. normals[ 0 ].cross( tangents[ 0 ], vec );
  18897. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  18898. }
  18899. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18900. for ( i = 1; i < numpoints; i++ ) {
  18901. normals[ i ] = normals[ i-1 ].clone();
  18902. binormals[ i ] = binormals[ i-1 ].clone();
  18903. vec.cross( tangents[ i-1 ], tangents[ i ] );
  18904. if ( vec.length() > epsilon ) {
  18905. vec.normalize();
  18906. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  18907. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  18908. }
  18909. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18910. }
  18911. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18912. if ( closed ) {
  18913. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  18914. theta /= ( numpoints - 1 );
  18915. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  18916. theta = -theta;
  18917. }
  18918. for ( i = 1; i < numpoints; i++ ) {
  18919. // twist a little...
  18920. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  18921. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18922. }
  18923. }
  18924. };
  18925. /**
  18926. * @author clockworkgeek / https://github.com/clockworkgeek
  18927. * @author timothypratley / https://github.com/timothypratley
  18928. */
  18929. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  18930. THREE.Geometry.call( this );
  18931. radius = radius || 1;
  18932. detail = detail || 0;
  18933. var that = this;
  18934. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  18935. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  18936. }
  18937. var midpoints = [], p = this.vertices;
  18938. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18939. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  18940. }
  18941. this.mergeVertices();
  18942. // Apply radius
  18943. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  18944. this.vertices[ i ].multiplyScalar( radius );
  18945. }
  18946. // Project vector onto sphere's surface
  18947. function prepare( vector ) {
  18948. var vertex = vector.normalize().clone();
  18949. vertex.index = that.vertices.push( vertex ) - 1;
  18950. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  18951. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  18952. var v = inclination( vector ) / Math.PI + 0.5;
  18953. vertex.uv = new THREE.UV( u, 1 - v );
  18954. return vertex;
  18955. }
  18956. // Approximate a curved face with recursively sub-divided triangles.
  18957. function make( v1, v2, v3, detail ) {
  18958. if ( detail < 1 ) {
  18959. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  18960. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  18961. face.normal = face.centroid.clone().normalize();
  18962. that.faces.push( face );
  18963. var azi = azimuth( face.centroid );
  18964. that.faceVertexUvs[ 0 ].push( [
  18965. correctUV( v1.uv, v1, azi ),
  18966. correctUV( v2.uv, v2, azi ),
  18967. correctUV( v3.uv, v3, azi )
  18968. ] );
  18969. } else {
  18970. detail -= 1;
  18971. // split triangle into 4 smaller triangles
  18972. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  18973. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  18974. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  18975. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  18976. }
  18977. }
  18978. function midpoint( v1, v2 ) {
  18979. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  18980. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  18981. var mid = midpoints[ v1.index ][ v2.index ];
  18982. if ( mid === undefined ) {
  18983. // generate mean point and project to surface with prepare()
  18984. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  18985. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  18986. );
  18987. }
  18988. return mid;
  18989. }
  18990. // Angle around the Y axis, counter-clockwise when looking from above.
  18991. function azimuth( vector ) {
  18992. return Math.atan2( vector.z, -vector.x );
  18993. }
  18994. // Angle above the XZ plane.
  18995. function inclination( vector ) {
  18996. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18997. }
  18998. // Texture fixing helper. Spheres have some odd behaviours.
  18999. function correctUV( uv, vector, azimuth ) {
  19000. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19001. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19002. return uv;
  19003. }
  19004. this.computeCentroids();
  19005. this.boundingSphere = { radius: radius };
  19006. };
  19007. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19008. /**
  19009. * @author timothypratley / https://github.com/timothypratley
  19010. */
  19011. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19012. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19013. var vertices = [
  19014. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19015. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19016. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19017. ];
  19018. var faces = [
  19019. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19020. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19021. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19022. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19023. ];
  19024. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19025. };
  19026. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19027. /**
  19028. * @author timothypratley / https://github.com/timothypratley
  19029. */
  19030. THREE.OctahedronGeometry = function ( radius, detail ) {
  19031. var vertices = [
  19032. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19033. ];
  19034. var faces = [
  19035. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19036. ];
  19037. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19038. };
  19039. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19040. /**
  19041. * @author timothypratley / https://github.com/timothypratley
  19042. */
  19043. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19044. var vertices = [
  19045. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19046. ];
  19047. var faces = [
  19048. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19049. ];
  19050. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19051. };
  19052. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19053. /**
  19054. * @author zz85 / https://github.com/zz85
  19055. * Parametric Surfaces Geometry
  19056. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19057. *
  19058. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19059. *
  19060. */
  19061. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19062. THREE.Geometry.call( this );
  19063. var verts = this.vertices;
  19064. var faces = this.faces;
  19065. var uvs = this.faceVertexUvs[ 0 ];
  19066. useTris = (useTris === undefined) ? false : useTris;
  19067. var i, il, j, p;
  19068. var u, v;
  19069. var stackCount = stacks + 1;
  19070. var sliceCount = slices + 1;
  19071. for ( i = 0; i <= stacks; i ++ ) {
  19072. v = i / stacks;
  19073. for ( j = 0; j <= slices; j ++ ) {
  19074. u = j / slices;
  19075. p = func( u, v );
  19076. verts.push( p );
  19077. }
  19078. }
  19079. var a, b, c, d;
  19080. var uva, uvb, uvc, uvd;
  19081. for ( i = 0; i < stacks; i ++ ) {
  19082. for ( j = 0; j < slices; j ++ ) {
  19083. a = i * sliceCount + j;
  19084. b = i * sliceCount + j + 1;
  19085. c = (i + 1) * sliceCount + j;
  19086. d = (i + 1) * sliceCount + j + 1;
  19087. uva = new THREE.UV( j / slices, i / stacks );
  19088. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19089. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19090. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19091. if ( useTris ) {
  19092. faces.push( new THREE.Face3( a, b, c ) );
  19093. faces.push( new THREE.Face3( b, d, c ) );
  19094. uvs.push( [ uva, uvb, uvc ] );
  19095. uvs.push( [ uvb, uvd, uvc ] );
  19096. } else {
  19097. faces.push( new THREE.Face4( a, b, d, c ) );
  19098. uvs.push( [ uva, uvb, uvd, uvc ] );
  19099. }
  19100. }
  19101. }
  19102. // console.log(this);
  19103. // magic bullet
  19104. // var diff = this.mergeVertices();
  19105. // console.log('removed ', diff, ' vertices by merging');
  19106. this.computeCentroids();
  19107. this.computeFaceNormals();
  19108. this.computeVertexNormals();
  19109. };
  19110. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19111. /**
  19112. * @author qiao / https://github.com/qiao
  19113. * @fileoverview This is a convex hull generator using the incremental method.
  19114. * The complexity is O(n^2) where n is the number of vertices.
  19115. * O(nlogn) algorithms do exist, but they are much more complicated.
  19116. *
  19117. * Benchmark:
  19118. *
  19119. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19120. *
  19121. * Num Vertices Time(ms)
  19122. *
  19123. * 10 1
  19124. * 20 3
  19125. * 30 19
  19126. * 40 48
  19127. * 50 107
  19128. */
  19129. THREE.ConvexGeometry = function( vertices ) {
  19130. THREE.Geometry.call( this );
  19131. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19132. for ( var i = 3; i < vertices.length; i++ ) {
  19133. addPoint( i );
  19134. }
  19135. function addPoint( vertexId ) {
  19136. var vertex = vertices[ vertexId ].clone();
  19137. var mag = vertex.length();
  19138. vertex.x += mag * randomOffset();
  19139. vertex.y += mag * randomOffset();
  19140. vertex.z += mag * randomOffset();
  19141. var hole = [];
  19142. for ( var f = 0; f < faces.length; ) {
  19143. var face = faces[ f ];
  19144. // for each face, if the vertex can see it,
  19145. // then we try to add the face's edges into the hole.
  19146. if ( visible( face, vertex ) ) {
  19147. for ( var e = 0; e < 3; e++ ) {
  19148. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19149. var boundary = true;
  19150. // remove duplicated edges.
  19151. for ( var h = 0; h < hole.length; h++ ) {
  19152. if ( equalEdge( hole[ h ], edge ) ) {
  19153. hole[ h ] = hole[ hole.length - 1 ];
  19154. hole.pop();
  19155. boundary = false;
  19156. break;
  19157. }
  19158. }
  19159. if ( boundary ) {
  19160. hole.push( edge );
  19161. }
  19162. }
  19163. // remove faces[ f ]
  19164. faces[ f ] = faces[ faces.length - 1 ];
  19165. faces.pop();
  19166. } else { // not visible
  19167. f++;
  19168. }
  19169. }
  19170. // construct the new faces formed by the edges of the hole and the vertex
  19171. for ( var h = 0; h < hole.length; h++ ) {
  19172. faces.push( [
  19173. hole[ h ][ 0 ],
  19174. hole[ h ][ 1 ],
  19175. vertexId
  19176. ] );
  19177. }
  19178. }
  19179. /**
  19180. * Whether the face is visible from the vertex
  19181. */
  19182. function visible( face, vertex ) {
  19183. var va = vertices[ face[ 0 ] ];
  19184. var vb = vertices[ face[ 1 ] ];
  19185. var vc = vertices[ face[ 2 ] ];
  19186. var n = normal( va, vb, vc );
  19187. // distance from face to origin
  19188. var dist = n.dot( va );
  19189. return n.dot( vertex ) >= dist;
  19190. }
  19191. /**
  19192. * Face normal
  19193. */
  19194. function normal( va, vb, vc ) {
  19195. var cb = new THREE.Vector3();
  19196. var ab = new THREE.Vector3();
  19197. cb.sub( vc, vb );
  19198. ab.sub( va, vb );
  19199. cb.crossSelf( ab );
  19200. cb.normalize();
  19201. return cb;
  19202. }
  19203. /**
  19204. * Detect whether two edges are equal.
  19205. * Note that when constructing the convex hull, two same edges can only
  19206. * be of the negative direction.
  19207. */
  19208. function equalEdge( ea, eb ) {
  19209. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19210. }
  19211. /**
  19212. * Create a random offset between -1e-6 and 1e-6.
  19213. */
  19214. function randomOffset() {
  19215. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19216. }
  19217. /**
  19218. * XXX: Not sure if this is the correct approach. Need someone to review.
  19219. */
  19220. function vertexUv( vertex ) {
  19221. var mag = vertex.length();
  19222. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19223. }
  19224. // Push vertices into `this.vertices`, skipping those inside the hull
  19225. var id = 0;
  19226. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19227. for ( var i = 0; i < faces.length; i++ ) {
  19228. var face = faces[ i ];
  19229. for ( var j = 0; j < 3; j++ ) {
  19230. if ( newId[ face[ j ] ] === undefined ) {
  19231. newId[ face[ j ] ] = id++;
  19232. this.vertices.push( vertices[ face[ j ] ] );
  19233. }
  19234. face[ j ] = newId[ face[ j ] ];
  19235. }
  19236. }
  19237. // Convert faces into instances of THREE.Face3
  19238. for ( var i = 0; i < faces.length; i++ ) {
  19239. this.faces.push( new THREE.Face3(
  19240. faces[ i ][ 0 ],
  19241. faces[ i ][ 1 ],
  19242. faces[ i ][ 2 ]
  19243. ) );
  19244. }
  19245. // Compute UVs
  19246. for ( var i = 0; i < this.faces.length; i++ ) {
  19247. var face = this.faces[ i ];
  19248. this.faceVertexUvs[ 0 ].push( [
  19249. vertexUv( this.vertices[ face.a ] ),
  19250. vertexUv( this.vertices[ face.b ] ),
  19251. vertexUv( this.vertices[ face.c ])
  19252. ] );
  19253. }
  19254. this.computeCentroids();
  19255. this.computeFaceNormals();
  19256. this.computeVertexNormals();
  19257. };
  19258. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19259. /**
  19260. * @author sroucheray / http://sroucheray.org/
  19261. * @author mrdoob / http://mrdoob.com/
  19262. */
  19263. THREE.AxisHelper = function ( size ) {
  19264. var geometry = new THREE.Geometry();
  19265. geometry.vertices.push(
  19266. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19267. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19268. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19269. );
  19270. geometry.colors.push(
  19271. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19272. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19273. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19274. );
  19275. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19276. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19277. };
  19278. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19279. /**
  19280. * @author WestLangley / http://github.com/WestLangley
  19281. * @author zz85 / https://github.com/zz85
  19282. *
  19283. * Creates an arrow for visualizing directions
  19284. *
  19285. * Parameters:
  19286. * dir - Vector3
  19287. * origin - Vector3
  19288. * length - Number
  19289. * hex - color in hex value
  19290. */
  19291. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19292. THREE.Object3D.call( this );
  19293. if ( hex === undefined ) hex = 0xffff00;
  19294. if ( length === undefined ) length = 20;
  19295. var lineGeometry = new THREE.Geometry();
  19296. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19297. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19298. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19299. this.add( this.line );
  19300. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19301. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19302. this.cone.position.set( 0, 1, 0 );
  19303. this.add( this.cone );
  19304. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19305. this.setDirection( dir );
  19306. this.setLength( length );
  19307. };
  19308. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19309. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19310. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19311. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19312. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19313. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19314. };
  19315. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19316. this.scale.set( length, length, length );
  19317. };
  19318. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19319. this.line.material.color.setHex( hex );
  19320. this.cone.material.color.setHex( hex );
  19321. };
  19322. /**
  19323. * @author alteredq / http://alteredqualia.com/
  19324. *
  19325. * - shows frustum, line of sight and up of the camera
  19326. * - suitable for fast updates
  19327. * - based on frustum visualization in lightgl.js shadowmap example
  19328. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19329. */
  19330. THREE.CameraHelper = function ( camera ) {
  19331. THREE.Line.call( this );
  19332. var scope = this;
  19333. this.geometry = new THREE.Geometry();
  19334. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19335. this.type = THREE.LinePieces;
  19336. this.matrixWorld = camera.matrixWorld;
  19337. this.matrixAutoUpdate = false;
  19338. this.pointMap = {};
  19339. // colors
  19340. var hexFrustum = 0xffaa00;
  19341. var hexCone = 0xff0000;
  19342. var hexUp = 0x00aaff;
  19343. var hexTarget = 0xffffff;
  19344. var hexCross = 0x333333;
  19345. // near
  19346. addLine( "n1", "n2", hexFrustum );
  19347. addLine( "n2", "n4", hexFrustum );
  19348. addLine( "n4", "n3", hexFrustum );
  19349. addLine( "n3", "n1", hexFrustum );
  19350. // far
  19351. addLine( "f1", "f2", hexFrustum );
  19352. addLine( "f2", "f4", hexFrustum );
  19353. addLine( "f4", "f3", hexFrustum );
  19354. addLine( "f3", "f1", hexFrustum );
  19355. // sides
  19356. addLine( "n1", "f1", hexFrustum );
  19357. addLine( "n2", "f2", hexFrustum );
  19358. addLine( "n3", "f3", hexFrustum );
  19359. addLine( "n4", "f4", hexFrustum );
  19360. // cone
  19361. addLine( "p", "n1", hexCone );
  19362. addLine( "p", "n2", hexCone );
  19363. addLine( "p", "n3", hexCone );
  19364. addLine( "p", "n4", hexCone );
  19365. // up
  19366. addLine( "u1", "u2", hexUp );
  19367. addLine( "u2", "u3", hexUp );
  19368. addLine( "u3", "u1", hexUp );
  19369. // target
  19370. addLine( "c", "t", hexTarget );
  19371. addLine( "p", "c", hexCross );
  19372. // cross
  19373. addLine( "cn1", "cn2", hexCross );
  19374. addLine( "cn3", "cn4", hexCross );
  19375. addLine( "cf1", "cf2", hexCross );
  19376. addLine( "cf3", "cf4", hexCross );
  19377. this.camera = camera;
  19378. function addLine( a, b, hex ) {
  19379. addPoint( a, hex );
  19380. addPoint( b, hex );
  19381. }
  19382. function addPoint( id, hex ) {
  19383. scope.geometry.vertices.push( new THREE.Vector3() );
  19384. scope.geometry.colors.push( new THREE.Color( hex ) );
  19385. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19386. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19387. }
  19388. this.update( camera );
  19389. };
  19390. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19391. THREE.CameraHelper.prototype.update = function () {
  19392. var scope = this;
  19393. var w = 1, h = 1;
  19394. // we need just camera projection matrix
  19395. // world matrix must be identity
  19396. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19397. // center / target
  19398. setPoint( "c", 0, 0, -1 );
  19399. setPoint( "t", 0, 0, 1 );
  19400. // near
  19401. setPoint( "n1", -w, -h, -1 );
  19402. setPoint( "n2", w, -h, -1 );
  19403. setPoint( "n3", -w, h, -1 );
  19404. setPoint( "n4", w, h, -1 );
  19405. // far
  19406. setPoint( "f1", -w, -h, 1 );
  19407. setPoint( "f2", w, -h, 1 );
  19408. setPoint( "f3", -w, h, 1 );
  19409. setPoint( "f4", w, h, 1 );
  19410. // up
  19411. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19412. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19413. setPoint( "u3", 0, h * 2, -1 );
  19414. // cross
  19415. setPoint( "cf1", -w, 0, 1 );
  19416. setPoint( "cf2", w, 0, 1 );
  19417. setPoint( "cf3", 0, -h, 1 );
  19418. setPoint( "cf4", 0, h, 1 );
  19419. setPoint( "cn1", -w, 0, -1 );
  19420. setPoint( "cn2", w, 0, -1 );
  19421. setPoint( "cn3", 0, -h, -1 );
  19422. setPoint( "cn4", 0, h, -1 );
  19423. function setPoint( point, x, y, z ) {
  19424. THREE.CameraHelper.__v.set( x, y, z );
  19425. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19426. var points = scope.pointMap[ point ];
  19427. if ( points !== undefined ) {
  19428. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19429. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19430. }
  19431. }
  19432. }
  19433. this.geometry.verticesNeedUpdate = true;
  19434. };
  19435. THREE.CameraHelper.__projector = new THREE.Projector();
  19436. THREE.CameraHelper.__v = new THREE.Vector3();
  19437. THREE.CameraHelper.__c = new THREE.Camera();
  19438. /**
  19439. * @author alteredq / http://alteredqualia.com/
  19440. *
  19441. * - shows directional light color, intensity, position, orientation and target
  19442. */
  19443. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  19444. THREE.Object3D.call( this );
  19445. this.light = light;
  19446. // position
  19447. this.position = light.position;
  19448. // direction
  19449. this.direction = new THREE.Vector3();
  19450. this.direction.sub( light.target.position, light.position );
  19451. // color
  19452. this.color = light.color.clone();
  19453. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19454. this.color.r *= intensity;
  19455. this.color.g *= intensity;
  19456. this.color.b *= intensity;
  19457. var hexColor = this.color.getHex();
  19458. // light helper
  19459. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19460. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19461. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19462. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19463. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19464. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19465. this.lightArrow.cone.material.fog = false;
  19466. this.lightArrow.line.material.fog = false;
  19467. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19468. this.add( this.lightArrow );
  19469. this.add( this.lightSphere );
  19470. this.add( this.lightRays );
  19471. this.lightSphere.properties.isGizmo = true;
  19472. this.lightSphere.properties.gizmoSubject = light;
  19473. this.lightSphere.properties.gizmoRoot = this;
  19474. // light target helper
  19475. this.targetSphere = null;
  19476. if ( light.target.properties.targetInverse ) {
  19477. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19478. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19479. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19480. this.targetSphere.position = light.target.position;
  19481. this.targetSphere.properties.isGizmo = true;
  19482. this.targetSphere.properties.gizmoSubject = light.target;
  19483. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19484. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19485. var lineGeometry = new THREE.Geometry();
  19486. lineGeometry.vertices.push( this.position.clone() );
  19487. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19488. lineGeometry.computeLineDistances();
  19489. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19490. this.targetLine.properties.isGizmo = true;
  19491. }
  19492. //
  19493. this.properties.isGizmo = true;
  19494. }
  19495. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19496. THREE.DirectionalLightHelper.prototype.update = function () {
  19497. // update arrow orientation
  19498. // pointing from light to target
  19499. this.direction.sub( this.light.target.position, this.light.position );
  19500. this.lightArrow.setDirection( this.direction );
  19501. // update arrow, spheres, rays and line colors to light color * light intensity
  19502. this.color.copy( this.light.color );
  19503. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19504. this.color.r *= intensity;
  19505. this.color.g *= intensity;
  19506. this.color.b *= intensity;
  19507. this.lightArrow.setColor( this.color.getHex() );
  19508. this.lightSphere.material.color.copy( this.color );
  19509. this.lightRays.material.color.copy( this.color );
  19510. this.targetSphere.material.color.copy( this.color );
  19511. this.targetLine.material.color.copy( this.color );
  19512. // update target line vertices
  19513. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19514. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19515. this.targetLine.geometry.computeLineDistances();
  19516. this.targetLine.geometry.verticesNeedUpdate = true;
  19517. }
  19518. /**
  19519. * @author alteredq / http://alteredqualia.com/
  19520. *
  19521. * - shows hemisphere light intensity, sky and ground colors and directions
  19522. */
  19523. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  19524. THREE.Object3D.call( this );
  19525. this.light = light;
  19526. // position
  19527. this.position = light.position;
  19528. //
  19529. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19530. // sky color
  19531. this.color = light.color.clone();
  19532. this.color.r *= intensity;
  19533. this.color.g *= intensity;
  19534. this.color.b *= intensity;
  19535. var hexColor = this.color.getHex();
  19536. // ground color
  19537. this.groundColor = light.groundColor.clone();
  19538. this.groundColor.r *= intensity;
  19539. this.groundColor.g *= intensity;
  19540. this.groundColor.b *= intensity;
  19541. var hexColorGround = this.groundColor.getHex();
  19542. // double colored light bulb
  19543. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  19544. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  19545. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19546. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  19547. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  19548. bulbGeometry.faces[ i ].materialIndex = 0;
  19549. }
  19550. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  19551. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  19552. }
  19553. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  19554. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  19555. // arrows for sky and ground light directions
  19556. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  19557. this.lightArrow.rotation.x = Math.PI;
  19558. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  19559. var joint = new THREE.Object3D();
  19560. joint.rotation.x = -Math.PI * 0.5;
  19561. joint.add( this.lightSphere );
  19562. joint.add( this.lightArrow );
  19563. joint.add( this.lightArrowGround );
  19564. this.add( joint );
  19565. //
  19566. this.lightSphere.properties.isGizmo = true;
  19567. this.lightSphere.properties.gizmoSubject = light;
  19568. this.lightSphere.properties.gizmoRoot = this;
  19569. //
  19570. this.properties.isGizmo = true;
  19571. //
  19572. this.target = new THREE.Vector3();
  19573. this.lookAt( this.target );
  19574. }
  19575. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19576. THREE.HemisphereLightHelper.prototype.update = function () {
  19577. // update sphere sky and ground colors to light color * light intensity
  19578. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19579. this.color.copy( this.light.color );
  19580. this.groundColor.copy( this.light.groundColor );
  19581. this.color.r *= intensity;
  19582. this.color.g *= intensity;
  19583. this.color.b *= intensity;
  19584. this.groundColor.r *= intensity;
  19585. this.groundColor.g *= intensity;
  19586. this.groundColor.b *= intensity;
  19587. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  19588. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  19589. this.lightArrow.setColor( this.color.getHex() );
  19590. this.lightArrowGround.setColor( this.groundColor.getHex() );
  19591. this.lookAt( this.target );
  19592. }
  19593. /**
  19594. * @author alteredq / http://alteredqualia.com/
  19595. *
  19596. * - shows point light color, intensity, position and distance
  19597. */
  19598. THREE.PointLightHelper = function ( light, sphereSize ) {
  19599. THREE.Object3D.call( this );
  19600. this.light = light;
  19601. // position
  19602. this.position = light.position;
  19603. // color
  19604. this.color = light.color.clone();
  19605. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19606. this.color.r *= intensity;
  19607. this.color.g *= intensity;
  19608. this.color.b *= intensity;
  19609. var hexColor = this.color.getHex();
  19610. // light helper
  19611. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19612. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19613. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  19614. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19615. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19616. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  19617. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19618. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19619. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  19620. var d = light.distance;
  19621. if ( d === 0.0 ) {
  19622. this.lightDistance.visible = false;
  19623. } else {
  19624. this.lightDistance.scale.set( d, d, d );
  19625. }
  19626. this.add( this.lightSphere );
  19627. this.add( this.lightRays );
  19628. this.add( this.lightDistance );
  19629. //
  19630. this.lightSphere.properties.isGizmo = true;
  19631. this.lightSphere.properties.gizmoSubject = light;
  19632. this.lightSphere.properties.gizmoRoot = this;
  19633. //
  19634. this.properties.isGizmo = true;
  19635. }
  19636. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19637. THREE.PointLightHelper.prototype.update = function () {
  19638. // update sphere and rays colors to light color * light intensity
  19639. this.color.copy( this.light.color );
  19640. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19641. this.color.r *= intensity;
  19642. this.color.g *= intensity;
  19643. this.color.b *= intensity;
  19644. this.lightSphere.material.color.copy( this.color );
  19645. this.lightRays.material.color.copy( this.color );
  19646. this.lightDistance.material.color.copy( this.color );
  19647. //
  19648. var d = this.light.distance;
  19649. if ( d === 0.0 ) {
  19650. this.lightDistance.visible = false;
  19651. } else {
  19652. this.lightDistance.visible = true;
  19653. this.lightDistance.scale.set( d, d, d );
  19654. }
  19655. }
  19656. /**
  19657. * @author alteredq / http://alteredqualia.com/
  19658. *
  19659. * - shows spot light color, intensity, position, orientation, light cone and target
  19660. */
  19661. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  19662. THREE.Object3D.call( this );
  19663. this.light = light;
  19664. // position
  19665. this.position = light.position;
  19666. // direction
  19667. this.direction = new THREE.Vector3();
  19668. this.direction.sub( light.target.position, light.position );
  19669. // color
  19670. this.color = light.color.clone();
  19671. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  19672. this.color.r *= intensity;
  19673. this.color.g *= intensity;
  19674. this.color.b *= intensity;
  19675. var hexColor = this.color.getHex();
  19676. // light helper
  19677. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  19678. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  19679. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  19680. var coneMatrix = new THREE.Matrix4();
  19681. coneMatrix.rotateX( -Math.PI/2 );
  19682. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  19683. coneGeometry.applyMatrix( coneMatrix );
  19684. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  19685. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  19686. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  19687. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  19688. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  19689. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  19690. var coneLength = light.distance ? light.distance : 10000;
  19691. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  19692. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19693. this.lightArrow.cone.material.fog = false;
  19694. this.lightArrow.line.material.fog = false;
  19695. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  19696. this.gyroscope = new THREE.Gyroscope();
  19697. this.gyroscope.add( this.lightArrow );
  19698. this.gyroscope.add( this.lightSphere );
  19699. this.gyroscope.add( this.lightRays );
  19700. this.add( this.gyroscope );
  19701. this.add( this.lightCone );
  19702. this.lookAt( light.target.position );
  19703. this.lightSphere.properties.isGizmo = true;
  19704. this.lightSphere.properties.gizmoSubject = light;
  19705. this.lightSphere.properties.gizmoRoot = this;
  19706. // light target helper
  19707. this.targetSphere = null;
  19708. if ( light.target.properties.targetInverse ) {
  19709. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  19710. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  19711. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  19712. this.targetSphere.position = light.target.position;
  19713. this.targetSphere.properties.isGizmo = true;
  19714. this.targetSphere.properties.gizmoSubject = light.target;
  19715. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  19716. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  19717. var lineGeometry = new THREE.Geometry();
  19718. lineGeometry.vertices.push( this.position.clone() );
  19719. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  19720. lineGeometry.computeLineDistances();
  19721. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  19722. this.targetLine.properties.isGizmo = true;
  19723. }
  19724. //
  19725. this.properties.isGizmo = true;
  19726. }
  19727. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  19728. THREE.SpotLightHelper.prototype.update = function () {
  19729. // update arrow orientation
  19730. // pointing from light to target
  19731. this.direction.sub( this.light.target.position, this.light.position );
  19732. this.lightArrow.setDirection( this.direction );
  19733. // update light cone orientation and size
  19734. this.lookAt( this.light.target.position );
  19735. var coneLength = this.light.distance ? this.light.distance : 10000;
  19736. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  19737. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  19738. // update arrow, spheres, rays and line colors to light color * light intensity
  19739. this.color.copy( this.light.color );
  19740. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  19741. this.color.r *= intensity;
  19742. this.color.g *= intensity;
  19743. this.color.b *= intensity;
  19744. this.lightArrow.setColor( this.color.getHex() );
  19745. this.lightSphere.material.color.copy( this.color );
  19746. this.lightRays.material.color.copy( this.color );
  19747. this.lightCone.material.color.copy( this.color );
  19748. this.targetSphere.material.color.copy( this.color );
  19749. this.targetLine.material.color.copy( this.color );
  19750. // update target line vertices
  19751. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  19752. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  19753. this.targetLine.geometry.computeLineDistances();
  19754. this.targetLine.geometry.verticesNeedUpdate = true;
  19755. }
  19756. /*
  19757. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19758. *
  19759. * Subdivision Geometry Modifier
  19760. * using Catmull-Clark Subdivision Surfaces
  19761. * for creating smooth geometry meshes
  19762. *
  19763. * Note: a modifier modifies vertices and faces of geometry,
  19764. * so use geometry.clone() if original geometry needs to be retained
  19765. *
  19766. * Readings:
  19767. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19768. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19769. * http://xrt.wikidot.com/blog:31
  19770. * "Subdivision Surfaces in Character Animation"
  19771. *
  19772. * (on boundary edges)
  19773. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19774. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  19775. *
  19776. * Supports:
  19777. * Closed and Open geometries.
  19778. *
  19779. * TODO:
  19780. * crease vertex and "semi-sharp" features
  19781. * selective subdivision
  19782. */
  19783. THREE.SubdivisionModifier = function( subdivisions ) {
  19784. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19785. // Settings
  19786. this.useOldVertexColors = false;
  19787. this.supportUVs = true;
  19788. this.debug = false;
  19789. };
  19790. // Applies the "modify" pattern
  19791. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19792. var repeats = this.subdivisions;
  19793. while ( repeats-- > 0 ) {
  19794. this.smooth( geometry );
  19795. }
  19796. };
  19797. /// REFACTORING THIS OUT
  19798. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  19799. return Math.min( a, b ) + "_" + Math.max( a, b );
  19800. };
  19801. // Returns a hashmap - of { edge_key: face_index }
  19802. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  19803. var i, il, v1, v2, j, k,
  19804. face, faceIndices, faceIndex,
  19805. edge,
  19806. hash,
  19807. edgeFaceMap = {};
  19808. var orderedKey = THREE.GeometryUtils.orderedKey;
  19809. function mapEdgeHash( hash, i ) {
  19810. if ( edgeFaceMap[ hash ] === undefined ) {
  19811. edgeFaceMap[ hash ] = [];
  19812. }
  19813. edgeFaceMap[ hash ].push( i );
  19814. }
  19815. // construct vertex -> face map
  19816. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19817. face = geometry.faces[ i ];
  19818. if ( face instanceof THREE.Face3 ) {
  19819. hash = orderedKey( face.a, face.b );
  19820. mapEdgeHash( hash, i );
  19821. hash = orderedKey( face.b, face.c );
  19822. mapEdgeHash( hash, i );
  19823. hash = orderedKey( face.c, face.a );
  19824. mapEdgeHash( hash, i );
  19825. } else if ( face instanceof THREE.Face4 ) {
  19826. hash = orderedKey( face.a, face.b );
  19827. mapEdgeHash( hash, i );
  19828. hash = orderedKey( face.b, face.c );
  19829. mapEdgeHash( hash, i );
  19830. hash = orderedKey( face.c, face.d );
  19831. mapEdgeHash( hash, i );
  19832. hash = orderedKey( face.d, face.a );
  19833. mapEdgeHash( hash, i );
  19834. }
  19835. }
  19836. // extract faces
  19837. // var edges = [];
  19838. //
  19839. // var numOfEdges = 0;
  19840. // for (i in edgeFaceMap) {
  19841. // numOfEdges++;
  19842. //
  19843. // edge = edgeFaceMap[i];
  19844. // edges.push(edge);
  19845. //
  19846. // }
  19847. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19848. return edgeFaceMap;
  19849. }
  19850. /////////////////////////////
  19851. // Performs an iteration of Catmull-Clark Subdivision
  19852. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19853. //debug( 'running smooth' );
  19854. // New set of vertices, faces and uvs
  19855. var newVertices = [], newFaces = [], newUVs = [];
  19856. function v( x, y, z ) {
  19857. newVertices.push( new THREE.Vector3( x, y, z ) );
  19858. }
  19859. var scope = this;
  19860. var orderedKey = THREE.GeometryUtils.orderedKey;
  19861. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  19862. function assert() {
  19863. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  19864. }
  19865. function debug() {
  19866. if (scope.debug) console.log.apply(console, arguments);
  19867. }
  19868. function warn() {
  19869. if (console)
  19870. console.log.apply(console, arguments);
  19871. }
  19872. function f4( a, b, c, d, oldFace, orders, facei ) {
  19873. // TODO move vertex selection over here!
  19874. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19875. if (scope.useOldVertexColors) {
  19876. newFace.vertexColors = [];
  19877. var color, tmpColor, order;
  19878. for (var i=0;i<4;i++) {
  19879. order = orders[i];
  19880. color = new THREE.Color(),
  19881. color.setRGB(0,0,0);
  19882. for (var j=0, jl=0; j<order.length;j++) {
  19883. tmpColor = oldFace.vertexColors[order[j]-1];
  19884. color.r += tmpColor.r;
  19885. color.g += tmpColor.g;
  19886. color.b += tmpColor.b;
  19887. }
  19888. color.r /= order.length;
  19889. color.g /= order.length;
  19890. color.b /= order.length;
  19891. newFace.vertexColors[i] = color;
  19892. }
  19893. }
  19894. newFaces.push( newFace );
  19895. if (scope.supportUVs) {
  19896. var aUv = [
  19897. getUV(a, ''),
  19898. getUV(b, facei),
  19899. getUV(c, facei),
  19900. getUV(d, facei)
  19901. ];
  19902. if (!aUv[0]) debug('a :( ', a+':'+facei);
  19903. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  19904. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  19905. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  19906. else
  19907. newUVs.push( aUv );
  19908. }
  19909. }
  19910. var originalPoints = oldGeometry.vertices;
  19911. var originalFaces = oldGeometry.faces;
  19912. var originalVerticesLength = originalPoints.length;
  19913. var newPoints = originalPoints.concat(); // New set of vertices to work on
  19914. var facePoints = [], // these are new points on exisiting faces
  19915. edgePoints = {}; // these are new points on exisiting edges
  19916. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  19917. // TODO: handle this correctly.
  19918. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  19919. function debugCoreStuff() {
  19920. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  19921. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  19922. }
  19923. function getUV(vertexNo, oldFaceNo) {
  19924. var j,jl;
  19925. var key = vertexNo+':'+oldFaceNo;
  19926. var theUV = uvForVertices[key];
  19927. if (!theUV) {
  19928. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  19929. debug('face pt');
  19930. } else {
  19931. debug('edge pt');
  19932. }
  19933. warn('warning, UV not found for', key);
  19934. return null;
  19935. }
  19936. return theUV;
  19937. // Original faces -> Vertex Nos.
  19938. // new Facepoint -> Vertex Nos.
  19939. // edge Points
  19940. }
  19941. function addUV(vertexNo, oldFaceNo, value) {
  19942. var key = vertexNo+':'+oldFaceNo;
  19943. if (!(key in uvForVertices)) {
  19944. uvForVertices[key] = value;
  19945. } else {
  19946. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  19947. }
  19948. }
  19949. // Step 1
  19950. // For each face, add a face point
  19951. // Set each face point to be the centroid of all original points for the respective face.
  19952. // debug(oldGeometry);
  19953. var i, il, j, jl, face;
  19954. // For Uvs
  19955. var uvs = oldGeometry.faceVertexUvs[0];
  19956. var abcd = 'abcd', vertice;
  19957. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  19958. if (scope.supportUVs)
  19959. for (i=0, il = uvs.length; i<il; i++ ) {
  19960. for (j=0,jl=uvs[i].length;j<jl;j++) {
  19961. vertice = originalFaces[i][abcd.charAt(j)];
  19962. addUV(vertice, i, uvs[i][j]);
  19963. }
  19964. }
  19965. if (uvs.length == 0) scope.supportUVs = false;
  19966. // Additional UVs check, if we index original
  19967. var uvCount = 0;
  19968. for (var u in uvForVertices) {
  19969. uvCount++;
  19970. }
  19971. if (!uvCount) {
  19972. scope.supportUVs = false;
  19973. debug('no uvs');
  19974. }
  19975. var avgUv ;
  19976. for (i=0, il = originalFaces.length; i<il ;i++) {
  19977. face = originalFaces[ i ];
  19978. facePoints.push( face.centroid );
  19979. newPoints.push( face.centroid );
  19980. if (!scope.supportUVs) continue;
  19981. // Prepare subdivided uv
  19982. avgUv = new THREE.UV();
  19983. if ( face instanceof THREE.Face3 ) {
  19984. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  19985. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  19986. avgUv.u /= 3;
  19987. avgUv.v /= 3;
  19988. } else if ( face instanceof THREE.Face4 ) {
  19989. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  19990. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  19991. avgUv.u /= 4;
  19992. avgUv.v /= 4;
  19993. }
  19994. addUV(originalVerticesLength + i, '', avgUv);
  19995. }
  19996. // Step 2
  19997. // For each edge, add an edge point.
  19998. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  19999. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  20000. var edge, faceIndexA, faceIndexB, avg;
  20001. // debug('edgeFaceMap', edgeFaceMap);
  20002. var edgeCount = 0;
  20003. var edgeVertex, edgeVertexA, edgeVertexB;
  20004. ////
  20005. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  20006. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  20007. function addVertexEdgeMap(vertex, edge) {
  20008. if (vertexEdgeMap[vertex]===undefined) {
  20009. vertexEdgeMap[vertex] = [];
  20010. }
  20011. vertexEdgeMap[vertex].push(edge);
  20012. }
  20013. function addVertexFaceMap(vertex, face, edge) {
  20014. if (vertexFaceMap[vertex]===undefined) {
  20015. vertexFaceMap[vertex] = {};
  20016. }
  20017. vertexFaceMap[vertex][face] = edge;
  20018. // vertexFaceMap[vertex][face] = null;
  20019. }
  20020. // Prepares vertexEdgeMap and vertexFaceMap
  20021. for (i in edgeFaceMap) { // This is for every edge
  20022. edge = edgeFaceMap[i];
  20023. edgeVertex = i.split('_');
  20024. edgeVertexA = edgeVertex[0];
  20025. edgeVertexB = edgeVertex[1];
  20026. // Maps an edgeVertex to connecting edges
  20027. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  20028. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  20029. for (j=0,jl=edge.length;j<jl;j++) {
  20030. face = edge[j];
  20031. addVertexFaceMap(edgeVertexA, face, i);
  20032. addVertexFaceMap(edgeVertexB, face, i);
  20033. }
  20034. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  20035. // this thing is fishy right now.
  20036. if (edge.length < 2) {
  20037. // edge is "sharp";
  20038. sharpEdges[i] = true;
  20039. sharpVertices[edgeVertexA] = true;
  20040. sharpVertices[edgeVertexB] = true;
  20041. }
  20042. }
  20043. for (i in edgeFaceMap) {
  20044. edge = edgeFaceMap[i];
  20045. faceIndexA = edge[0]; // face index a
  20046. faceIndexB = edge[1]; // face index b
  20047. edgeVertex = i.split('_');
  20048. edgeVertexA = edgeVertex[0];
  20049. edgeVertexB = edgeVertex[1];
  20050. avg = new THREE.Vector3();
  20051. //debug(i, faceIndexB,facePoints[faceIndexB]);
  20052. assert(edge.length > 0, 'an edge without faces?!');
  20053. if (edge.length==1) {
  20054. avg.addSelf(originalPoints[edgeVertexA]);
  20055. avg.addSelf(originalPoints[edgeVertexB]);
  20056. avg.multiplyScalar(0.5);
  20057. sharpVertices[newPoints.length] = true;
  20058. } else {
  20059. avg.addSelf(facePoints[faceIndexA]);
  20060. avg.addSelf(facePoints[faceIndexB]);
  20061. avg.addSelf(originalPoints[edgeVertexA]);
  20062. avg.addSelf(originalPoints[edgeVertexB]);
  20063. avg.multiplyScalar(0.25);
  20064. }
  20065. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  20066. newPoints.push( avg );
  20067. edgeCount ++;
  20068. if (!scope.supportUVs) {
  20069. continue;
  20070. }
  20071. // Prepare subdivided uv
  20072. avgUv = new THREE.UV();
  20073. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  20074. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  20075. avgUv.u /= 2;
  20076. avgUv.v /= 2;
  20077. addUV(edgePoints[i], faceIndexA, avgUv);
  20078. if (edge.length>=2) {
  20079. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  20080. avgUv = new THREE.UV();
  20081. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  20082. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  20083. avgUv.u /= 2;
  20084. avgUv.v /= 2;
  20085. addUV(edgePoints[i], faceIndexB, avgUv);
  20086. }
  20087. }
  20088. debug('-- Step 2 done');
  20089. // Step 3
  20090. // For each face point, add an edge for every edge of the face,
  20091. // connecting the face point to each edge point for the face.
  20092. var facePt, currentVerticeIndex;
  20093. var hashAB, hashBC, hashCD, hashDA, hashCA;
  20094. var abc123 = ['123', '12', '2', '23'];
  20095. var bca123 = ['123', '23', '3', '31'];
  20096. var cab123 = ['123', '31', '1', '12'];
  20097. var abc1234 = ['1234', '12', '2', '23'];
  20098. var bcd1234 = ['1234', '23', '3', '34'];
  20099. var cda1234 = ['1234', '34', '4', '41'];
  20100. var dab1234 = ['1234', '41', '1', '12'];
  20101. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  20102. facePt = facePoints[i];
  20103. face = originalFaces[i];
  20104. currentVerticeIndex = originalVerticesLength+ i;
  20105. if ( face instanceof THREE.Face3 ) {
  20106. // create 3 face4s
  20107. hashAB = orderedKey( face.a, face.b );
  20108. hashBC = orderedKey( face.b, face.c );
  20109. hashCA = orderedKey( face.c, face.a );
  20110. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  20111. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  20112. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  20113. } else if ( face instanceof THREE.Face4 ) {
  20114. // create 4 face4s
  20115. hashAB = orderedKey( face.a, face.b );
  20116. hashBC = orderedKey( face.b, face.c );
  20117. hashCD = orderedKey( face.c, face.d );
  20118. hashDA = orderedKey( face.d, face.a );
  20119. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  20120. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  20121. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  20122. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  20123. } else {
  20124. debug('face should be a face!', face);
  20125. }
  20126. }
  20127. newVertices = newPoints;
  20128. // Step 4
  20129. // For each original point P,
  20130. // take the average F of all n face points for faces touching P,
  20131. // and take the average R of all n edge midpoints for edges touching P,
  20132. // where each edge midpoint is the average of its two endpoint vertices.
  20133. // Move each original point to the point
  20134. var F = new THREE.Vector3();
  20135. var R = new THREE.Vector3();
  20136. var n;
  20137. for (i=0, il = originalPoints.length; i<il; i++) {
  20138. // (F + 2R + (n-3)P) / n
  20139. if (vertexEdgeMap[i]===undefined) continue;
  20140. F.set(0,0,0);
  20141. R.set(0,0,0);
  20142. var newPos = new THREE.Vector3(0,0,0);
  20143. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20144. for (j in vertexFaceMap[i]) {
  20145. F.addSelf(facePoints[j]);
  20146. f++;
  20147. }
  20148. var sharpEdgeCount = 0;
  20149. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20150. // Are we on the border?
  20151. var boundary_case = f != n;
  20152. // if (boundary_case) {
  20153. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20154. // }
  20155. for (j=0;j<n;j++) {
  20156. if (
  20157. sharpEdges[
  20158. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20159. ]) {
  20160. sharpEdgeCount++;
  20161. }
  20162. }
  20163. // if ( sharpEdgeCount==2 ) {
  20164. // continue;
  20165. // // Do not move vertex if there's 2 connecting sharp edges.
  20166. // }
  20167. /*
  20168. if (sharpEdgeCount>2) {
  20169. // TODO
  20170. }
  20171. */
  20172. F.divideScalar(f);
  20173. var boundary_edges = 0;
  20174. if (boundary_case) {
  20175. var bb_edge;
  20176. for (j=0; j<n;j++) {
  20177. edge = vertexEdgeMap[i][j];
  20178. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20179. if (bb_edge) {
  20180. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20181. R.addSelf(midPt);
  20182. boundary_edges++;
  20183. }
  20184. }
  20185. R.divideScalar(4);
  20186. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20187. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20188. } else {
  20189. for (j=0; j<n;j++) {
  20190. edge = vertexEdgeMap[i][j];
  20191. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20192. R.addSelf(midPt);
  20193. }
  20194. R.divideScalar(n);
  20195. }
  20196. // Sum the formula
  20197. newPos.addSelf(originalPoints[i]);
  20198. if (boundary_case) {
  20199. newPos.divideScalar(2);
  20200. newPos.addSelf(R);
  20201. } else {
  20202. newPos.multiplyScalar(n - 3);
  20203. newPos.addSelf(F);
  20204. newPos.addSelf(R.multiplyScalar(2));
  20205. newPos.divideScalar(n);
  20206. }
  20207. newVertices[i] = newPos;
  20208. }
  20209. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20210. newGeometry.vertices = newVertices;
  20211. newGeometry.faces = newFaces;
  20212. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20213. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20214. newGeometry.computeCentroids();
  20215. newGeometry.computeFaceNormals();
  20216. newGeometry.computeVertexNormals();
  20217. };
  20218. /**
  20219. * @author alteredq / http://alteredqualia.com/
  20220. */
  20221. THREE.ImmediateRenderObject = function ( ) {
  20222. THREE.Object3D.call( this );
  20223. this.render = function ( renderCallback ) { };
  20224. };
  20225. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20226. /**
  20227. * @author mikael emtinger / http://gomo.se/
  20228. * @author alteredq / http://alteredqualia.com/
  20229. */
  20230. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20231. THREE.Object3D.call( this );
  20232. this.lensFlares = [];
  20233. this.positionScreen = new THREE.Vector3();
  20234. this.customUpdateCallback = undefined;
  20235. if( texture !== undefined ) {
  20236. this.add( texture, size, distance, blending, color );
  20237. }
  20238. };
  20239. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20240. /*
  20241. * Add: adds another flare
  20242. */
  20243. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20244. if( size === undefined ) size = -1;
  20245. if( distance === undefined ) distance = 0;
  20246. if( opacity === undefined ) opacity = 1;
  20247. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20248. if( blending === undefined ) blending = THREE.NormalBlending;
  20249. distance = Math.min( distance, Math.max( 0, distance ) );
  20250. this.lensFlares.push( { texture: texture, // THREE.Texture
  20251. size: size, // size in pixels (-1 = use texture.width)
  20252. distance: distance, // distance (0-1) from light source (0=at light source)
  20253. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20254. scale: 1, // scale
  20255. rotation: 1, // rotation
  20256. opacity: opacity, // opacity
  20257. color: color, // color
  20258. blending: blending } ); // blending
  20259. };
  20260. /*
  20261. * Update lens flares update positions on all flares based on the screen position
  20262. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20263. */
  20264. THREE.LensFlare.prototype.updateLensFlares = function () {
  20265. var f, fl = this.lensFlares.length;
  20266. var flare;
  20267. var vecX = -this.positionScreen.x * 2;
  20268. var vecY = -this.positionScreen.y * 2;
  20269. for( f = 0; f < fl; f ++ ) {
  20270. flare = this.lensFlares[ f ];
  20271. flare.x = this.positionScreen.x + vecX * flare.distance;
  20272. flare.y = this.positionScreen.y + vecY * flare.distance;
  20273. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20274. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20275. }
  20276. };
  20277. /**
  20278. * @author alteredq / http://alteredqualia.com/
  20279. */
  20280. THREE.MorphBlendMesh = function( geometry, material ) {
  20281. THREE.Mesh.call( this, geometry, material );
  20282. this.animationsMap = {};
  20283. this.animationsList = [];
  20284. // prepare default animation
  20285. // (all frames played together in 1 second)
  20286. var numFrames = this.geometry.morphTargets.length;
  20287. var name = "__default";
  20288. var startFrame = 0;
  20289. var endFrame = numFrames - 1;
  20290. var fps = numFrames / 1;
  20291. this.createAnimation( name, startFrame, endFrame, fps );
  20292. this.setAnimationWeight( name, 1 );
  20293. };
  20294. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  20295. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20296. var animation = {
  20297. startFrame: start,
  20298. endFrame: end,
  20299. length: end - start + 1,
  20300. fps: fps,
  20301. duration: ( end - start ) / fps,
  20302. lastFrame: 0,
  20303. currentFrame: 0,
  20304. active: false,
  20305. time: 0,
  20306. direction: 1,
  20307. weight: 1,
  20308. directionBackwards: false,
  20309. mirroredLoop: false
  20310. };
  20311. this.animationsMap[ name ] = animation;
  20312. this.animationsList.push( animation );
  20313. };
  20314. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20315. var pattern = /([a-z]+)(\d+)/;
  20316. var firstAnimation, frameRanges = {};
  20317. var geometry = this.geometry;
  20318. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20319. var morph = geometry.morphTargets[ i ];
  20320. var chunks = morph.name.match( pattern );
  20321. if ( chunks && chunks.length > 1 ) {
  20322. var name = chunks[ 1 ];
  20323. var num = chunks[ 2 ];
  20324. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20325. var range = frameRanges[ name ];
  20326. if ( i < range.start ) range.start = i;
  20327. if ( i > range.end ) range.end = i;
  20328. if ( ! firstAnimation ) firstAnimation = name;
  20329. }
  20330. }
  20331. for ( var name in frameRanges ) {
  20332. var range = frameRanges[ name ];
  20333. this.createAnimation( name, range.start, range.end, fps );
  20334. }
  20335. this.firstAnimation = firstAnimation;
  20336. };
  20337. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20338. var animation = this.animationsMap[ name ];
  20339. if ( animation ) {
  20340. animation.direction = 1;
  20341. animation.directionBackwards = false;
  20342. }
  20343. };
  20344. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20345. var animation = this.animationsMap[ name ];
  20346. if ( animation ) {
  20347. animation.direction = -1;
  20348. animation.directionBackwards = true;
  20349. }
  20350. };
  20351. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20352. var animation = this.animationsMap[ name ];
  20353. if ( animation ) {
  20354. animation.fps = fps;
  20355. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20356. }
  20357. };
  20358. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20359. var animation = this.animationsMap[ name ];
  20360. if ( animation ) {
  20361. animation.duration = duration;
  20362. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20363. }
  20364. };
  20365. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20366. var animation = this.animationsMap[ name ];
  20367. if ( animation ) {
  20368. animation.weight = weight;
  20369. }
  20370. };
  20371. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20372. var animation = this.animationsMap[ name ];
  20373. if ( animation ) {
  20374. animation.time = time;
  20375. }
  20376. };
  20377. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20378. var time = 0;
  20379. var animation = this.animationsMap[ name ];
  20380. if ( animation ) {
  20381. time = animation.time;
  20382. }
  20383. return time;
  20384. };
  20385. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20386. var duration = -1;
  20387. var animation = this.animationsMap[ name ];
  20388. if ( animation ) {
  20389. duration = animation.duration;
  20390. }
  20391. return duration;
  20392. };
  20393. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20394. var animation = this.animationsMap[ name ];
  20395. if ( animation ) {
  20396. animation.time = 0;
  20397. animation.active = true;
  20398. } else {
  20399. console.warn( "animation[" + name + "] undefined" );
  20400. }
  20401. };
  20402. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20403. var animation = this.animationsMap[ name ];
  20404. if ( animation ) {
  20405. animation.active = false;
  20406. }
  20407. };
  20408. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20409. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20410. var animation = this.animationsList[ i ];
  20411. if ( ! animation.active ) continue;
  20412. var frameTime = animation.duration / animation.length;
  20413. animation.time += animation.direction * delta;
  20414. if ( animation.mirroredLoop ) {
  20415. if ( animation.time > animation.duration || animation.time < 0 ) {
  20416. animation.direction *= -1;
  20417. if ( animation.time > animation.duration ) {
  20418. animation.time = animation.duration;
  20419. animation.directionBackwards = true;
  20420. }
  20421. if ( animation.time < 0 ) {
  20422. animation.time = 0;
  20423. animation.directionBackwards = false;
  20424. }
  20425. }
  20426. } else {
  20427. animation.time = animation.time % animation.duration;
  20428. if ( animation.time < 0 ) animation.time += animation.duration;
  20429. }
  20430. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20431. var weight = animation.weight;
  20432. if ( keyframe !== animation.currentFrame ) {
  20433. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20434. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20435. this.morphTargetInfluences[ keyframe ] = 0;
  20436. animation.lastFrame = animation.currentFrame;
  20437. animation.currentFrame = keyframe;
  20438. }
  20439. var mix = ( animation.time % frameTime ) / frameTime;
  20440. if ( animation.directionBackwards ) mix = 1 - mix;
  20441. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20442. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20443. }
  20444. };
  20445. /**
  20446. * @author mikael emtinger / http://gomo.se/
  20447. * @author alteredq / http://alteredqualia.com/
  20448. */
  20449. THREE.LensFlarePlugin = function ( ) {
  20450. var _gl, _renderer, _lensFlare = {};
  20451. this.init = function ( renderer ) {
  20452. _gl = renderer.context;
  20453. _renderer = renderer;
  20454. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20455. _lensFlare.faces = new Uint16Array( 6 );
  20456. var i = 0;
  20457. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20458. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20459. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20460. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20461. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20462. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20463. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20464. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20465. i = 0;
  20466. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20467. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20468. // buffers
  20469. _lensFlare.vertexBuffer = _gl.createBuffer();
  20470. _lensFlare.elementBuffer = _gl.createBuffer();
  20471. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20472. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20473. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20474. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20475. // textures
  20476. _lensFlare.tempTexture = _gl.createTexture();
  20477. _lensFlare.occlusionTexture = _gl.createTexture();
  20478. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20479. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20480. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20481. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20482. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20483. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20484. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20485. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20486. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20487. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20488. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20489. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20490. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20491. _lensFlare.hasVertexTexture = false;
  20492. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20493. } else {
  20494. _lensFlare.hasVertexTexture = true;
  20495. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20496. }
  20497. _lensFlare.attributes = {};
  20498. _lensFlare.uniforms = {};
  20499. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20500. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20501. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20502. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20503. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20504. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20505. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20506. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20507. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20508. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20509. };
  20510. /*
  20511. * Render lens flares
  20512. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20513. * reads these back and calculates occlusion.
  20514. * Then _lensFlare.update_lensFlares() is called to re-position and
  20515. * update transparency of flares. Then they are rendered.
  20516. *
  20517. */
  20518. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20519. var flares = scene.__webglFlares,
  20520. nFlares = flares.length;
  20521. if ( ! nFlares ) return;
  20522. var tempPosition = new THREE.Vector3();
  20523. var invAspect = viewportHeight / viewportWidth,
  20524. halfViewportWidth = viewportWidth * 0.5,
  20525. halfViewportHeight = viewportHeight * 0.5;
  20526. var size = 16 / viewportHeight,
  20527. scale = new THREE.Vector2( size * invAspect, size );
  20528. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20529. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20530. var uniforms = _lensFlare.uniforms,
  20531. attributes = _lensFlare.attributes;
  20532. // set _lensFlare program and reset blending
  20533. _gl.useProgram( _lensFlare.program );
  20534. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20535. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20536. // loop through all lens flares to update their occlusion and positions
  20537. // setup gl and common used attribs/unforms
  20538. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20539. _gl.uniform1i( uniforms.map, 1 );
  20540. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20541. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20542. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20543. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20544. _gl.disable( _gl.CULL_FACE );
  20545. _gl.depthMask( false );
  20546. var i, j, jl, flare, sprite;
  20547. for ( i = 0; i < nFlares; i ++ ) {
  20548. size = 16 / viewportHeight;
  20549. scale.set( size * invAspect, size );
  20550. // calc object screen position
  20551. flare = flares[ i ];
  20552. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20553. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20554. camera.projectionMatrix.multiplyVector3( tempPosition );
  20555. // setup arrays for gl programs
  20556. screenPosition.copy( tempPosition )
  20557. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20558. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20559. // screen cull
  20560. if ( _lensFlare.hasVertexTexture || (
  20561. screenPositionPixels.x > 0 &&
  20562. screenPositionPixels.x < viewportWidth &&
  20563. screenPositionPixels.y > 0 &&
  20564. screenPositionPixels.y < viewportHeight ) ) {
  20565. // save current RGB to temp texture
  20566. _gl.activeTexture( _gl.TEXTURE1 );
  20567. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20568. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20569. // render pink quad
  20570. _gl.uniform1i( uniforms.renderType, 0 );
  20571. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20572. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20573. _gl.disable( _gl.BLEND );
  20574. _gl.enable( _gl.DEPTH_TEST );
  20575. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20576. // copy result to occlusionMap
  20577. _gl.activeTexture( _gl.TEXTURE0 );
  20578. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20579. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20580. // restore graphics
  20581. _gl.uniform1i( uniforms.renderType, 1 );
  20582. _gl.disable( _gl.DEPTH_TEST );
  20583. _gl.activeTexture( _gl.TEXTURE1 );
  20584. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20585. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20586. // update object positions
  20587. flare.positionScreen.copy( screenPosition )
  20588. if ( flare.customUpdateCallback ) {
  20589. flare.customUpdateCallback( flare );
  20590. } else {
  20591. flare.updateLensFlares();
  20592. }
  20593. // render flares
  20594. _gl.uniform1i( uniforms.renderType, 2 );
  20595. _gl.enable( _gl.BLEND );
  20596. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20597. sprite = flare.lensFlares[ j ];
  20598. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20599. screenPosition.x = sprite.x;
  20600. screenPosition.y = sprite.y;
  20601. screenPosition.z = sprite.z;
  20602. size = sprite.size * sprite.scale / viewportHeight;
  20603. scale.x = size * invAspect;
  20604. scale.y = size;
  20605. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20606. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20607. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20608. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20609. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20610. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20611. _renderer.setTexture( sprite.texture, 1 );
  20612. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20613. }
  20614. }
  20615. }
  20616. }
  20617. // restore gl
  20618. _gl.enable( _gl.CULL_FACE );
  20619. _gl.enable( _gl.DEPTH_TEST );
  20620. _gl.depthMask( true );
  20621. };
  20622. function createProgram ( shader ) {
  20623. var program = _gl.createProgram();
  20624. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20625. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20626. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20627. _gl.shaderSource( vertexShader, shader.vertexShader );
  20628. _gl.compileShader( fragmentShader );
  20629. _gl.compileShader( vertexShader );
  20630. _gl.attachShader( program, fragmentShader );
  20631. _gl.attachShader( program, vertexShader );
  20632. _gl.linkProgram( program );
  20633. return program;
  20634. };
  20635. };/**
  20636. * @author alteredq / http://alteredqualia.com/
  20637. */
  20638. THREE.ShadowMapPlugin = function ( ) {
  20639. var _gl,
  20640. _renderer,
  20641. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20642. _frustum = new THREE.Frustum(),
  20643. _projScreenMatrix = new THREE.Matrix4(),
  20644. _min = new THREE.Vector3(),
  20645. _max = new THREE.Vector3();
  20646. this.init = function ( renderer ) {
  20647. _gl = renderer.context;
  20648. _renderer = renderer;
  20649. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20650. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20651. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20652. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20653. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20654. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20655. _depthMaterial._shadowPass = true;
  20656. _depthMaterialMorph._shadowPass = true;
  20657. _depthMaterialSkin._shadowPass = true;
  20658. _depthMaterialMorphSkin._shadowPass = true;
  20659. };
  20660. this.render = function ( scene, camera ) {
  20661. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20662. this.update( scene, camera );
  20663. };
  20664. this.update = function ( scene, camera ) {
  20665. var i, il, j, jl, n,
  20666. shadowMap, shadowMatrix, shadowCamera,
  20667. program, buffer, material,
  20668. webglObject, object, light,
  20669. renderList,
  20670. lights = [],
  20671. k = 0,
  20672. fog = null;
  20673. // set GL state for depth map
  20674. _gl.clearColor( 1, 1, 1, 1 );
  20675. _gl.disable( _gl.BLEND );
  20676. _gl.enable( _gl.CULL_FACE );
  20677. _gl.frontFace( _gl.CCW );
  20678. if ( _renderer.shadowMapCullFrontFaces ) {
  20679. _gl.cullFace( _gl.FRONT );
  20680. } else {
  20681. _gl.cullFace( _gl.BACK );
  20682. }
  20683. _renderer.setDepthTest( true );
  20684. // preprocess lights
  20685. // - skip lights that are not casting shadows
  20686. // - create virtual lights for cascaded shadow maps
  20687. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20688. light = scene.__lights[ i ];
  20689. if ( ! light.castShadow ) continue;
  20690. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20691. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20692. var virtualLight;
  20693. if ( ! light.shadowCascadeArray[ n ] ) {
  20694. virtualLight = createVirtualLight( light, n );
  20695. virtualLight.originalCamera = camera;
  20696. var gyro = new THREE.Gyroscope();
  20697. gyro.position = light.shadowCascadeOffset;
  20698. gyro.add( virtualLight );
  20699. gyro.add( virtualLight.target );
  20700. camera.add( gyro );
  20701. light.shadowCascadeArray[ n ] = virtualLight;
  20702. console.log( "Created virtualLight", virtualLight );
  20703. } else {
  20704. virtualLight = light.shadowCascadeArray[ n ];
  20705. }
  20706. updateVirtualLight( light, n );
  20707. lights[ k ] = virtualLight;
  20708. k ++;
  20709. }
  20710. } else {
  20711. lights[ k ] = light;
  20712. k ++;
  20713. }
  20714. }
  20715. // render depth map
  20716. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20717. light = lights[ i ];
  20718. if ( ! light.shadowMap ) {
  20719. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20720. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20721. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20722. light.shadowMatrix = new THREE.Matrix4();
  20723. }
  20724. if ( ! light.shadowCamera ) {
  20725. if ( light instanceof THREE.SpotLight ) {
  20726. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20727. } else if ( light instanceof THREE.DirectionalLight ) {
  20728. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20729. } else {
  20730. console.error( "Unsupported light type for shadow" );
  20731. continue;
  20732. }
  20733. scene.add( light.shadowCamera );
  20734. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20735. }
  20736. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20737. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20738. light.shadowCamera.add( light.cameraHelper );
  20739. }
  20740. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20741. updateShadowCamera( camera, light );
  20742. }
  20743. shadowMap = light.shadowMap;
  20744. shadowMatrix = light.shadowMatrix;
  20745. shadowCamera = light.shadowCamera;
  20746. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20747. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20748. shadowCamera.updateMatrixWorld();
  20749. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20750. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20751. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20752. // compute shadow matrix
  20753. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20754. 0.0, 0.5, 0.0, 0.5,
  20755. 0.0, 0.0, 0.5, 0.5,
  20756. 0.0, 0.0, 0.0, 1.0 );
  20757. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20758. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20759. // update camera matrices and frustum
  20760. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20761. _frustum.setFromMatrix( _projScreenMatrix );
  20762. // render shadow map
  20763. _renderer.setRenderTarget( shadowMap );
  20764. _renderer.clear();
  20765. // set object matrices & frustum culling
  20766. renderList = scene.__webglObjects;
  20767. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20768. webglObject = renderList[ j ];
  20769. object = webglObject.object;
  20770. webglObject.render = false;
  20771. if ( object.visible && object.castShadow ) {
  20772. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20773. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20774. webglObject.render = true;
  20775. }
  20776. }
  20777. }
  20778. // render regular objects
  20779. var objectMaterial, useMorphing, useSkinning;
  20780. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20781. webglObject = renderList[ j ];
  20782. if ( webglObject.render ) {
  20783. object = webglObject.object;
  20784. buffer = webglObject.buffer;
  20785. // culling is overriden globally for all objects
  20786. // while rendering depth map
  20787. // need to deal with MeshFaceMaterial somehow
  20788. // in that case just use the first of material.materials for now
  20789. // (proper solution would require to break objects by materials
  20790. // similarly to regular rendering and then set corresponding
  20791. // depth materials per each chunk instead of just once per object)
  20792. objectMaterial = getObjectMaterial( object );
  20793. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20794. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20795. if ( object.customDepthMaterial ) {
  20796. material = object.customDepthMaterial;
  20797. } else if ( useSkinning ) {
  20798. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20799. } else if ( useMorphing ) {
  20800. material = _depthMaterialMorph;
  20801. } else {
  20802. material = _depthMaterial;
  20803. }
  20804. if ( buffer instanceof THREE.BufferGeometry ) {
  20805. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20806. } else {
  20807. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20808. }
  20809. }
  20810. }
  20811. // set matrices and render immediate objects
  20812. renderList = scene.__webglObjectsImmediate;
  20813. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20814. webglObject = renderList[ j ];
  20815. object = webglObject.object;
  20816. if ( object.visible && object.castShadow ) {
  20817. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20818. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20819. }
  20820. }
  20821. }
  20822. // restore GL state
  20823. var clearColor = _renderer.getClearColor(),
  20824. clearAlpha = _renderer.getClearAlpha();
  20825. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20826. _gl.enable( _gl.BLEND );
  20827. if ( _renderer.shadowMapCullFrontFaces ) {
  20828. _gl.cullFace( _gl.BACK );
  20829. }
  20830. };
  20831. function createVirtualLight( light, cascade ) {
  20832. var virtualLight = new THREE.DirectionalLight();
  20833. virtualLight.isVirtual = true;
  20834. virtualLight.onlyShadow = true;
  20835. virtualLight.castShadow = true;
  20836. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20837. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20838. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20839. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20840. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20841. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20842. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20843. virtualLight.shadowDarkness = light.shadowDarkness;
  20844. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20845. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20846. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20847. virtualLight.pointsWorld = [];
  20848. virtualLight.pointsFrustum = [];
  20849. var pointsWorld = virtualLight.pointsWorld,
  20850. pointsFrustum = virtualLight.pointsFrustum;
  20851. for ( var i = 0; i < 8; i ++ ) {
  20852. pointsWorld[ i ] = new THREE.Vector3();
  20853. pointsFrustum[ i ] = new THREE.Vector3();
  20854. }
  20855. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20856. var farZ = light.shadowCascadeFarZ[ cascade ];
  20857. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20858. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20859. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20860. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20861. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20862. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20863. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20864. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20865. return virtualLight;
  20866. }
  20867. // Synchronize virtual light with the original light
  20868. function updateVirtualLight( light, cascade ) {
  20869. var virtualLight = light.shadowCascadeArray[ cascade ];
  20870. virtualLight.position.copy( light.position );
  20871. virtualLight.target.position.copy( light.target.position );
  20872. virtualLight.lookAt( virtualLight.target );
  20873. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20874. virtualLight.shadowDarkness = light.shadowDarkness;
  20875. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20876. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20877. var farZ = light.shadowCascadeFarZ[ cascade ];
  20878. var pointsFrustum = virtualLight.pointsFrustum;
  20879. pointsFrustum[ 0 ].z = nearZ;
  20880. pointsFrustum[ 1 ].z = nearZ;
  20881. pointsFrustum[ 2 ].z = nearZ;
  20882. pointsFrustum[ 3 ].z = nearZ;
  20883. pointsFrustum[ 4 ].z = farZ;
  20884. pointsFrustum[ 5 ].z = farZ;
  20885. pointsFrustum[ 6 ].z = farZ;
  20886. pointsFrustum[ 7 ].z = farZ;
  20887. }
  20888. // Fit shadow camera's ortho frustum to camera frustum
  20889. function updateShadowCamera( camera, light ) {
  20890. var shadowCamera = light.shadowCamera,
  20891. pointsFrustum = light.pointsFrustum,
  20892. pointsWorld = light.pointsWorld;
  20893. _min.set( Infinity, Infinity, Infinity );
  20894. _max.set( -Infinity, -Infinity, -Infinity );
  20895. for ( var i = 0; i < 8; i ++ ) {
  20896. var p = pointsWorld[ i ];
  20897. p.copy( pointsFrustum[ i ] );
  20898. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20899. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  20900. if ( p.x < _min.x ) _min.x = p.x;
  20901. if ( p.x > _max.x ) _max.x = p.x;
  20902. if ( p.y < _min.y ) _min.y = p.y;
  20903. if ( p.y > _max.y ) _max.y = p.y;
  20904. if ( p.z < _min.z ) _min.z = p.z;
  20905. if ( p.z > _max.z ) _max.z = p.z;
  20906. }
  20907. shadowCamera.left = _min.x;
  20908. shadowCamera.right = _max.x;
  20909. shadowCamera.top = _max.y;
  20910. shadowCamera.bottom = _min.y;
  20911. // can't really fit near/far
  20912. //shadowCamera.near = _min.z;
  20913. //shadowCamera.far = _max.z;
  20914. shadowCamera.updateProjectionMatrix();
  20915. }
  20916. // For the moment just ignore objects that have multiple materials with different animation methods
  20917. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  20918. function getObjectMaterial( object ) {
  20919. return object.material instanceof THREE.MeshFaceMaterial
  20920. ? object.material.materials[ 0 ]
  20921. : object.material;
  20922. };
  20923. };
  20924. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20925. /**
  20926. * @author mikael emtinger / http://gomo.se/
  20927. * @author alteredq / http://alteredqualia.com/
  20928. */
  20929. THREE.SpritePlugin = function ( ) {
  20930. var _gl, _renderer, _sprite = {};
  20931. this.init = function ( renderer ) {
  20932. _gl = renderer.context;
  20933. _renderer = renderer;
  20934. _sprite.vertices = new Float32Array( 8 + 8 );
  20935. _sprite.faces = new Uint16Array( 6 );
  20936. var i = 0;
  20937. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20938. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20939. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20940. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20941. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20942. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20943. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20944. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20945. i = 0;
  20946. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  20947. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  20948. _sprite.vertexBuffer = _gl.createBuffer();
  20949. _sprite.elementBuffer = _gl.createBuffer();
  20950. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20951. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  20952. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20953. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  20954. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  20955. _sprite.attributes = {};
  20956. _sprite.uniforms = {};
  20957. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  20958. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  20959. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  20960. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  20961. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  20962. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  20963. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  20964. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  20965. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  20966. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  20967. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  20968. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  20969. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  20970. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  20971. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  20972. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  20973. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  20974. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  20975. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  20976. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  20977. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  20978. };
  20979. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20980. var sprites = scene.__webglSprites,
  20981. nSprites = sprites.length;
  20982. if ( ! nSprites ) return;
  20983. var attributes = _sprite.attributes,
  20984. uniforms = _sprite.uniforms;
  20985. var invAspect = viewportHeight / viewportWidth;
  20986. var halfViewportWidth = viewportWidth * 0.5,
  20987. halfViewportHeight = viewportHeight * 0.5;
  20988. // setup gl
  20989. _gl.useProgram( _sprite.program );
  20990. _gl.enableVertexAttribArray( attributes.position );
  20991. _gl.enableVertexAttribArray( attributes.uv );
  20992. _gl.disable( _gl.CULL_FACE );
  20993. _gl.enable( _gl.BLEND );
  20994. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20995. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20996. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20997. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20998. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  20999. _gl.activeTexture( _gl.TEXTURE0 );
  21000. _gl.uniform1i( uniforms.map, 0 );
  21001. var oldFogType = 0;
  21002. var sceneFogType = 0;
  21003. var fog = scene.fog;
  21004. if ( fog ) {
  21005. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21006. if ( fog instanceof THREE.Fog ) {
  21007. _gl.uniform1f( uniforms.fogNear, fog.near );
  21008. _gl.uniform1f( uniforms.fogFar, fog.far );
  21009. _gl.uniform1i( uniforms.fogType, 1 );
  21010. oldFogType = 1;
  21011. sceneFogType = 1;
  21012. } else if ( fog instanceof THREE.FogExp2 ) {
  21013. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21014. _gl.uniform1i( uniforms.fogType, 2 );
  21015. oldFogType = 2;
  21016. sceneFogType = 2;
  21017. }
  21018. } else {
  21019. _gl.uniform1i( uniforms.fogType, 0 );
  21020. oldFogType = 0;
  21021. sceneFogType = 0;
  21022. }
  21023. // update positions and sort
  21024. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21025. for( i = 0; i < nSprites; i ++ ) {
  21026. sprite = sprites[ i ];
  21027. material = sprite.material;
  21028. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21029. if ( ! material.useScreenCoordinates ) {
  21030. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21031. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21032. } else {
  21033. sprite.z = - sprite.position.z;
  21034. }
  21035. }
  21036. sprites.sort( painterSortStable );
  21037. // render all sprites
  21038. for( i = 0; i < nSprites; i ++ ) {
  21039. sprite = sprites[ i ];
  21040. material = sprite.material;
  21041. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21042. if ( material.map && material.map.image && material.map.image.width ) {
  21043. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21044. if ( material.useScreenCoordinates ) {
  21045. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21046. _gl.uniform3f(
  21047. uniforms.screenPosition,
  21048. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21049. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21050. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21051. );
  21052. } else {
  21053. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21054. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21055. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21056. }
  21057. if ( scene.fog && material.fog ) {
  21058. fogType = sceneFogType;
  21059. } else {
  21060. fogType = 0;
  21061. }
  21062. if ( oldFogType !== fogType ) {
  21063. _gl.uniform1i( uniforms.fogType, fogType );
  21064. oldFogType = fogType;
  21065. }
  21066. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21067. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21068. scale[ 1 ] = size * sprite.scale.y;
  21069. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21070. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21071. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21072. _gl.uniform1f( uniforms.opacity, material.opacity );
  21073. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21074. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21075. _gl.uniform2fv( uniforms.scale, scale );
  21076. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21077. _renderer.setDepthTest( material.depthTest );
  21078. _renderer.setDepthWrite( material.depthWrite );
  21079. _renderer.setTexture( material.map, 0 );
  21080. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21081. }
  21082. }
  21083. // restore gl
  21084. _gl.enable( _gl.CULL_FACE );
  21085. };
  21086. function createProgram ( shader ) {
  21087. var program = _gl.createProgram();
  21088. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21089. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21090. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21091. _gl.shaderSource( vertexShader, shader.vertexShader );
  21092. _gl.compileShader( fragmentShader );
  21093. _gl.compileShader( vertexShader );
  21094. _gl.attachShader( program, fragmentShader );
  21095. _gl.attachShader( program, vertexShader );
  21096. _gl.linkProgram( program );
  21097. return program;
  21098. };
  21099. function painterSortStable ( a, b ) {
  21100. if ( a.z !== b.z ) {
  21101. return b.z - a.z;
  21102. } else {
  21103. return b.id - a.id;
  21104. }
  21105. };
  21106. };/**
  21107. * @author alteredq / http://alteredqualia.com/
  21108. */
  21109. THREE.DepthPassPlugin = function ( ) {
  21110. this.enabled = false;
  21111. this.renderTarget = null;
  21112. var _gl,
  21113. _renderer,
  21114. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21115. _frustum = new THREE.Frustum(),
  21116. _projScreenMatrix = new THREE.Matrix4();
  21117. this.init = function ( renderer ) {
  21118. _gl = renderer.context;
  21119. _renderer = renderer;
  21120. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21121. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21122. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21123. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21124. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21125. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21126. _depthMaterial._shadowPass = true;
  21127. _depthMaterialMorph._shadowPass = true;
  21128. _depthMaterialSkin._shadowPass = true;
  21129. _depthMaterialMorphSkin._shadowPass = true;
  21130. };
  21131. this.render = function ( scene, camera ) {
  21132. if ( ! this.enabled ) return;
  21133. this.update( scene, camera );
  21134. };
  21135. this.update = function ( scene, camera ) {
  21136. var i, il, j, jl, n,
  21137. program, buffer, material,
  21138. webglObject, object, light,
  21139. renderList,
  21140. fog = null;
  21141. // set GL state for depth map
  21142. _gl.clearColor( 1, 1, 1, 1 );
  21143. _gl.disable( _gl.BLEND );
  21144. _renderer.setDepthTest( true );
  21145. // update scene
  21146. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21147. // update camera matrices and frustum
  21148. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21149. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21150. _frustum.setFromMatrix( _projScreenMatrix );
  21151. // render depth map
  21152. _renderer.setRenderTarget( this.renderTarget );
  21153. _renderer.clear();
  21154. // set object matrices & frustum culling
  21155. renderList = scene.__webglObjects;
  21156. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21157. webglObject = renderList[ j ];
  21158. object = webglObject.object;
  21159. webglObject.render = false;
  21160. if ( object.visible ) {
  21161. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21162. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21163. webglObject.render = true;
  21164. }
  21165. }
  21166. }
  21167. // render regular objects
  21168. var objectMaterial, useMorphing, useSkinning;
  21169. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21170. webglObject = renderList[ j ];
  21171. if ( webglObject.render ) {
  21172. object = webglObject.object;
  21173. buffer = webglObject.buffer;
  21174. // todo: create proper depth material for particles
  21175. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21176. objectMaterial = getObjectMaterial( object );
  21177. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21178. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21179. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21180. if ( object.customDepthMaterial ) {
  21181. material = object.customDepthMaterial;
  21182. } else if ( useSkinning ) {
  21183. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21184. } else if ( useMorphing ) {
  21185. material = _depthMaterialMorph;
  21186. } else {
  21187. material = _depthMaterial;
  21188. }
  21189. if ( buffer instanceof THREE.BufferGeometry ) {
  21190. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21191. } else {
  21192. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21193. }
  21194. }
  21195. }
  21196. // set matrices and render immediate objects
  21197. renderList = scene.__webglObjectsImmediate;
  21198. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21199. webglObject = renderList[ j ];
  21200. object = webglObject.object;
  21201. if ( object.visible ) {
  21202. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21203. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21204. }
  21205. }
  21206. // restore GL state
  21207. var clearColor = _renderer.getClearColor(),
  21208. clearAlpha = _renderer.getClearAlpha();
  21209. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21210. _gl.enable( _gl.BLEND );
  21211. };
  21212. // For the moment just ignore objects that have multiple materials with different animation methods
  21213. // Only the first material will be taken into account for deciding which depth material to use
  21214. function getObjectMaterial( object ) {
  21215. return object.material instanceof THREE.MeshFaceMaterial
  21216. ? object.material.materials[ 0 ]
  21217. : object.material;
  21218. };
  21219. };
  21220. /**
  21221. * @author mikael emtinger / http://gomo.se/
  21222. *
  21223. */
  21224. THREE.ShaderFlares = {
  21225. 'lensFlareVertexTexture': {
  21226. vertexShader: [
  21227. "uniform vec3 screenPosition;",
  21228. "uniform vec2 scale;",
  21229. "uniform float rotation;",
  21230. "uniform int renderType;",
  21231. "uniform sampler2D occlusionMap;",
  21232. "attribute vec2 position;",
  21233. "attribute vec2 uv;",
  21234. "varying vec2 vUV;",
  21235. "varying float vVisibility;",
  21236. "void main() {",
  21237. "vUV = uv;",
  21238. "vec2 pos = position;",
  21239. "if( renderType == 2 ) {",
  21240. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21241. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21242. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21243. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21244. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21245. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21246. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21247. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21248. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21249. "vVisibility = ( visibility.r / 9.0 ) *",
  21250. "( 1.0 - visibility.g / 9.0 ) *",
  21251. "( visibility.b / 9.0 ) *",
  21252. "( 1.0 - visibility.a / 9.0 );",
  21253. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21254. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21255. "}",
  21256. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21257. "}"
  21258. ].join( "\n" ),
  21259. fragmentShader: [
  21260. "precision mediump float;",
  21261. "uniform sampler2D map;",
  21262. "uniform float opacity;",
  21263. "uniform int renderType;",
  21264. "uniform vec3 color;",
  21265. "varying vec2 vUV;",
  21266. "varying float vVisibility;",
  21267. "void main() {",
  21268. // pink square
  21269. "if( renderType == 0 ) {",
  21270. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21271. // restore
  21272. "} else if( renderType == 1 ) {",
  21273. "gl_FragColor = texture2D( map, vUV );",
  21274. // flare
  21275. "} else {",
  21276. "vec4 texture = texture2D( map, vUV );",
  21277. "texture.a *= opacity * vVisibility;",
  21278. "gl_FragColor = texture;",
  21279. "gl_FragColor.rgb *= color;",
  21280. "}",
  21281. "}"
  21282. ].join( "\n" )
  21283. },
  21284. 'lensFlare': {
  21285. vertexShader: [
  21286. "uniform vec3 screenPosition;",
  21287. "uniform vec2 scale;",
  21288. "uniform float rotation;",
  21289. "uniform int renderType;",
  21290. "attribute vec2 position;",
  21291. "attribute vec2 uv;",
  21292. "varying vec2 vUV;",
  21293. "void main() {",
  21294. "vUV = uv;",
  21295. "vec2 pos = position;",
  21296. "if( renderType == 2 ) {",
  21297. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21298. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21299. "}",
  21300. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21301. "}"
  21302. ].join( "\n" ),
  21303. fragmentShader: [
  21304. "precision mediump float;",
  21305. "uniform sampler2D map;",
  21306. "uniform sampler2D occlusionMap;",
  21307. "uniform float opacity;",
  21308. "uniform int renderType;",
  21309. "uniform vec3 color;",
  21310. "varying vec2 vUV;",
  21311. "void main() {",
  21312. // pink square
  21313. "if( renderType == 0 ) {",
  21314. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21315. // restore
  21316. "} else if( renderType == 1 ) {",
  21317. "gl_FragColor = texture2D( map, vUV );",
  21318. // flare
  21319. "} else {",
  21320. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21321. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21322. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21323. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21324. "visibility = ( 1.0 - visibility / 4.0 );",
  21325. "vec4 texture = texture2D( map, vUV );",
  21326. "texture.a *= opacity * visibility;",
  21327. "gl_FragColor = texture;",
  21328. "gl_FragColor.rgb *= color;",
  21329. "}",
  21330. "}"
  21331. ].join( "\n" )
  21332. }
  21333. };
  21334. /**
  21335. * @author mikael emtinger / http://gomo.se/
  21336. * @author alteredq / http://alteredqualia.com/
  21337. *
  21338. */
  21339. THREE.ShaderSprite = {
  21340. 'sprite': {
  21341. vertexShader: [
  21342. "uniform int useScreenCoordinates;",
  21343. "uniform int sizeAttenuation;",
  21344. "uniform vec3 screenPosition;",
  21345. "uniform mat4 modelViewMatrix;",
  21346. "uniform mat4 projectionMatrix;",
  21347. "uniform float rotation;",
  21348. "uniform vec2 scale;",
  21349. "uniform vec2 alignment;",
  21350. "uniform vec2 uvOffset;",
  21351. "uniform vec2 uvScale;",
  21352. "attribute vec2 position;",
  21353. "attribute vec2 uv;",
  21354. "varying vec2 vUV;",
  21355. "void main() {",
  21356. "vUV = uvOffset + uv * uvScale;",
  21357. "vec2 alignedPosition = position + alignment;",
  21358. "vec2 rotatedPosition;",
  21359. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21360. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21361. "vec4 finalPosition;",
  21362. "if( useScreenCoordinates != 0 ) {",
  21363. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21364. "} else {",
  21365. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21366. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  21367. "}",
  21368. "gl_Position = finalPosition;",
  21369. "}"
  21370. ].join( "\n" ),
  21371. fragmentShader: [
  21372. "precision mediump float;",
  21373. "uniform vec3 color;",
  21374. "uniform sampler2D map;",
  21375. "uniform float opacity;",
  21376. "uniform int fogType;",
  21377. "uniform vec3 fogColor;",
  21378. "uniform float fogDensity;",
  21379. "uniform float fogNear;",
  21380. "uniform float fogFar;",
  21381. "uniform float alphaTest;",
  21382. "varying vec2 vUV;",
  21383. "void main() {",
  21384. "vec4 texture = texture2D( map, vUV );",
  21385. "if ( texture.a < alphaTest ) discard;",
  21386. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21387. "if ( fogType > 0 ) {",
  21388. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  21389. "float fogFactor = 0.0;",
  21390. "if ( fogType == 1 ) {",
  21391. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  21392. "} else {",
  21393. "const float LOG2 = 1.442695;",
  21394. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  21395. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  21396. "}",
  21397. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  21398. "}",
  21399. "}"
  21400. ].join( "\n" )
  21401. }
  21402. };