three.js 799 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '53dev' };
  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. // Mapping modes
  101. THREE.UVMapping = function () {};
  102. THREE.CubeReflectionMapping = function () {};
  103. THREE.CubeRefractionMapping = function () {};
  104. THREE.SphericalReflectionMapping = function () {};
  105. THREE.SphericalRefractionMapping = function () {};
  106. // Wrapping modes
  107. THREE.RepeatWrapping = 1000;
  108. THREE.ClampToEdgeWrapping = 1001;
  109. THREE.MirroredRepeatWrapping = 1002;
  110. // Filters
  111. THREE.NearestFilter = 1003;
  112. THREE.NearestMipMapNearestFilter = 1004;
  113. THREE.NearestMipMapLinearFilter = 1005;
  114. THREE.LinearFilter = 1006;
  115. THREE.LinearMipMapNearestFilter = 1007;
  116. THREE.LinearMipMapLinearFilter = 1008;
  117. // Data types
  118. THREE.UnsignedByteType = 1009;
  119. THREE.ByteType = 1010;
  120. THREE.ShortType = 1011;
  121. THREE.UnsignedShortType = 1012;
  122. THREE.IntType = 1013;
  123. THREE.UnsignedIntType = 1014;
  124. THREE.FloatType = 1015;
  125. // Pixel types
  126. //THREE.UnsignedByteType = 1009;
  127. THREE.UnsignedShort4444Type = 1016;
  128. THREE.UnsignedShort5551Type = 1017;
  129. THREE.UnsignedShort565Type = 1018;
  130. // Pixel formats
  131. THREE.AlphaFormat = 1019;
  132. THREE.RGBFormat = 1020;
  133. THREE.RGBAFormat = 1021;
  134. THREE.LuminanceFormat = 1022;
  135. THREE.LuminanceAlphaFormat = 1023;
  136. // Compressed texture formats
  137. THREE.RGB_S3TC_DXT1_Format = 2001;
  138. THREE.RGBA_S3TC_DXT1_Format = 2002;
  139. THREE.RGBA_S3TC_DXT3_Format = 2003;
  140. THREE.RGBA_S3TC_DXT5_Format = 2004;
  141. /*
  142. // Potential future PVRTC compressed texture formats
  143. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  144. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  145. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  146. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  147. */
  148. /**
  149. * @author alteredq / http://alteredqualia.com/
  150. */
  151. THREE.Clock = function ( autoStart ) {
  152. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  153. this.startTime = 0;
  154. this.oldTime = 0;
  155. this.elapsedTime = 0;
  156. this.running = false;
  157. };
  158. THREE.Clock.prototype.start = function () {
  159. this.startTime = Date.now();
  160. this.oldTime = this.startTime;
  161. this.running = true;
  162. };
  163. THREE.Clock.prototype.stop = function () {
  164. this.getElapsedTime();
  165. this.running = false;
  166. };
  167. THREE.Clock.prototype.getElapsedTime = function () {
  168. this.elapsedTime += this.getDelta();
  169. return this.elapsedTime;
  170. };
  171. THREE.Clock.prototype.getDelta = function () {
  172. var diff = 0;
  173. if ( this.autoStart && ! this.running ) {
  174. this.start();
  175. }
  176. if ( this.running ) {
  177. var newTime = Date.now();
  178. diff = 0.001 * ( newTime - this.oldTime );
  179. this.oldTime = newTime;
  180. this.elapsedTime += diff;
  181. }
  182. return diff;
  183. };/**
  184. * @author mrdoob / http://mrdoob.com/
  185. */
  186. THREE.Color = function ( hex ) {
  187. if ( hex !== undefined ) this.setHex( hex );
  188. return this;
  189. };
  190. THREE.Color.prototype = {
  191. constructor: THREE.Color,
  192. r: 1, g: 1, b: 1,
  193. copy: function ( color ) {
  194. this.r = color.r;
  195. this.g = color.g;
  196. this.b = color.b;
  197. return this;
  198. },
  199. copyGammaToLinear: function ( color ) {
  200. this.r = color.r * color.r;
  201. this.g = color.g * color.g;
  202. this.b = color.b * color.b;
  203. return this;
  204. },
  205. copyLinearToGamma: function ( color ) {
  206. this.r = Math.sqrt( color.r );
  207. this.g = Math.sqrt( color.g );
  208. this.b = Math.sqrt( color.b );
  209. return this;
  210. },
  211. convertGammaToLinear: function () {
  212. var r = this.r, g = this.g, b = this.b;
  213. this.r = r * r;
  214. this.g = g * g;
  215. this.b = b * b;
  216. return this;
  217. },
  218. convertLinearToGamma: function () {
  219. this.r = Math.sqrt( this.r );
  220. this.g = Math.sqrt( this.g );
  221. this.b = Math.sqrt( this.b );
  222. return this;
  223. },
  224. setRGB: function ( r, g, b ) {
  225. this.r = r;
  226. this.g = g;
  227. this.b = b;
  228. return this;
  229. },
  230. setHSV: function ( h, s, v ) {
  231. // based on MochiKit implementation by Bob Ippolito
  232. // h,s,v ranges are < 0.0 - 1.0 >
  233. var i, f, p, q, t;
  234. if ( v === 0 ) {
  235. this.r = this.g = this.b = 0;
  236. } else {
  237. i = Math.floor( h * 6 );
  238. f = ( h * 6 ) - i;
  239. p = v * ( 1 - s );
  240. q = v * ( 1 - ( s * f ) );
  241. t = v * ( 1 - ( s * ( 1 - f ) ) );
  242. if ( i === 0 ) {
  243. this.r = v;
  244. this.g = t;
  245. this.b = p;
  246. } else if ( i === 1 ) {
  247. this.r = q;
  248. this.g = v;
  249. this.b = p;
  250. } else if ( i === 2 ) {
  251. this.r = p;
  252. this.g = v;
  253. this.b = t;
  254. } else if ( i === 3 ) {
  255. this.r = p;
  256. this.g = q;
  257. this.b = v;
  258. } else if ( i === 4 ) {
  259. this.r = t;
  260. this.g = p;
  261. this.b = v;
  262. } else if ( i === 5 ) {
  263. this.r = v;
  264. this.g = p;
  265. this.b = q;
  266. }
  267. }
  268. return this;
  269. },
  270. setHex: function ( hex ) {
  271. hex = Math.floor( hex );
  272. this.r = ( hex >> 16 & 255 ) / 255;
  273. this.g = ( hex >> 8 & 255 ) / 255;
  274. this.b = ( hex & 255 ) / 255;
  275. return this;
  276. },
  277. lerpSelf: function ( color, alpha ) {
  278. this.r += ( color.r - this.r ) * alpha;
  279. this.g += ( color.g - this.g ) * alpha;
  280. this.b += ( color.b - this.b ) * alpha;
  281. return this;
  282. },
  283. getHex: function () {
  284. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  285. },
  286. getContextStyle: function () {
  287. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  288. },
  289. clone: function () {
  290. return new THREE.Color().setRGB( this.r, this.g, this.b );
  291. }
  292. };
  293. /**
  294. * @author mrdoob / http://mrdoob.com/
  295. * @author philogb / http://blog.thejit.org/
  296. * @author egraether / http://egraether.com/
  297. * @author zz85 / http://www.lab4games.net/zz85/blog
  298. */
  299. THREE.Vector2 = function ( x, y ) {
  300. this.x = x || 0;
  301. this.y = y || 0;
  302. };
  303. THREE.Vector2.prototype = {
  304. constructor: THREE.Vector2,
  305. set: function ( x, y ) {
  306. this.x = x;
  307. this.y = y;
  308. return this;
  309. },
  310. copy: function ( v ) {
  311. this.x = v.x;
  312. this.y = v.y;
  313. return this;
  314. },
  315. add: function ( a, b ) {
  316. this.x = a.x + b.x;
  317. this.y = a.y + b.y;
  318. return this;
  319. },
  320. addSelf: function ( v ) {
  321. this.x += v.x;
  322. this.y += v.y;
  323. return this;
  324. },
  325. sub: function ( a, b ) {
  326. this.x = a.x - b.x;
  327. this.y = a.y - b.y;
  328. return this;
  329. },
  330. subSelf: function ( v ) {
  331. this.x -= v.x;
  332. this.y -= v.y;
  333. return this;
  334. },
  335. multiplyScalar: function ( s ) {
  336. this.x *= s;
  337. this.y *= s;
  338. return this;
  339. },
  340. divideScalar: function ( s ) {
  341. if ( s ) {
  342. this.x /= s;
  343. this.y /= s;
  344. } else {
  345. this.set( 0, 0 );
  346. }
  347. return this;
  348. },
  349. negate: function() {
  350. return this.multiplyScalar( - 1 );
  351. },
  352. dot: function ( v ) {
  353. return this.x * v.x + this.y * v.y;
  354. },
  355. lengthSq: function () {
  356. return this.x * this.x + this.y * this.y;
  357. },
  358. length: function () {
  359. return Math.sqrt( this.lengthSq() );
  360. },
  361. normalize: function () {
  362. return this.divideScalar( this.length() );
  363. },
  364. distanceTo: function ( v ) {
  365. return Math.sqrt( this.distanceToSquared( v ) );
  366. },
  367. distanceToSquared: function ( v ) {
  368. var dx = this.x - v.x, dy = this.y - v.y;
  369. return dx * dx + dy * dy;
  370. },
  371. setLength: function ( l ) {
  372. return this.normalize().multiplyScalar( l );
  373. },
  374. lerpSelf: function ( v, alpha ) {
  375. this.x += ( v.x - this.x ) * alpha;
  376. this.y += ( v.y - this.y ) * alpha;
  377. return this;
  378. },
  379. equals: function( v ) {
  380. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  381. },
  382. isZero: function ( v ) {
  383. return this.lengthSq() < ( v !== undefined ? v : 0.0001 );
  384. },
  385. clone: function () {
  386. return new THREE.Vector2( this.x, this.y );
  387. }
  388. };
  389. /**
  390. * @author mrdoob / http://mrdoob.com/
  391. * @author kile / http://kile.stravaganza.org/
  392. * @author philogb / http://blog.thejit.org/
  393. * @author mikael emtinger / http://gomo.se/
  394. * @author egraether / http://egraether.com/
  395. * @author WestLangley / http://github.com/WestLangley
  396. */
  397. THREE.Vector3 = function ( x, y, z ) {
  398. this.x = x || 0;
  399. this.y = y || 0;
  400. this.z = z || 0;
  401. };
  402. THREE.Vector3.prototype = {
  403. constructor: THREE.Vector3,
  404. set: function ( x, y, z ) {
  405. this.x = x;
  406. this.y = y;
  407. this.z = z;
  408. return this;
  409. },
  410. setX: function ( x ) {
  411. this.x = x;
  412. return this;
  413. },
  414. setY: function ( y ) {
  415. this.y = y;
  416. return this;
  417. },
  418. setZ: function ( z ) {
  419. this.z = z;
  420. return this;
  421. },
  422. copy: function ( v ) {
  423. this.x = v.x;
  424. this.y = v.y;
  425. this.z = v.z;
  426. return this;
  427. },
  428. add: function ( a, b ) {
  429. this.x = a.x + b.x;
  430. this.y = a.y + b.y;
  431. this.z = a.z + b.z;
  432. return this;
  433. },
  434. addSelf: function ( v ) {
  435. this.x += v.x;
  436. this.y += v.y;
  437. this.z += v.z;
  438. return this;
  439. },
  440. addScalar: function ( s ) {
  441. this.x += s;
  442. this.y += s;
  443. this.z += s;
  444. return this;
  445. },
  446. sub: function ( a, b ) {
  447. this.x = a.x - b.x;
  448. this.y = a.y - b.y;
  449. this.z = a.z - b.z;
  450. return this;
  451. },
  452. subSelf: function ( v ) {
  453. this.x -= v.x;
  454. this.y -= v.y;
  455. this.z -= v.z;
  456. return this;
  457. },
  458. multiply: function ( a, b ) {
  459. this.x = a.x * b.x;
  460. this.y = a.y * b.y;
  461. this.z = a.z * b.z;
  462. return this;
  463. },
  464. multiplySelf: function ( v ) {
  465. this.x *= v.x;
  466. this.y *= v.y;
  467. this.z *= v.z;
  468. return this;
  469. },
  470. multiplyScalar: function ( s ) {
  471. this.x *= s;
  472. this.y *= s;
  473. this.z *= s;
  474. return this;
  475. },
  476. divideSelf: function ( v ) {
  477. this.x /= v.x;
  478. this.y /= v.y;
  479. this.z /= v.z;
  480. return this;
  481. },
  482. divideScalar: function ( s ) {
  483. if ( s ) {
  484. this.x /= s;
  485. this.y /= s;
  486. this.z /= s;
  487. } else {
  488. this.x = 0;
  489. this.y = 0;
  490. this.z = 0;
  491. }
  492. return this;
  493. },
  494. negate: function() {
  495. return this.multiplyScalar( - 1 );
  496. },
  497. dot: function ( v ) {
  498. return this.x * v.x + this.y * v.y + this.z * v.z;
  499. },
  500. lengthSq: function () {
  501. return this.x * this.x + this.y * this.y + this.z * this.z;
  502. },
  503. length: function () {
  504. return Math.sqrt( this.lengthSq() );
  505. },
  506. lengthManhattan: function () {
  507. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  508. },
  509. normalize: function () {
  510. return this.divideScalar( this.length() );
  511. },
  512. setLength: function ( l ) {
  513. return this.normalize().multiplyScalar( l );
  514. },
  515. lerpSelf: function ( v, alpha ) {
  516. this.x += ( v.x - this.x ) * alpha;
  517. this.y += ( v.y - this.y ) * alpha;
  518. this.z += ( v.z - this.z ) * alpha;
  519. return this;
  520. },
  521. cross: function ( a, b ) {
  522. this.x = a.y * b.z - a.z * b.y;
  523. this.y = a.z * b.x - a.x * b.z;
  524. this.z = a.x * b.y - a.y * b.x;
  525. return this;
  526. },
  527. crossSelf: function ( v ) {
  528. var x = this.x, y = this.y, z = this.z;
  529. this.x = y * v.z - z * v.y;
  530. this.y = z * v.x - x * v.z;
  531. this.z = x * v.y - y * v.x;
  532. return this;
  533. },
  534. angleTo: function ( v ) {
  535. return Math.acos( this.dot( v ) / this.length() / v.length() );
  536. },
  537. distanceTo: function ( v ) {
  538. return Math.sqrt( this.distanceToSquared( v ) );
  539. },
  540. distanceToSquared: function ( v ) {
  541. return new THREE.Vector3().sub( this, v ).lengthSq();
  542. },
  543. getPositionFromMatrix: function ( m ) {
  544. this.x = m.elements[12];
  545. this.y = m.elements[13];
  546. this.z = m.elements[14];
  547. return this;
  548. },
  549. setEulerFromRotationMatrix: function ( m, order ) {
  550. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  551. // clamp, to handle numerical problems
  552. function clamp( x ) {
  553. return Math.min( Math.max( x, -1 ), 1 );
  554. }
  555. var te = m.elements;
  556. var m11 = te[0], m12 = te[4], m13 = te[8];
  557. var m21 = te[1], m22 = te[5], m23 = te[9];
  558. var m31 = te[2], m32 = te[6], m33 = te[10];
  559. if ( order === undefined || order === 'XYZ' ) {
  560. this.y = Math.asin( clamp( m13 ) );
  561. if ( Math.abs( m13 ) < 0.99999 ) {
  562. this.x = Math.atan2( - m23, m33 );
  563. this.z = Math.atan2( - m12, m11 );
  564. } else {
  565. this.x = Math.atan2( m32, m22 );
  566. this.z = 0;
  567. }
  568. } else if ( order === 'YXZ' ) {
  569. this.x = Math.asin( - clamp( m23 ) );
  570. if ( Math.abs( m23 ) < 0.99999 ) {
  571. this.y = Math.atan2( m13, m33 );
  572. this.z = Math.atan2( m21, m22 );
  573. } else {
  574. this.y = Math.atan2( - m31, m11 );
  575. this.z = 0;
  576. }
  577. } else if ( order === 'ZXY' ) {
  578. this.x = Math.asin( clamp( m32 ) );
  579. if ( Math.abs( m32 ) < 0.99999 ) {
  580. this.y = Math.atan2( - m31, m33 );
  581. this.z = Math.atan2( - m12, m22 );
  582. } else {
  583. this.y = 0;
  584. this.z = Math.atan2( m21, m11 );
  585. }
  586. } else if ( order === 'ZYX' ) {
  587. this.y = Math.asin( - clamp( m31 ) );
  588. if ( Math.abs( m31 ) < 0.99999 ) {
  589. this.x = Math.atan2( m32, m33 );
  590. this.z = Math.atan2( m21, m11 );
  591. } else {
  592. this.x = 0;
  593. this.z = Math.atan2( - m12, m22 );
  594. }
  595. } else if ( order === 'YZX' ) {
  596. this.z = Math.asin( clamp( m21 ) );
  597. if ( Math.abs( m21 ) < 0.99999 ) {
  598. this.x = Math.atan2( - m23, m22 );
  599. this.y = Math.atan2( - m31, m11 );
  600. } else {
  601. this.x = 0;
  602. this.y = Math.atan2( m13, m33 );
  603. }
  604. } else if ( order === 'XZY' ) {
  605. this.z = Math.asin( - clamp( m12 ) );
  606. if ( Math.abs( m12 ) < 0.99999 ) {
  607. this.x = Math.atan2( m32, m22 );
  608. this.y = Math.atan2( m13, m11 );
  609. } else {
  610. this.x = Math.atan2( - m23, m33 );
  611. this.y = 0;
  612. }
  613. }
  614. return this;
  615. },
  616. setEulerFromQuaternion: function ( q, order ) {
  617. // q is assumed to be normalized
  618. // clamp, to handle numerical problems
  619. function clamp( x ) {
  620. return Math.min( Math.max( x, -1 ), 1 );
  621. }
  622. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  623. var sqx = q.x * q.x;
  624. var sqy = q.y * q.y;
  625. var sqz = q.z * q.z;
  626. var sqw = q.w * q.w;
  627. if ( order === undefined || order === 'XYZ' ) {
  628. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  629. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  630. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  631. } else if ( order === 'YXZ' ) {
  632. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  633. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  634. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  635. } else if ( order === 'ZXY' ) {
  636. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  637. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  638. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  639. } else if ( order === 'ZYX' ) {
  640. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  641. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  642. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  643. } else if ( order === 'YZX' ) {
  644. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  645. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  646. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  647. } else if ( order === 'XZY' ) {
  648. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  649. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  650. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  651. }
  652. return this;
  653. },
  654. getScaleFromMatrix: function ( m ) {
  655. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  656. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  657. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  658. this.x = sx;
  659. this.y = sy;
  660. this.z = sz;
  661. return this;
  662. },
  663. equals: function ( v ) {
  664. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  665. },
  666. isZero: function ( v ) {
  667. return this.lengthSq() < ( v !== undefined ? v : 0.0001 );
  668. },
  669. clone: function () {
  670. return new THREE.Vector3( this.x, this.y, this.z );
  671. }
  672. };
  673. /**
  674. * @author supereggbert / http://www.paulbrunt.co.uk/
  675. * @author philogb / http://blog.thejit.org/
  676. * @author mikael emtinger / http://gomo.se/
  677. * @author egraether / http://egraether.com/
  678. * @author WestLangley / http://github.com/WestLangley
  679. */
  680. THREE.Vector4 = function ( x, y, z, w ) {
  681. this.x = x || 0;
  682. this.y = y || 0;
  683. this.z = z || 0;
  684. this.w = ( w !== undefined ) ? w : 1;
  685. };
  686. THREE.Vector4.prototype = {
  687. constructor: THREE.Vector4,
  688. set: function ( x, y, z, w ) {
  689. this.x = x;
  690. this.y = y;
  691. this.z = z;
  692. this.w = w;
  693. return this;
  694. },
  695. copy: function ( v ) {
  696. this.x = v.x;
  697. this.y = v.y;
  698. this.z = v.z;
  699. this.w = ( v.w !== undefined ) ? v.w : 1;
  700. return this;
  701. },
  702. add: function ( a, b ) {
  703. this.x = a.x + b.x;
  704. this.y = a.y + b.y;
  705. this.z = a.z + b.z;
  706. this.w = a.w + b.w;
  707. return this;
  708. },
  709. addSelf: function ( v ) {
  710. this.x += v.x;
  711. this.y += v.y;
  712. this.z += v.z;
  713. this.w += v.w;
  714. return this;
  715. },
  716. sub: function ( a, b ) {
  717. this.x = a.x - b.x;
  718. this.y = a.y - b.y;
  719. this.z = a.z - b.z;
  720. this.w = a.w - b.w;
  721. return this;
  722. },
  723. subSelf: function ( v ) {
  724. this.x -= v.x;
  725. this.y -= v.y;
  726. this.z -= v.z;
  727. this.w -= v.w;
  728. return this;
  729. },
  730. multiplyScalar: function ( s ) {
  731. this.x *= s;
  732. this.y *= s;
  733. this.z *= s;
  734. this.w *= s;
  735. return this;
  736. },
  737. divideScalar: function ( s ) {
  738. if ( s ) {
  739. this.x /= s;
  740. this.y /= s;
  741. this.z /= s;
  742. this.w /= s;
  743. } else {
  744. this.x = 0;
  745. this.y = 0;
  746. this.z = 0;
  747. this.w = 1;
  748. }
  749. return this;
  750. },
  751. negate: function() {
  752. return this.multiplyScalar( -1 );
  753. },
  754. dot: function ( v ) {
  755. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  756. },
  757. lengthSq: function () {
  758. return this.dot( this );
  759. },
  760. length: function () {
  761. return Math.sqrt( this.lengthSq() );
  762. },
  763. lengthManhattan: function () {
  764. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  765. },
  766. normalize: function () {
  767. return this.divideScalar( this.length() );
  768. },
  769. setLength: function ( l ) {
  770. return this.normalize().multiplyScalar( l );
  771. },
  772. lerpSelf: function ( v, alpha ) {
  773. this.x += ( v.x - this.x ) * alpha;
  774. this.y += ( v.y - this.y ) * alpha;
  775. this.z += ( v.z - this.z ) * alpha;
  776. this.w += ( v.w - this.w ) * alpha;
  777. return this;
  778. },
  779. clone: function () {
  780. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  781. },
  782. setAxisAngleFromQuaternion: function ( q ) {
  783. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  784. // q is assumed to be normalized
  785. this.w = 2 * Math.acos( q.w );
  786. var s = Math.sqrt( 1 - q.w * q.w );
  787. if ( s < 0.0001 ) {
  788. this.x = 1;
  789. this.y = 0;
  790. this.z = 0;
  791. } else {
  792. this.x = q.x / s;
  793. this.y = q.y / s;
  794. this.z = q.z / s;
  795. }
  796. return this;
  797. },
  798. setAxisAngleFromRotationMatrix: function ( m ) {
  799. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  800. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  801. var angle, x, y, z, // variables for result
  802. epsilon = 0.01, // margin to allow for rounding errors
  803. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  804. te = m.elements,
  805. m11 = te[0], m12 = te[4], m13 = te[8],
  806. m21 = te[1], m22 = te[5], m23 = te[9],
  807. m31 = te[2], m32 = te[6], m33 = te[10];
  808. if ( ( Math.abs( m12 - m21 ) < epsilon )
  809. && ( Math.abs( m13 - m31 ) < epsilon )
  810. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  811. // singularity found
  812. // first check for identity matrix which must have +1 for all terms
  813. // in leading diagonal and zero in other terms
  814. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  815. && ( Math.abs( m13 + m31 ) < epsilon2 )
  816. && ( Math.abs( m23 + m32 ) < epsilon2 )
  817. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  818. // this singularity is identity matrix so angle = 0
  819. this.set( 1, 0, 0, 0 );
  820. return this; // zero angle, arbitrary axis
  821. }
  822. // otherwise this singularity is angle = 180
  823. angle = Math.PI;
  824. var xx = ( m11 + 1 ) / 2;
  825. var yy = ( m22 + 1 ) / 2;
  826. var zz = ( m33 + 1 ) / 2;
  827. var xy = ( m12 + m21 ) / 4;
  828. var xz = ( m13 + m31 ) / 4;
  829. var yz = ( m23 + m32 ) / 4;
  830. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  831. if ( xx < epsilon ) {
  832. x = 0;
  833. y = 0.707106781;
  834. z = 0.707106781;
  835. } else {
  836. x = Math.sqrt( xx );
  837. y = xy / x;
  838. z = xz / x;
  839. }
  840. } else if ( yy > zz ) { // m22 is the largest diagonal term
  841. if ( yy < epsilon ) {
  842. x = 0.707106781;
  843. y = 0;
  844. z = 0.707106781;
  845. } else {
  846. y = Math.sqrt( yy );
  847. x = xy / y;
  848. z = yz / y;
  849. }
  850. } else { // m33 is the largest diagonal term so base result on this
  851. if ( zz < epsilon ) {
  852. x = 0.707106781;
  853. y = 0.707106781;
  854. z = 0;
  855. } else {
  856. z = Math.sqrt( zz );
  857. x = xz / z;
  858. y = yz / z;
  859. }
  860. }
  861. this.set( x, y, z, angle );
  862. return this; // return 180 deg rotation
  863. }
  864. // as we have reached here there are no singularities so we can handle normally
  865. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  866. + ( m13 - m31 ) * ( m13 - m31 )
  867. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  868. if ( Math.abs( s ) < 0.001 ) s = 1;
  869. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  870. // caught by singularity test above, but I've left it in just in case
  871. this.x = ( m32 - m23 ) / s;
  872. this.y = ( m13 - m31 ) / s;
  873. this.z = ( m21 - m12 ) / s;
  874. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  875. return this;
  876. }
  877. };
  878. /**
  879. * @author alteredq / http://alteredqualia.com/
  880. */
  881. THREE.Matrix3 = function () {
  882. this.elements = new Float32Array(9);
  883. };
  884. THREE.Matrix3.prototype = {
  885. constructor: THREE.Matrix3,
  886. getInverse: function ( matrix ) {
  887. // input: THREE.Matrix4
  888. // ( based on http://code.google.com/p/webgl-mjs/ )
  889. var me = matrix.elements;
  890. var a11 = me[10] * me[5] - me[6] * me[9];
  891. var a21 = - me[10] * me[1] + me[2] * me[9];
  892. var a31 = me[6] * me[1] - me[2] * me[5];
  893. var a12 = - me[10] * me[4] + me[6] * me[8];
  894. var a22 = me[10] * me[0] - me[2] * me[8];
  895. var a32 = - me[6] * me[0] + me[2] * me[4];
  896. var a13 = me[9] * me[4] - me[5] * me[8];
  897. var a23 = - me[9] * me[0] + me[1] * me[8];
  898. var a33 = me[5] * me[0] - me[1] * me[4];
  899. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  900. // no inverse
  901. if ( det === 0 ) {
  902. console.warn( "Matrix3.getInverse(): determinant == 0" );
  903. }
  904. var idet = 1.0 / det;
  905. var m = this.elements;
  906. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  907. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  908. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  909. return this;
  910. },
  911. transpose: function () {
  912. var tmp, m = this.elements;
  913. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  914. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  915. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  916. return this;
  917. },
  918. transposeIntoArray: function ( r ) {
  919. var m = this.m;
  920. r[ 0 ] = m[ 0 ];
  921. r[ 1 ] = m[ 3 ];
  922. r[ 2 ] = m[ 6 ];
  923. r[ 3 ] = m[ 1 ];
  924. r[ 4 ] = m[ 4 ];
  925. r[ 5 ] = m[ 7 ];
  926. r[ 6 ] = m[ 2 ];
  927. r[ 7 ] = m[ 5 ];
  928. r[ 8 ] = m[ 8 ];
  929. return this;
  930. }
  931. };
  932. /**
  933. * @author mrdoob / http://mrdoob.com/
  934. * @author supereggbert / http://www.paulbrunt.co.uk/
  935. * @author philogb / http://blog.thejit.org/
  936. * @author jordi_ros / http://plattsoft.com
  937. * @author D1plo1d / http://github.com/D1plo1d
  938. * @author alteredq / http://alteredqualia.com/
  939. * @author mikael emtinger / http://gomo.se/
  940. * @author timknip / http://www.floorplanner.com/
  941. */
  942. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  943. this.elements = new Float32Array( 16 );
  944. this.set(
  945. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  946. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  947. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  948. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  949. );
  950. };
  951. THREE.Matrix4.prototype = {
  952. constructor: THREE.Matrix4,
  953. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  954. var te = this.elements;
  955. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  956. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  957. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  958. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  959. return this;
  960. },
  961. identity: function () {
  962. this.set(
  963. 1, 0, 0, 0,
  964. 0, 1, 0, 0,
  965. 0, 0, 1, 0,
  966. 0, 0, 0, 1
  967. );
  968. return this;
  969. },
  970. copy: function ( m ) {
  971. var me = m.elements;
  972. this.set(
  973. me[0], me[4], me[8], me[12],
  974. me[1], me[5], me[9], me[13],
  975. me[2], me[6], me[10], me[14],
  976. me[3], me[7], me[11], me[15]
  977. );
  978. return this;
  979. },
  980. lookAt: function ( eye, target, up ) {
  981. var te = this.elements;
  982. var x = THREE.Matrix4.__v1;
  983. var y = THREE.Matrix4.__v2;
  984. var z = THREE.Matrix4.__v3;
  985. z.sub( eye, target ).normalize();
  986. if ( z.length() === 0 ) {
  987. z.z = 1;
  988. }
  989. x.cross( up, z ).normalize();
  990. if ( x.length() === 0 ) {
  991. z.x += 0.0001;
  992. x.cross( up, z ).normalize();
  993. }
  994. y.cross( z, x );
  995. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  996. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  997. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  998. return this;
  999. },
  1000. multiply: function ( a, b ) {
  1001. var ae = a.elements;
  1002. var be = b.elements;
  1003. var te = this.elements;
  1004. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1005. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1006. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1007. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1008. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1009. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1010. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1011. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1012. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1013. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1014. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1015. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1016. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1017. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1018. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1019. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1020. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1021. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1022. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1023. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1024. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1025. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1026. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1027. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1028. return this;
  1029. },
  1030. multiplySelf: function ( m ) {
  1031. return this.multiply( this, m );
  1032. },
  1033. multiplyToArray: function ( a, b, r ) {
  1034. var te = this.elements;
  1035. this.multiply( a, b );
  1036. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1037. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1038. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1039. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1040. return this;
  1041. },
  1042. multiplyScalar: function ( s ) {
  1043. var te = this.elements;
  1044. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1045. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1046. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1047. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1048. return this;
  1049. },
  1050. multiplyVector3: function ( v ) {
  1051. var te = this.elements;
  1052. var vx = v.x, vy = v.y, vz = v.z;
  1053. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1054. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1055. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1056. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1057. return v;
  1058. },
  1059. multiplyVector4: function ( v ) {
  1060. var te = this.elements;
  1061. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1062. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1063. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1064. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1065. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1066. return v;
  1067. },
  1068. multiplyVector3Array: function ( a ) {
  1069. var tmp = THREE.Matrix4.__v1;
  1070. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1071. tmp.x = a[ i ];
  1072. tmp.y = a[ i + 1 ];
  1073. tmp.z = a[ i + 2 ];
  1074. this.multiplyVector3( tmp );
  1075. a[ i ] = tmp.x;
  1076. a[ i + 1 ] = tmp.y;
  1077. a[ i + 2 ] = tmp.z;
  1078. }
  1079. return a;
  1080. },
  1081. rotateAxis: function ( v ) {
  1082. var te = this.elements;
  1083. var vx = v.x, vy = v.y, vz = v.z;
  1084. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1085. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1086. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1087. v.normalize();
  1088. return v;
  1089. },
  1090. crossVector: function ( a ) {
  1091. var te = this.elements;
  1092. var v = new THREE.Vector4();
  1093. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1094. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1095. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1096. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1097. return v;
  1098. },
  1099. determinant: function () {
  1100. var te = this.elements;
  1101. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1102. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1103. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1104. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1105. //TODO: make this more efficient
  1106. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1107. return (
  1108. n14 * n23 * n32 * n41-
  1109. n13 * n24 * n32 * n41-
  1110. n14 * n22 * n33 * n41+
  1111. n12 * n24 * n33 * n41+
  1112. n13 * n22 * n34 * n41-
  1113. n12 * n23 * n34 * n41-
  1114. n14 * n23 * n31 * n42+
  1115. n13 * n24 * n31 * n42+
  1116. n14 * n21 * n33 * n42-
  1117. n11 * n24 * n33 * n42-
  1118. n13 * n21 * n34 * n42+
  1119. n11 * n23 * n34 * n42+
  1120. n14 * n22 * n31 * n43-
  1121. n12 * n24 * n31 * n43-
  1122. n14 * n21 * n32 * n43+
  1123. n11 * n24 * n32 * n43+
  1124. n12 * n21 * n34 * n43-
  1125. n11 * n22 * n34 * n43-
  1126. n13 * n22 * n31 * n44+
  1127. n12 * n23 * n31 * n44+
  1128. n13 * n21 * n32 * n44-
  1129. n11 * n23 * n32 * n44-
  1130. n12 * n21 * n33 * n44+
  1131. n11 * n22 * n33 * n44
  1132. );
  1133. },
  1134. transpose: function () {
  1135. var te = this.elements;
  1136. var tmp;
  1137. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1138. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1139. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1140. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1141. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1142. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1143. return this;
  1144. },
  1145. flattenToArray: function ( flat ) {
  1146. var te = this.elements;
  1147. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1148. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1149. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1150. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1151. return flat;
  1152. },
  1153. flattenToArrayOffset: function( flat, offset ) {
  1154. var te = this.elements;
  1155. flat[ offset ] = te[0];
  1156. flat[ offset + 1 ] = te[1];
  1157. flat[ offset + 2 ] = te[2];
  1158. flat[ offset + 3 ] = te[3];
  1159. flat[ offset + 4 ] = te[4];
  1160. flat[ offset + 5 ] = te[5];
  1161. flat[ offset + 6 ] = te[6];
  1162. flat[ offset + 7 ] = te[7];
  1163. flat[ offset + 8 ] = te[8];
  1164. flat[ offset + 9 ] = te[9];
  1165. flat[ offset + 10 ] = te[10];
  1166. flat[ offset + 11 ] = te[11];
  1167. flat[ offset + 12 ] = te[12];
  1168. flat[ offset + 13 ] = te[13];
  1169. flat[ offset + 14 ] = te[14];
  1170. flat[ offset + 15 ] = te[15];
  1171. return flat;
  1172. },
  1173. getPosition: function () {
  1174. var te = this.elements;
  1175. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1176. },
  1177. setPosition: function ( v ) {
  1178. var te = this.elements;
  1179. te[12] = v.x;
  1180. te[13] = v.y;
  1181. te[14] = v.z;
  1182. return this;
  1183. },
  1184. getColumnX: function () {
  1185. var te = this.elements;
  1186. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1187. },
  1188. getColumnY: function () {
  1189. var te = this.elements;
  1190. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1191. },
  1192. getColumnZ: function() {
  1193. var te = this.elements;
  1194. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1195. },
  1196. getInverse: function ( m ) {
  1197. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1198. var te = this.elements;
  1199. var me = m.elements;
  1200. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1201. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1202. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1203. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1204. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1205. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1206. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1207. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1208. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1209. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1210. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1211. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1212. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1213. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1214. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1215. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1216. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1217. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1218. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1219. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1220. this.multiplyScalar( 1 / m.determinant() );
  1221. return this;
  1222. },
  1223. setRotationFromEuler: function ( v, order ) {
  1224. var te = this.elements;
  1225. var x = v.x, y = v.y, z = v.z;
  1226. var a = Math.cos( x ), b = Math.sin( x );
  1227. var c = Math.cos( y ), d = Math.sin( y );
  1228. var e = Math.cos( z ), f = Math.sin( z );
  1229. if ( order === undefined || order === 'XYZ' ) {
  1230. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1231. te[0] = c * e;
  1232. te[4] = - c * f;
  1233. te[8] = d;
  1234. te[1] = af + be * d;
  1235. te[5] = ae - bf * d;
  1236. te[9] = - b * c;
  1237. te[2] = bf - ae * d;
  1238. te[6] = be + af * d;
  1239. te[10] = a * c;
  1240. } else if ( order === 'YXZ' ) {
  1241. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1242. te[0] = ce + df * b;
  1243. te[4] = de * b - cf;
  1244. te[8] = a * d;
  1245. te[1] = a * f;
  1246. te[5] = a * e;
  1247. te[9] = - b;
  1248. te[2] = cf * b - de;
  1249. te[6] = df + ce * b;
  1250. te[10] = a * c;
  1251. } else if ( order === 'ZXY' ) {
  1252. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1253. te[0] = ce - df * b;
  1254. te[4] = - a * f;
  1255. te[8] = de + cf * b;
  1256. te[1] = cf + de * b;
  1257. te[5] = a * e;
  1258. te[9] = df - ce * b;
  1259. te[2] = - a * d;
  1260. te[6] = b;
  1261. te[10] = a * c;
  1262. } else if ( order === 'ZYX' ) {
  1263. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1264. te[0] = c * e;
  1265. te[4] = be * d - af;
  1266. te[8] = ae * d + bf;
  1267. te[1] = c * f;
  1268. te[5] = bf * d + ae;
  1269. te[9] = af * d - be;
  1270. te[2] = - d;
  1271. te[6] = b * c;
  1272. te[10] = a * c;
  1273. } else if ( order === 'YZX' ) {
  1274. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1275. te[0] = c * e;
  1276. te[4] = bd - ac * f;
  1277. te[8] = bc * f + ad;
  1278. te[1] = f;
  1279. te[5] = a * e;
  1280. te[9] = - b * e;
  1281. te[2] = - d * e;
  1282. te[6] = ad * f + bc;
  1283. te[10] = ac - bd * f;
  1284. } else if ( order === 'XZY' ) {
  1285. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1286. te[0] = c * e;
  1287. te[4] = - f;
  1288. te[8] = d * e;
  1289. te[1] = ac * f + bd;
  1290. te[5] = a * e;
  1291. te[9] = ad * f - bc;
  1292. te[2] = bc * f - ad;
  1293. te[6] = b * e;
  1294. te[10] = bd * f + ac;
  1295. }
  1296. return this;
  1297. },
  1298. setRotationFromQuaternion: function ( q ) {
  1299. var te = this.elements;
  1300. var x = q.x, y = q.y, z = q.z, w = q.w;
  1301. var x2 = x + x, y2 = y + y, z2 = z + z;
  1302. var xx = x * x2, xy = x * y2, xz = x * z2;
  1303. var yy = y * y2, yz = y * z2, zz = z * z2;
  1304. var wx = w * x2, wy = w * y2, wz = w * z2;
  1305. te[0] = 1 - ( yy + zz );
  1306. te[4] = xy - wz;
  1307. te[8] = xz + wy;
  1308. te[1] = xy + wz;
  1309. te[5] = 1 - ( xx + zz );
  1310. te[9] = yz - wx;
  1311. te[2] = xz - wy;
  1312. te[6] = yz + wx;
  1313. te[10] = 1 - ( xx + yy );
  1314. return this;
  1315. },
  1316. compose: function ( translation, rotation, scale ) {
  1317. var te = this.elements;
  1318. var mRotation = THREE.Matrix4.__m1;
  1319. var mScale = THREE.Matrix4.__m2;
  1320. mRotation.identity();
  1321. mRotation.setRotationFromQuaternion( rotation );
  1322. mScale.makeScale( scale.x, scale.y, scale.z );
  1323. this.multiply( mRotation, mScale );
  1324. te[12] = translation.x;
  1325. te[13] = translation.y;
  1326. te[14] = translation.z;
  1327. return this;
  1328. },
  1329. decompose: function ( translation, rotation, scale ) {
  1330. var te = this.elements;
  1331. // grab the axis vectors
  1332. var x = THREE.Matrix4.__v1;
  1333. var y = THREE.Matrix4.__v2;
  1334. var z = THREE.Matrix4.__v3;
  1335. x.set( te[0], te[1], te[2] );
  1336. y.set( te[4], te[5], te[6] );
  1337. z.set( te[8], te[9], te[10] );
  1338. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1339. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1340. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1341. scale.x = x.length();
  1342. scale.y = y.length();
  1343. scale.z = z.length();
  1344. translation.x = te[12];
  1345. translation.y = te[13];
  1346. translation.z = te[14];
  1347. // scale the rotation part
  1348. var matrix = THREE.Matrix4.__m1;
  1349. matrix.copy( this );
  1350. matrix.elements[0] /= scale.x;
  1351. matrix.elements[1] /= scale.x;
  1352. matrix.elements[2] /= scale.x;
  1353. matrix.elements[4] /= scale.y;
  1354. matrix.elements[5] /= scale.y;
  1355. matrix.elements[6] /= scale.y;
  1356. matrix.elements[8] /= scale.z;
  1357. matrix.elements[9] /= scale.z;
  1358. matrix.elements[10] /= scale.z;
  1359. rotation.setFromRotationMatrix( matrix );
  1360. return [ translation, rotation, scale ];
  1361. },
  1362. extractPosition: function ( m ) {
  1363. var te = this.elements;
  1364. var me = m.elements;
  1365. te[12] = me[12];
  1366. te[13] = me[13];
  1367. te[14] = me[14];
  1368. return this;
  1369. },
  1370. extractRotation: function ( m ) {
  1371. var te = this.elements;
  1372. var me = m.elements;
  1373. var vector = THREE.Matrix4.__v1;
  1374. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1375. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1376. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1377. te[0] = me[0] * scaleX;
  1378. te[1] = me[1] * scaleX;
  1379. te[2] = me[2] * scaleX;
  1380. te[4] = me[4] * scaleY;
  1381. te[5] = me[5] * scaleY;
  1382. te[6] = me[6] * scaleY;
  1383. te[8] = me[8] * scaleZ;
  1384. te[9] = me[9] * scaleZ;
  1385. te[10] = me[10] * scaleZ;
  1386. return this;
  1387. },
  1388. //
  1389. translate: function ( v ) {
  1390. var te = this.elements;
  1391. var x = v.x, y = v.y, z = v.z;
  1392. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1393. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1394. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1395. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1396. return this;
  1397. },
  1398. rotateX: function ( angle ) {
  1399. var te = this.elements;
  1400. var m12 = te[4];
  1401. var m22 = te[5];
  1402. var m32 = te[6];
  1403. var m42 = te[7];
  1404. var m13 = te[8];
  1405. var m23 = te[9];
  1406. var m33 = te[10];
  1407. var m43 = te[11];
  1408. var c = Math.cos( angle );
  1409. var s = Math.sin( angle );
  1410. te[4] = c * m12 + s * m13;
  1411. te[5] = c * m22 + s * m23;
  1412. te[6] = c * m32 + s * m33;
  1413. te[7] = c * m42 + s * m43;
  1414. te[8] = c * m13 - s * m12;
  1415. te[9] = c * m23 - s * m22;
  1416. te[10] = c * m33 - s * m32;
  1417. te[11] = c * m43 - s * m42;
  1418. return this;
  1419. },
  1420. rotateY: function ( angle ) {
  1421. var te = this.elements;
  1422. var m11 = te[0];
  1423. var m21 = te[1];
  1424. var m31 = te[2];
  1425. var m41 = te[3];
  1426. var m13 = te[8];
  1427. var m23 = te[9];
  1428. var m33 = te[10];
  1429. var m43 = te[11];
  1430. var c = Math.cos( angle );
  1431. var s = Math.sin( angle );
  1432. te[0] = c * m11 - s * m13;
  1433. te[1] = c * m21 - s * m23;
  1434. te[2] = c * m31 - s * m33;
  1435. te[3] = c * m41 - s * m43;
  1436. te[8] = c * m13 + s * m11;
  1437. te[9] = c * m23 + s * m21;
  1438. te[10] = c * m33 + s * m31;
  1439. te[11] = c * m43 + s * m41;
  1440. return this;
  1441. },
  1442. rotateZ: function ( angle ) {
  1443. var te = this.elements;
  1444. var m11 = te[0];
  1445. var m21 = te[1];
  1446. var m31 = te[2];
  1447. var m41 = te[3];
  1448. var m12 = te[4];
  1449. var m22 = te[5];
  1450. var m32 = te[6];
  1451. var m42 = te[7];
  1452. var c = Math.cos( angle );
  1453. var s = Math.sin( angle );
  1454. te[0] = c * m11 + s * m12;
  1455. te[1] = c * m21 + s * m22;
  1456. te[2] = c * m31 + s * m32;
  1457. te[3] = c * m41 + s * m42;
  1458. te[4] = c * m12 - s * m11;
  1459. te[5] = c * m22 - s * m21;
  1460. te[6] = c * m32 - s * m31;
  1461. te[7] = c * m42 - s * m41;
  1462. return this;
  1463. },
  1464. rotateByAxis: function ( axis, angle ) {
  1465. var te = this.elements;
  1466. // optimize by checking axis
  1467. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1468. return this.rotateX( angle );
  1469. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1470. return this.rotateY( angle );
  1471. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1472. return this.rotateZ( angle );
  1473. }
  1474. var x = axis.x, y = axis.y, z = axis.z;
  1475. var n = Math.sqrt(x * x + y * y + z * z);
  1476. x /= n;
  1477. y /= n;
  1478. z /= n;
  1479. var xx = x * x, yy = y * y, zz = z * z;
  1480. var c = Math.cos( angle );
  1481. var s = Math.sin( angle );
  1482. var oneMinusCosine = 1 - c;
  1483. var xy = x * y * oneMinusCosine;
  1484. var xz = x * z * oneMinusCosine;
  1485. var yz = y * z * oneMinusCosine;
  1486. var xs = x * s;
  1487. var ys = y * s;
  1488. var zs = z * s;
  1489. var r11 = xx + (1 - xx) * c;
  1490. var r21 = xy + zs;
  1491. var r31 = xz - ys;
  1492. var r12 = xy - zs;
  1493. var r22 = yy + (1 - yy) * c;
  1494. var r32 = yz + xs;
  1495. var r13 = xz + ys;
  1496. var r23 = yz - xs;
  1497. var r33 = zz + (1 - zz) * c;
  1498. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1499. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1500. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1501. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1502. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1503. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1504. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1505. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1506. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1507. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1508. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1509. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1510. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1511. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1512. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1513. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1514. return this;
  1515. },
  1516. scale: function ( v ) {
  1517. var te = this.elements;
  1518. var x = v.x, y = v.y, z = v.z;
  1519. te[0] *= x; te[4] *= y; te[8] *= z;
  1520. te[1] *= x; te[5] *= y; te[9] *= z;
  1521. te[2] *= x; te[6] *= y; te[10] *= z;
  1522. te[3] *= x; te[7] *= y; te[11] *= z;
  1523. return this;
  1524. },
  1525. getMaxScaleOnAxis: function () {
  1526. var te = this.elements;
  1527. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  1528. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  1529. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  1530. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  1531. },
  1532. //
  1533. makeTranslation: function ( x, y, z ) {
  1534. this.set(
  1535. 1, 0, 0, x,
  1536. 0, 1, 0, y,
  1537. 0, 0, 1, z,
  1538. 0, 0, 0, 1
  1539. );
  1540. return this;
  1541. },
  1542. makeRotationX: function ( theta ) {
  1543. var c = Math.cos( theta ), s = Math.sin( theta );
  1544. this.set(
  1545. 1, 0, 0, 0,
  1546. 0, c, -s, 0,
  1547. 0, s, c, 0,
  1548. 0, 0, 0, 1
  1549. );
  1550. return this;
  1551. },
  1552. makeRotationY: function ( theta ) {
  1553. var c = Math.cos( theta ), s = Math.sin( theta );
  1554. this.set(
  1555. c, 0, s, 0,
  1556. 0, 1, 0, 0,
  1557. -s, 0, c, 0,
  1558. 0, 0, 0, 1
  1559. );
  1560. return this;
  1561. },
  1562. makeRotationZ: function ( theta ) {
  1563. var c = Math.cos( theta ), s = Math.sin( theta );
  1564. this.set(
  1565. c, -s, 0, 0,
  1566. s, c, 0, 0,
  1567. 0, 0, 1, 0,
  1568. 0, 0, 0, 1
  1569. );
  1570. return this;
  1571. },
  1572. makeRotationAxis: function ( axis, angle ) {
  1573. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1574. var c = Math.cos( angle );
  1575. var s = Math.sin( angle );
  1576. var t = 1 - c;
  1577. var x = axis.x, y = axis.y, z = axis.z;
  1578. var tx = t * x, ty = t * y;
  1579. this.set(
  1580. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1581. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1582. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1583. 0, 0, 0, 1
  1584. );
  1585. return this;
  1586. },
  1587. makeScale: function ( x, y, z ) {
  1588. this.set(
  1589. x, 0, 0, 0,
  1590. 0, y, 0, 0,
  1591. 0, 0, z, 0,
  1592. 0, 0, 0, 1
  1593. );
  1594. return this;
  1595. },
  1596. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1597. var te = this.elements;
  1598. var x = 2 * near / ( right - left );
  1599. var y = 2 * near / ( top - bottom );
  1600. var a = ( right + left ) / ( right - left );
  1601. var b = ( top + bottom ) / ( top - bottom );
  1602. var c = - ( far + near ) / ( far - near );
  1603. var d = - 2 * far * near / ( far - near );
  1604. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1605. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1606. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1607. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1608. return this;
  1609. },
  1610. makePerspective: function ( fov, aspect, near, far ) {
  1611. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1612. var ymin = - ymax;
  1613. var xmin = ymin * aspect;
  1614. var xmax = ymax * aspect;
  1615. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1616. },
  1617. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1618. var te = this.elements;
  1619. var w = right - left;
  1620. var h = top - bottom;
  1621. var p = far - near;
  1622. var x = ( right + left ) / w;
  1623. var y = ( top + bottom ) / h;
  1624. var z = ( far + near ) / p;
  1625. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1626. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1627. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1628. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1629. return this;
  1630. },
  1631. clone: function () {
  1632. var te = this.elements;
  1633. return new THREE.Matrix4(
  1634. te[0], te[4], te[8], te[12],
  1635. te[1], te[5], te[9], te[13],
  1636. te[2], te[6], te[10], te[14],
  1637. te[3], te[7], te[11], te[15]
  1638. );
  1639. }
  1640. };
  1641. THREE.Matrix4.__v1 = new THREE.Vector3();
  1642. THREE.Matrix4.__v2 = new THREE.Vector3();
  1643. THREE.Matrix4.__v3 = new THREE.Vector3();
  1644. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1645. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1646. /**
  1647. * https://github.com/mrdoob/eventtarget.js/
  1648. */
  1649. THREE.EventTarget = function () {
  1650. var listeners = {};
  1651. this.addEventListener = function ( type, listener ) {
  1652. if ( listeners[ type ] === undefined ) {
  1653. listeners[ type ] = [];
  1654. }
  1655. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1656. listeners[ type ].push( listener );
  1657. }
  1658. };
  1659. this.dispatchEvent = function ( event ) {
  1660. for ( var listener in listeners[ event.type ] ) {
  1661. listeners[ event.type ][ listener ]( event );
  1662. }
  1663. };
  1664. this.removeEventListener = function ( type, listener ) {
  1665. var index = listeners[ type ].indexOf( listener );
  1666. if ( index !== - 1 ) {
  1667. listeners[ type ].splice( index, 1 );
  1668. }
  1669. };
  1670. };
  1671. /**
  1672. * @author mrdoob / http://mrdoob.com/
  1673. * @author alteredq / http://alteredqualia.com/
  1674. */
  1675. THREE.Frustum = function ( ) {
  1676. this.planes = [
  1677. new THREE.Vector4(),
  1678. new THREE.Vector4(),
  1679. new THREE.Vector4(),
  1680. new THREE.Vector4(),
  1681. new THREE.Vector4(),
  1682. new THREE.Vector4()
  1683. ];
  1684. };
  1685. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  1686. var plane;
  1687. var planes = this.planes;
  1688. var me = m.elements;
  1689. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  1690. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  1691. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  1692. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  1693. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  1694. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  1695. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  1696. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  1697. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  1698. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  1699. for ( var i = 0; i < 6; i ++ ) {
  1700. plane = planes[ i ];
  1701. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  1702. }
  1703. };
  1704. THREE.Frustum.prototype.contains = function ( object ) {
  1705. var distance = 0.0;
  1706. var planes = this.planes;
  1707. var matrix = object.matrixWorld;
  1708. var me = matrix.elements;
  1709. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  1710. for ( var i = 0; i < 6; i ++ ) {
  1711. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  1712. if ( distance <= radius ) return false;
  1713. }
  1714. return true;
  1715. };
  1716. THREE.Frustum.__v1 = new THREE.Vector3();
  1717. /**
  1718. * @author mrdoob / http://mrdoob.com/
  1719. */
  1720. ( function ( THREE ) {
  1721. THREE.Ray = function ( origin, direction, near, far ) {
  1722. this.origin = origin || new THREE.Vector3();
  1723. this.direction = direction || new THREE.Vector3();
  1724. this.near = near || 0;
  1725. this.far = far || Infinity;
  1726. };
  1727. var originCopy = new THREE.Vector3();
  1728. var localOriginCopy = new THREE.Vector3();
  1729. var localDirectionCopy = new THREE.Vector3();
  1730. var vector = new THREE.Vector3();
  1731. var normal = new THREE.Vector3();
  1732. var intersectPoint = new THREE.Vector3();
  1733. var inverseMatrix = new THREE.Matrix4();
  1734. var descSort = function ( a, b ) {
  1735. return a.distance - b.distance;
  1736. };
  1737. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  1738. var distanceFromIntersection = function ( origin, direction, position ) {
  1739. v0.sub( position, origin );
  1740. var dot = v0.dot( direction );
  1741. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  1742. var distance = position.distanceTo( intersect );
  1743. return distance;
  1744. };
  1745. // http://www.blackpawn.com/texts/pointinpoly/default.html
  1746. var pointInFace3 = function ( p, a, b, c ) {
  1747. v0.sub( c, a );
  1748. v1.sub( b, a );
  1749. v2.sub( p, a );
  1750. var dot00 = v0.dot( v0 );
  1751. var dot01 = v0.dot( v1 );
  1752. var dot02 = v0.dot( v2 );
  1753. var dot11 = v1.dot( v1 );
  1754. var dot12 = v1.dot( v2 );
  1755. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  1756. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  1757. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  1758. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  1759. };
  1760. var intersectObject = function ( object, ray, intersects ) {
  1761. var distance,intersect;
  1762. if ( object instanceof THREE.Particle ) {
  1763. distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1764. if ( distance > object.scale.x ) {
  1765. return intersects;
  1766. }
  1767. intersect = {
  1768. distance: distance,
  1769. point: object.position,
  1770. face: null,
  1771. object: object
  1772. };
  1773. intersects.push( intersect );
  1774. } else if ( object instanceof THREE.Mesh ) {
  1775. // Checking boundingSphere
  1776. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  1777. // Checking distance to ray
  1778. distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  1779. if ( distance > scaledRadius) {
  1780. return intersects;
  1781. }
  1782. // Checking faces
  1783. var f, fl, face, dot, scalar,
  1784. geometry = object.geometry,
  1785. vertices = geometry.vertices,
  1786. objMatrix, geometryMaterials,
  1787. isFaceMaterial, material, side, point;
  1788. geometryMaterials = object.geometry.materials;
  1789. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  1790. side = object.material.side;
  1791. var a, b, c, d;
  1792. var precision = ray.precision;
  1793. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  1794. originCopy.copy( ray.origin );
  1795. objMatrix = object.matrixWorld;
  1796. inverseMatrix.getInverse( objMatrix );
  1797. localOriginCopy.copy( originCopy );
  1798. inverseMatrix.multiplyVector3( localOriginCopy );
  1799. localDirectionCopy.copy( ray.direction );
  1800. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  1801. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  1802. face = geometry.faces[ f ];
  1803. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  1804. if ( material === undefined ) continue;
  1805. side = material.side;
  1806. vector.sub( face.centroid, localOriginCopy );
  1807. normal = face.normal;
  1808. dot = localDirectionCopy.dot( normal );
  1809. // bail if ray and plane are parallel
  1810. if ( Math.abs( dot ) < precision ) continue;
  1811. // calc distance to plane
  1812. scalar = normal.dot( vector ) / dot;
  1813. // if negative distance, then plane is behind ray
  1814. if ( scalar < 0 ) continue;
  1815. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  1816. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  1817. if ( face instanceof THREE.Face3 ) {
  1818. a = vertices[ face.a ];
  1819. b = vertices[ face.b ];
  1820. c = vertices[ face.c ];
  1821. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  1822. point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1823. distance = originCopy.distanceTo( point );
  1824. if ( distance < ray.near || distance > ray.far ) continue;
  1825. intersect = {
  1826. distance: distance,
  1827. point: point,
  1828. face: face,
  1829. faceIndex: f,
  1830. object: object
  1831. };
  1832. intersects.push( intersect );
  1833. }
  1834. } else if ( face instanceof THREE.Face4 ) {
  1835. a = vertices[ face.a ];
  1836. b = vertices[ face.b ];
  1837. c = vertices[ face.c ];
  1838. d = vertices[ face.d ];
  1839. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  1840. point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  1841. distance = originCopy.distanceTo( point );
  1842. if ( distance < ray.near || distance > ray.far ) continue;
  1843. intersect = {
  1844. distance: distance,
  1845. point: point,
  1846. face: face,
  1847. faceIndex: f,
  1848. object: object
  1849. };
  1850. intersects.push( intersect );
  1851. }
  1852. }
  1853. }
  1854. }
  1855. }
  1856. };
  1857. var intersectDescendants = function ( object, ray, intersects ) {
  1858. var descendants = object.getDescendants();
  1859. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  1860. intersectObject( descendants[ i ], ray, intersects );
  1861. }
  1862. };
  1863. //
  1864. THREE.Ray.prototype.precision = 0.0001;
  1865. THREE.Ray.prototype.set = function ( origin, direction ) {
  1866. this.origin = origin;
  1867. this.direction = direction;
  1868. };
  1869. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  1870. var intersects = [];
  1871. if ( recursive === true ) {
  1872. intersectDescendants( object, this, intersects );
  1873. }
  1874. intersectObject( object, this, intersects );
  1875. intersects.sort( descSort );
  1876. return intersects;
  1877. };
  1878. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  1879. var intersects = [];
  1880. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  1881. intersectObject( objects[ i ], this, intersects );
  1882. if ( recursive === true ) {
  1883. intersectDescendants( objects[ i ], this, intersects );
  1884. }
  1885. }
  1886. intersects.sort( descSort );
  1887. return intersects;
  1888. };
  1889. }( THREE ) );
  1890. /**
  1891. * @author mrdoob / http://mrdoob.com/
  1892. */
  1893. THREE.Rectangle = function () {
  1894. var _left = 0;
  1895. var _top = 0;
  1896. var _right = 0;
  1897. var _bottom = 0;
  1898. var _width = 0;
  1899. var _height = 0;
  1900. var _isEmpty = true;
  1901. function resize() {
  1902. _width = _right - _left;
  1903. _height = _bottom - _top;
  1904. }
  1905. this.getX = function () {
  1906. return _left;
  1907. };
  1908. this.getY = function () {
  1909. return _top;
  1910. };
  1911. this.getWidth = function () {
  1912. return _width;
  1913. };
  1914. this.getHeight = function () {
  1915. return _height;
  1916. };
  1917. this.getLeft = function() {
  1918. return _left;
  1919. };
  1920. this.getTop = function() {
  1921. return _top;
  1922. };
  1923. this.getRight = function() {
  1924. return _right;
  1925. };
  1926. this.getBottom = function() {
  1927. return _bottom;
  1928. };
  1929. this.set = function ( left, top, right, bottom ) {
  1930. _isEmpty = false;
  1931. _left = left; _top = top;
  1932. _right = right; _bottom = bottom;
  1933. resize();
  1934. };
  1935. this.addPoint = function ( x, y ) {
  1936. if ( _isEmpty === true ) {
  1937. _isEmpty = false;
  1938. _left = x; _top = y;
  1939. _right = x; _bottom = y;
  1940. resize();
  1941. } else {
  1942. _left = _left < x ? _left : x; // Math.min( _left, x );
  1943. _top = _top < y ? _top : y; // Math.min( _top, y );
  1944. _right = _right > x ? _right : x; // Math.max( _right, x );
  1945. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  1946. resize();
  1947. }
  1948. };
  1949. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  1950. if ( _isEmpty === true ) {
  1951. _isEmpty = false;
  1952. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  1953. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  1954. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  1955. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  1956. resize();
  1957. } else {
  1958. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  1959. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  1960. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  1961. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  1962. resize();
  1963. };
  1964. };
  1965. this.addRectangle = function ( r ) {
  1966. if ( _isEmpty === true ) {
  1967. _isEmpty = false;
  1968. _left = r.getLeft(); _top = r.getTop();
  1969. _right = r.getRight(); _bottom = r.getBottom();
  1970. resize();
  1971. } else {
  1972. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  1973. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  1974. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  1975. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  1976. resize();
  1977. }
  1978. };
  1979. this.inflate = function ( v ) {
  1980. _left -= v; _top -= v;
  1981. _right += v; _bottom += v;
  1982. resize();
  1983. };
  1984. this.minSelf = function ( r ) {
  1985. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  1986. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  1987. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  1988. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  1989. resize();
  1990. };
  1991. this.intersects = function ( r ) {
  1992. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  1993. if ( _right < r.getLeft() ) return false;
  1994. if ( _left > r.getRight() ) return false;
  1995. if ( _bottom < r.getTop() ) return false;
  1996. if ( _top > r.getBottom() ) return false;
  1997. return true;
  1998. };
  1999. this.empty = function () {
  2000. _isEmpty = true;
  2001. _left = 0; _top = 0;
  2002. _right = 0; _bottom = 0;
  2003. resize();
  2004. };
  2005. this.isEmpty = function () {
  2006. return _isEmpty;
  2007. };
  2008. };
  2009. /**
  2010. * @author alteredq / http://alteredqualia.com/
  2011. */
  2012. THREE.Math = {
  2013. // Clamp value to range <a, b>
  2014. clamp: function ( x, a, b ) {
  2015. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2016. },
  2017. // Clamp value to range <a, inf)
  2018. clampBottom: function ( x, a ) {
  2019. return x < a ? a : x;
  2020. },
  2021. // Linear mapping from range <a1, a2> to range <b1, b2>
  2022. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2023. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2024. },
  2025. // Random float from <0, 1> with 16 bits of randomness
  2026. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2027. random16: function () {
  2028. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2029. },
  2030. // Random integer from <low, high> interval
  2031. randInt: function ( low, high ) {
  2032. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2033. },
  2034. // Random float from <low, high> interval
  2035. randFloat: function ( low, high ) {
  2036. return low + Math.random() * ( high - low );
  2037. },
  2038. // Random float from <-range/2, range/2> interval
  2039. randFloatSpread: function ( range ) {
  2040. return range * ( 0.5 - Math.random() );
  2041. },
  2042. sign: function ( x ) {
  2043. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2044. }
  2045. };
  2046. /**
  2047. * @author mrdoob / http://mrdoob.com/
  2048. * @author mikael emtinger / http://gomo.se/
  2049. * @author alteredq / http://alteredqualia.com/
  2050. */
  2051. THREE.Object3D = function () {
  2052. THREE.Object3DLibrary.push( this );
  2053. this.id = THREE.Object3DIdCount ++;
  2054. this.name = '';
  2055. this.properties = {};
  2056. this.parent = undefined;
  2057. this.children = [];
  2058. this.up = new THREE.Vector3( 0, 1, 0 );
  2059. this.position = new THREE.Vector3();
  2060. this.rotation = new THREE.Vector3();
  2061. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2062. this.scale = new THREE.Vector3( 1, 1, 1 );
  2063. this.renderDepth = null;
  2064. this.rotationAutoUpdate = true;
  2065. this.matrix = new THREE.Matrix4();
  2066. this.matrixWorld = new THREE.Matrix4();
  2067. this.matrixRotationWorld = new THREE.Matrix4();
  2068. this.matrixAutoUpdate = true;
  2069. this.matrixWorldNeedsUpdate = true;
  2070. this.quaternion = new THREE.Quaternion();
  2071. this.useQuaternion = false;
  2072. this.boundRadius = 0.0;
  2073. this.boundRadiusScale = 1.0;
  2074. this.visible = true;
  2075. this.castShadow = false;
  2076. this.receiveShadow = false;
  2077. this.frustumCulled = true;
  2078. this._vector = new THREE.Vector3();
  2079. };
  2080. THREE.Object3D.prototype = {
  2081. constructor: THREE.Object3D,
  2082. applyMatrix: function ( matrix ) {
  2083. this.matrix.multiply( matrix, this.matrix );
  2084. this.scale.getScaleFromMatrix( this.matrix );
  2085. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2086. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2087. this.position.getPositionFromMatrix( this.matrix );
  2088. },
  2089. translate: function ( distance, axis ) {
  2090. this.matrix.rotateAxis( axis );
  2091. this.position.addSelf( axis.multiplyScalar( distance ) );
  2092. },
  2093. translateX: function ( distance ) {
  2094. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2095. },
  2096. translateY: function ( distance ) {
  2097. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2098. },
  2099. translateZ: function ( distance ) {
  2100. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2101. },
  2102. localToWorld: function ( vector ) {
  2103. return this.matrixWorld.multiplyVector3( vector );
  2104. },
  2105. worldToLocal: function ( vector ) {
  2106. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2107. },
  2108. lookAt: function ( vector ) {
  2109. // TODO: Add hierarchy support.
  2110. this.matrix.lookAt( vector, this.position, this.up );
  2111. if ( this.rotationAutoUpdate ) {
  2112. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2113. }
  2114. },
  2115. add: function ( object ) {
  2116. if ( object === this ) {
  2117. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2118. return;
  2119. }
  2120. if ( object instanceof THREE.Object3D ) {
  2121. if ( object.parent !== undefined ) {
  2122. object.parent.remove( object );
  2123. }
  2124. object.parent = this;
  2125. this.children.push( object );
  2126. // add to scene
  2127. var scene = this;
  2128. while ( scene.parent !== undefined ) {
  2129. scene = scene.parent;
  2130. }
  2131. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2132. scene.__addObject( object );
  2133. }
  2134. }
  2135. },
  2136. remove: function ( object ) {
  2137. var index = this.children.indexOf( object );
  2138. if ( index !== - 1 ) {
  2139. object.parent = undefined;
  2140. this.children.splice( index, 1 );
  2141. // remove from scene
  2142. var scene = this;
  2143. while ( scene.parent !== undefined ) {
  2144. scene = scene.parent;
  2145. }
  2146. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2147. scene.__removeObject( object );
  2148. }
  2149. }
  2150. },
  2151. traverse: function ( callback ) {
  2152. callback( this );
  2153. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2154. this.children[ i ].traverse( callback );
  2155. }
  2156. },
  2157. getChildByName: function ( name, recursive ) {
  2158. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2159. var child = this.children[ i ];
  2160. if ( child.name === name ) {
  2161. return child;
  2162. }
  2163. if ( recursive === true ) {
  2164. child = child.getChildByName( name, recursive );
  2165. if ( child !== undefined ) {
  2166. return child;
  2167. }
  2168. }
  2169. }
  2170. return undefined;
  2171. },
  2172. getDescendants: function ( array ) {
  2173. if ( array === undefined ) array = [];
  2174. Array.prototype.push.apply( array, this.children );
  2175. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2176. this.children[ i ].getDescendants( array );
  2177. }
  2178. return array;
  2179. },
  2180. updateMatrix: function () {
  2181. this.matrix.setPosition( this.position );
  2182. if ( this.useQuaternion === false ) {
  2183. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2184. } else {
  2185. this.matrix.setRotationFromQuaternion( this.quaternion );
  2186. }
  2187. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2188. this.matrix.scale( this.scale );
  2189. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2190. }
  2191. this.matrixWorldNeedsUpdate = true;
  2192. },
  2193. updateMatrixWorld: function ( force ) {
  2194. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2195. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2196. if ( this.parent === undefined ) {
  2197. this.matrixWorld.copy( this.matrix );
  2198. } else {
  2199. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2200. }
  2201. this.matrixWorldNeedsUpdate = false;
  2202. force = true;
  2203. }
  2204. // update children
  2205. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2206. this.children[ i ].updateMatrixWorld( force );
  2207. }
  2208. },
  2209. clone: function ( object ) {
  2210. if ( object === undefined ) object = new THREE.Object3D();
  2211. object.name = this.name;
  2212. object.up.copy( this.up );
  2213. object.position.copy( this.position );
  2214. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2215. object.eulerOrder = this.eulerOrder;
  2216. object.scale.copy( this.scale );
  2217. object.renderDepth = this.renderDepth;
  2218. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2219. object.matrix.copy( this.matrix );
  2220. object.matrixWorld.copy( this.matrixWorld );
  2221. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2222. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2223. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2224. object.quaternion.copy( this.quaternion );
  2225. object.useQuaternion = this.useQuaternion;
  2226. object.boundRadius = this.boundRadius;
  2227. object.boundRadiusScale = this.boundRadiusScale;
  2228. object.visible = this.visible;
  2229. object.castShadow = this.castShadow;
  2230. object.receiveShadow = this.receiveShadow;
  2231. object.frustumCulled = this.frustumCulled;
  2232. return object;
  2233. },
  2234. deallocate: function () {
  2235. var index = THREE.Object3DLibrary.indexOf( this );
  2236. if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
  2237. }
  2238. };
  2239. THREE.Object3D.__m1 = new THREE.Matrix4();
  2240. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2241. THREE.Object3DIdCount = 0;
  2242. THREE.Object3DLibrary = [];
  2243. /**
  2244. * @author mrdoob / http://mrdoob.com/
  2245. * @author supereggbert / http://www.paulbrunt.co.uk/
  2246. * @author julianwa / https://github.com/julianwa
  2247. */
  2248. THREE.Projector = function() {
  2249. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2250. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  2251. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  2252. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  2253. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  2254. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  2255. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  2256. _vector3 = new THREE.Vector3(),
  2257. _vector4 = new THREE.Vector4(),
  2258. _viewProjectionMatrix = new THREE.Matrix4(),
  2259. _modelViewProjectionMatrix = new THREE.Matrix4(),
  2260. _frustum = new THREE.Frustum(),
  2261. _clippedVertex1PositionScreen = new THREE.Vector4(),
  2262. _clippedVertex2PositionScreen = new THREE.Vector4(),
  2263. _face3VertexNormals;
  2264. this.projectVector = function ( vector, camera ) {
  2265. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2266. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2267. _viewProjectionMatrix.multiplyVector3( vector );
  2268. return vector;
  2269. };
  2270. this.unprojectVector = function ( vector, camera ) {
  2271. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  2272. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  2273. _viewProjectionMatrix.multiplyVector3( vector );
  2274. return vector;
  2275. };
  2276. this.pickingRay = function ( vector, camera ) {
  2277. var end, ray, t;
  2278. // set two vectors with opposing z values
  2279. vector.z = -1.0;
  2280. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  2281. this.unprojectVector( vector, camera );
  2282. this.unprojectVector( end, camera );
  2283. // find direction from vector to end
  2284. end.subSelf( vector ).normalize();
  2285. return new THREE.Ray( vector, end );
  2286. };
  2287. var projectGraph = function ( root, sortObjects ) {
  2288. _objectCount = 0;
  2289. _renderData.objects.length = 0;
  2290. _renderData.sprites.length = 0;
  2291. _renderData.lights.length = 0;
  2292. var projectObject = function ( parent ) {
  2293. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  2294. var object = parent.children[ c ];
  2295. if ( object.visible === false ) continue;
  2296. if ( object instanceof THREE.Light ) {
  2297. _renderData.lights.push( object );
  2298. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  2299. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  2300. _object = getNextObjectInPool();
  2301. _object.object = object;
  2302. if ( object.renderDepth !== null ) {
  2303. _object.z = object.renderDepth;
  2304. } else {
  2305. _vector3.copy( object.matrixWorld.getPosition() );
  2306. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2307. _object.z = _vector3.z;
  2308. }
  2309. _renderData.objects.push( _object );
  2310. }
  2311. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  2312. _object = getNextObjectInPool();
  2313. _object.object = object;
  2314. // TODO: Find an elegant and performant solution and remove this dupe code.
  2315. if ( object.renderDepth !== null ) {
  2316. _object.z = object.renderDepth;
  2317. } else {
  2318. _vector3.copy( object.matrixWorld.getPosition() );
  2319. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2320. _object.z = _vector3.z;
  2321. }
  2322. _renderData.sprites.push( _object );
  2323. } else {
  2324. _object = getNextObjectInPool();
  2325. _object.object = object;
  2326. if ( object.renderDepth !== null ) {
  2327. _object.z = object.renderDepth;
  2328. } else {
  2329. _vector3.copy( object.matrixWorld.getPosition() );
  2330. _viewProjectionMatrix.multiplyVector3( _vector3 );
  2331. _object.z = _vector3.z;
  2332. }
  2333. _renderData.objects.push( _object );
  2334. }
  2335. projectObject( object );
  2336. }
  2337. };
  2338. projectObject( root );
  2339. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  2340. return _renderData;
  2341. };
  2342. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  2343. var near = camera.near, far = camera.far, visible = false,
  2344. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  2345. modelMatrix, rotationMatrix,
  2346. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  2347. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  2348. v1, v2, v3, v4, isFaceMaterial, material, side;
  2349. _face3Count = 0;
  2350. _face4Count = 0;
  2351. _lineCount = 0;
  2352. _particleCount = 0;
  2353. _renderData.elements.length = 0;
  2354. scene.updateMatrixWorld();
  2355. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  2356. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  2357. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  2358. _frustum.setFromMatrix( _viewProjectionMatrix );
  2359. _renderData = projectGraph( scene, sortObjects );
  2360. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  2361. object = _renderData.objects[ o ].object;
  2362. modelMatrix = object.matrixWorld;
  2363. _vertexCount = 0;
  2364. if ( object instanceof THREE.Mesh ) {
  2365. geometry = object.geometry;
  2366. geometryMaterials = object.geometry.materials;
  2367. vertices = geometry.vertices;
  2368. faces = geometry.faces;
  2369. faceVertexUvs = geometry.faceVertexUvs;
  2370. rotationMatrix = object.matrixRotationWorld.extractRotation( modelMatrix );
  2371. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2372. side = object.material.side;
  2373. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  2374. _vertex = getNextVertexInPool();
  2375. _vertex.positionWorld.copy( vertices[ v ] );
  2376. modelMatrix.multiplyVector3( _vertex.positionWorld );
  2377. _vertex.positionScreen.copy( _vertex.positionWorld );
  2378. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  2379. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  2380. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  2381. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  2382. }
  2383. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  2384. face = faces[ f ];
  2385. material = isFaceMaterial === true ? geometryMaterials[ face.materialIndex ] : object.material;
  2386. if ( material === undefined ) continue;
  2387. side = material.side;
  2388. if ( face instanceof THREE.Face3 ) {
  2389. v1 = _vertexPool[ face.a ];
  2390. v2 = _vertexPool[ face.b ];
  2391. v3 = _vertexPool[ face.c ];
  2392. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  2393. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2394. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  2395. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2396. _face = getNextFace3InPool();
  2397. _face.v1.copy( v1 );
  2398. _face.v2.copy( v2 );
  2399. _face.v3.copy( v3 );
  2400. } else {
  2401. continue;
  2402. }
  2403. } else {
  2404. continue;
  2405. }
  2406. } else if ( face instanceof THREE.Face4 ) {
  2407. v1 = _vertexPool[ face.a ];
  2408. v2 = _vertexPool[ face.b ];
  2409. v3 = _vertexPool[ face.c ];
  2410. v4 = _vertexPool[ face.d ];
  2411. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  2412. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  2413. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  2414. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  2415. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  2416. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  2417. _face = getNextFace4InPool();
  2418. _face.v1.copy( v1 );
  2419. _face.v2.copy( v2 );
  2420. _face.v3.copy( v3 );
  2421. _face.v4.copy( v4 );
  2422. } else {
  2423. continue;
  2424. }
  2425. } else {
  2426. continue;
  2427. }
  2428. }
  2429. _face.normalWorld.copy( face.normal );
  2430. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  2431. rotationMatrix.multiplyVector3( _face.normalWorld );
  2432. _face.centroidWorld.copy( face.centroid );
  2433. modelMatrix.multiplyVector3( _face.centroidWorld );
  2434. _face.centroidScreen.copy( _face.centroidWorld );
  2435. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  2436. faceVertexNormals = face.vertexNormals;
  2437. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  2438. normal = _face.vertexNormalsWorld[ n ];
  2439. normal.copy( faceVertexNormals[ n ] );
  2440. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  2441. rotationMatrix.multiplyVector3( normal );
  2442. }
  2443. _face.vertexNormalsLength = faceVertexNormals.length;
  2444. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  2445. uvs = faceVertexUvs[ c ][ f ];
  2446. if ( uvs === undefined ) continue;
  2447. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2448. _face.uvs[ c ][ u ] = uvs[ u ];
  2449. }
  2450. }
  2451. _face.color = face.color;
  2452. _face.material = material;
  2453. _face.z = _face.centroidScreen.z;
  2454. _renderData.elements.push( _face );
  2455. }
  2456. } else if ( object instanceof THREE.Line ) {
  2457. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  2458. vertices = object.geometry.vertices;
  2459. v1 = getNextVertexInPool();
  2460. v1.positionScreen.copy( vertices[ 0 ] );
  2461. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2462. // Handle LineStrip and LinePieces
  2463. var step = object.type === THREE.LinePieces ? 2 : 1;
  2464. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2465. v1 = getNextVertexInPool();
  2466. v1.positionScreen.copy( vertices[ v ] );
  2467. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  2468. if ( ( v + 1 ) % step > 0 ) continue;
  2469. v2 = _vertexPool[ _vertexCount - 2 ];
  2470. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2471. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2472. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  2473. // Perform the perspective divide
  2474. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2475. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2476. _line = getNextLineInPool();
  2477. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2478. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2479. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2480. _line.material = object.material;
  2481. _renderData.elements.push( _line );
  2482. }
  2483. }
  2484. }
  2485. }
  2486. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2487. object = _renderData.sprites[ o ].object;
  2488. modelMatrix = object.matrixWorld;
  2489. if ( object instanceof THREE.Particle ) {
  2490. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  2491. _viewProjectionMatrix.multiplyVector4( _vector4 );
  2492. _vector4.z /= _vector4.w;
  2493. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2494. _particle = getNextParticleInPool();
  2495. _particle.object = object;
  2496. _particle.x = _vector4.x / _vector4.w;
  2497. _particle.y = _vector4.y / _vector4.w;
  2498. _particle.z = _vector4.z;
  2499. _particle.rotation = object.rotation.z;
  2500. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2501. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2502. _particle.material = object.material;
  2503. _renderData.elements.push( _particle );
  2504. }
  2505. }
  2506. }
  2507. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  2508. return _renderData;
  2509. };
  2510. // Pools
  2511. function getNextObjectInPool() {
  2512. if ( _objectCount === _objectPoolLength ) {
  2513. var object = new THREE.RenderableObject();
  2514. _objectPool.push( object );
  2515. _objectPoolLength ++;
  2516. _objectCount ++;
  2517. return object;
  2518. }
  2519. return _objectPool[ _objectCount ++ ];
  2520. }
  2521. function getNextVertexInPool() {
  2522. if ( _vertexCount === _vertexPoolLength ) {
  2523. var vertex = new THREE.RenderableVertex();
  2524. _vertexPool.push( vertex );
  2525. _vertexPoolLength ++;
  2526. _vertexCount ++;
  2527. return vertex;
  2528. }
  2529. return _vertexPool[ _vertexCount ++ ];
  2530. }
  2531. function getNextFace3InPool() {
  2532. if ( _face3Count === _face3PoolLength ) {
  2533. var face = new THREE.RenderableFace3();
  2534. _face3Pool.push( face );
  2535. _face3PoolLength ++;
  2536. _face3Count ++;
  2537. return face;
  2538. }
  2539. return _face3Pool[ _face3Count ++ ];
  2540. }
  2541. function getNextFace4InPool() {
  2542. if ( _face4Count === _face4PoolLength ) {
  2543. var face = new THREE.RenderableFace4();
  2544. _face4Pool.push( face );
  2545. _face4PoolLength ++;
  2546. _face4Count ++;
  2547. return face;
  2548. }
  2549. return _face4Pool[ _face4Count ++ ];
  2550. }
  2551. function getNextLineInPool() {
  2552. if ( _lineCount === _linePoolLength ) {
  2553. var line = new THREE.RenderableLine();
  2554. _linePool.push( line );
  2555. _linePoolLength ++;
  2556. _lineCount ++
  2557. return line;
  2558. }
  2559. return _linePool[ _lineCount ++ ];
  2560. }
  2561. function getNextParticleInPool() {
  2562. if ( _particleCount === _particlePoolLength ) {
  2563. var particle = new THREE.RenderableParticle();
  2564. _particlePool.push( particle );
  2565. _particlePoolLength ++;
  2566. _particleCount ++
  2567. return particle;
  2568. }
  2569. return _particlePool[ _particleCount ++ ];
  2570. }
  2571. //
  2572. function painterSort( a, b ) {
  2573. return b.z - a.z;
  2574. }
  2575. function clipLine( s1, s2 ) {
  2576. var alpha1 = 0, alpha2 = 1,
  2577. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2578. // Z = -1 and Z = +1, respectively.
  2579. bc1near = s1.z + s1.w,
  2580. bc2near = s2.z + s2.w,
  2581. bc1far = - s1.z + s1.w,
  2582. bc2far = - s2.z + s2.w;
  2583. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2584. // Both vertices lie entirely within all clip planes.
  2585. return true;
  2586. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2587. // Both vertices lie entirely outside one of the clip planes.
  2588. return false;
  2589. } else {
  2590. // The line segment spans at least one clip plane.
  2591. if ( bc1near < 0 ) {
  2592. // v1 lies outside the near plane, v2 inside
  2593. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2594. } else if ( bc2near < 0 ) {
  2595. // v2 lies outside the near plane, v1 inside
  2596. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2597. }
  2598. if ( bc1far < 0 ) {
  2599. // v1 lies outside the far plane, v2 inside
  2600. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2601. } else if ( bc2far < 0 ) {
  2602. // v2 lies outside the far plane, v2 inside
  2603. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2604. }
  2605. if ( alpha2 < alpha1 ) {
  2606. // The line segment spans two boundaries, but is outside both of them.
  2607. // (This can't happen when we're only clipping against just near/far but good
  2608. // to leave the check here for future usage if other clip planes are added.)
  2609. return false;
  2610. } else {
  2611. // Update the s1 and s2 vertices to match the clipped line segment.
  2612. s1.lerpSelf( s2, alpha1 );
  2613. s2.lerpSelf( s1, 1 - alpha2 );
  2614. return true;
  2615. }
  2616. }
  2617. }
  2618. };
  2619. /**
  2620. * @author mikael emtinger / http://gomo.se/
  2621. * @author alteredq / http://alteredqualia.com/
  2622. * @author WestLangley / http://github.com/WestLangley
  2623. */
  2624. THREE.Quaternion = function( x, y, z, w ) {
  2625. this.x = x || 0;
  2626. this.y = y || 0;
  2627. this.z = z || 0;
  2628. this.w = ( w !== undefined ) ? w : 1;
  2629. };
  2630. THREE.Quaternion.prototype = {
  2631. constructor: THREE.Quaternion,
  2632. set: function ( x, y, z, w ) {
  2633. this.x = x;
  2634. this.y = y;
  2635. this.z = z;
  2636. this.w = w;
  2637. return this;
  2638. },
  2639. copy: function ( q ) {
  2640. this.x = q.x;
  2641. this.y = q.y;
  2642. this.z = q.z;
  2643. this.w = q.w;
  2644. return this;
  2645. },
  2646. setFromEuler: function ( v, order ) {
  2647. // http://www.mathworks.com/matlabcentral/fileexchange/
  2648. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  2649. // content/SpinCalc.m
  2650. var c1 = Math.cos( v.x / 2 );
  2651. var c2 = Math.cos( v.y / 2 );
  2652. var c3 = Math.cos( v.z / 2 );
  2653. var s1 = Math.sin( v.x / 2 );
  2654. var s2 = Math.sin( v.y / 2 );
  2655. var s3 = Math.sin( v.z / 2 );
  2656. if ( order === undefined || order === 'XYZ' ) {
  2657. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2658. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2659. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2660. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2661. } else if ( order === 'YXZ' ) {
  2662. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2663. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2664. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2665. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2666. } else if ( order === 'ZXY' ) {
  2667. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2668. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2669. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2670. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2671. } else if ( order === 'ZYX' ) {
  2672. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2673. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2674. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2675. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2676. } else if ( order === 'YZX' ) {
  2677. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  2678. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  2679. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  2680. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  2681. } else if ( order === 'XZY' ) {
  2682. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  2683. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  2684. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  2685. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  2686. }
  2687. return this;
  2688. },
  2689. setFromAxisAngle: function ( axis, angle ) {
  2690. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2691. // axis have to be normalized
  2692. var halfAngle = angle / 2,
  2693. s = Math.sin( halfAngle );
  2694. this.x = axis.x * s;
  2695. this.y = axis.y * s;
  2696. this.z = axis.z * s;
  2697. this.w = Math.cos( halfAngle );
  2698. return this;
  2699. },
  2700. setFromRotationMatrix: function ( m ) {
  2701. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2702. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  2703. var te = m.elements,
  2704. m11 = te[0], m12 = te[4], m13 = te[8],
  2705. m21 = te[1], m22 = te[5], m23 = te[9],
  2706. m31 = te[2], m32 = te[6], m33 = te[10],
  2707. trace = m11 + m22 + m33,
  2708. s;
  2709. if( trace > 0 ) {
  2710. s = 0.5 / Math.sqrt( trace + 1.0 );
  2711. this.w = 0.25 / s;
  2712. this.x = ( m32 - m23 ) * s;
  2713. this.y = ( m13 - m31 ) * s;
  2714. this.z = ( m21 - m12 ) * s;
  2715. } else if ( m11 > m22 && m11 > m33 ) {
  2716. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  2717. this.w = (m32 - m23 ) / s;
  2718. this.x = 0.25 * s;
  2719. this.y = (m12 + m21 ) / s;
  2720. this.z = (m13 + m31 ) / s;
  2721. } else if (m22 > m33) {
  2722. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  2723. this.w = (m13 - m31 ) / s;
  2724. this.x = (m12 + m21 ) / s;
  2725. this.y = 0.25 * s;
  2726. this.z = (m23 + m32 ) / s;
  2727. } else {
  2728. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  2729. this.w = ( m21 - m12 ) / s;
  2730. this.x = ( m13 + m31 ) / s;
  2731. this.y = ( m23 + m32 ) / s;
  2732. this.z = 0.25 * s;
  2733. }
  2734. return this;
  2735. },
  2736. calculateW : function () {
  2737. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2738. return this;
  2739. },
  2740. inverse: function () {
  2741. this.x *= -1;
  2742. this.y *= -1;
  2743. this.z *= -1;
  2744. return this;
  2745. },
  2746. length: function () {
  2747. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2748. },
  2749. normalize: function () {
  2750. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2751. if ( l === 0 ) {
  2752. this.x = 0;
  2753. this.y = 0;
  2754. this.z = 0;
  2755. this.w = 0;
  2756. } else {
  2757. l = 1 / l;
  2758. this.x = this.x * l;
  2759. this.y = this.y * l;
  2760. this.z = this.z * l;
  2761. this.w = this.w * l;
  2762. }
  2763. return this;
  2764. },
  2765. multiply: function ( a, b ) {
  2766. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2767. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  2768. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2769. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  2770. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  2771. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  2772. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  2773. return this;
  2774. },
  2775. multiplySelf: function ( b ) {
  2776. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2777. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2778. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2779. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2780. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2781. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2782. return this;
  2783. },
  2784. multiplyVector3: function ( vector, dest ) {
  2785. if ( !dest ) { dest = vector; }
  2786. var x = vector.x, y = vector.y, z = vector.z,
  2787. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2788. // calculate quat * vector
  2789. var ix = qw * x + qy * z - qz * y,
  2790. iy = qw * y + qz * x - qx * z,
  2791. iz = qw * z + qx * y - qy * x,
  2792. iw = -qx * x - qy * y - qz * z;
  2793. // calculate result * inverse quat
  2794. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2795. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2796. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2797. return dest;
  2798. },
  2799. slerpSelf: function ( qb, t ) {
  2800. var x = this.x, y = this.y, z = this.z, w = this.w;
  2801. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2802. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  2803. if ( cosHalfTheta < 0 ) {
  2804. this.w = -qb.w;
  2805. this.x = -qb.x;
  2806. this.y = -qb.y;
  2807. this.z = -qb.z;
  2808. cosHalfTheta = -cosHalfTheta;
  2809. } else {
  2810. this.copy( qb );
  2811. }
  2812. if ( cosHalfTheta >= 1.0 ) {
  2813. this.w = w;
  2814. this.x = x;
  2815. this.y = y;
  2816. this.z = z;
  2817. return this;
  2818. }
  2819. var halfTheta = Math.acos( cosHalfTheta );
  2820. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2821. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2822. this.w = 0.5 * ( w + this.w );
  2823. this.x = 0.5 * ( x + this.x );
  2824. this.y = 0.5 * ( y + this.y );
  2825. this.z = 0.5 * ( z + this.z );
  2826. return this;
  2827. }
  2828. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2829. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2830. this.w = ( w * ratioA + this.w * ratioB );
  2831. this.x = ( x * ratioA + this.x * ratioB );
  2832. this.y = ( y * ratioA + this.y * ratioB );
  2833. this.z = ( z * ratioA + this.z * ratioB );
  2834. return this;
  2835. },
  2836. clone: function () {
  2837. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2838. }
  2839. }
  2840. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2841. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2842. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2843. if ( cosHalfTheta < 0 ) {
  2844. qm.w = -qb.w;
  2845. qm.x = -qb.x;
  2846. qm.y = -qb.y;
  2847. qm.z = -qb.z;
  2848. cosHalfTheta = -cosHalfTheta;
  2849. } else {
  2850. qm.copy( qb );
  2851. }
  2852. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2853. qm.w = qa.w;
  2854. qm.x = qa.x;
  2855. qm.y = qa.y;
  2856. qm.z = qa.z;
  2857. return qm;
  2858. }
  2859. var halfTheta = Math.acos( cosHalfTheta );
  2860. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2861. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2862. qm.w = 0.5 * ( qa.w + qm.w );
  2863. qm.x = 0.5 * ( qa.x + qm.x );
  2864. qm.y = 0.5 * ( qa.y + qm.y );
  2865. qm.z = 0.5 * ( qa.z + qm.z );
  2866. return qm;
  2867. }
  2868. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  2869. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2870. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2871. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2872. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2873. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2874. return qm;
  2875. }
  2876. /**
  2877. * @author mrdoob / http://mrdoob.com/
  2878. */
  2879. THREE.Vertex = function ( v ) {
  2880. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  2881. return v;
  2882. };
  2883. /**
  2884. * @author mrdoob / http://mrdoob.com/
  2885. * @author alteredq / http://alteredqualia.com/
  2886. */
  2887. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2888. this.a = a;
  2889. this.b = b;
  2890. this.c = c;
  2891. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2892. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2893. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2894. this.vertexColors = color instanceof Array ? color : [];
  2895. this.vertexTangents = [];
  2896. this.materialIndex = materialIndex;
  2897. this.centroid = new THREE.Vector3();
  2898. };
  2899. THREE.Face3.prototype = {
  2900. constructor: THREE.Face3,
  2901. clone: function () {
  2902. var face = new THREE.Face3( this.a, this.b, this.c );
  2903. face.normal.copy( this.normal );
  2904. face.color.copy( this.color );
  2905. face.centroid.copy( this.centroid );
  2906. face.materialIndex = this.materialIndex;
  2907. var i, il;
  2908. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2909. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2910. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2911. return face;
  2912. }
  2913. };
  2914. /**
  2915. * @author mrdoob / http://mrdoob.com/
  2916. * @author alteredq / http://alteredqualia.com/
  2917. */
  2918. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2919. this.a = a;
  2920. this.b = b;
  2921. this.c = c;
  2922. this.d = d;
  2923. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2924. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2925. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2926. this.vertexColors = color instanceof Array ? color : [];
  2927. this.vertexTangents = [];
  2928. this.materialIndex = materialIndex;
  2929. this.centroid = new THREE.Vector3();
  2930. };
  2931. THREE.Face4.prototype = {
  2932. constructor: THREE.Face4,
  2933. clone: function () {
  2934. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2935. face.normal.copy( this.normal );
  2936. face.color.copy( this.color );
  2937. face.centroid.copy( this.centroid );
  2938. face.materialIndex = this.materialIndex;
  2939. var i, il;
  2940. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2941. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2942. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2943. return face;
  2944. }
  2945. };
  2946. /**
  2947. * @author mrdoob / http://mrdoob.com/
  2948. */
  2949. THREE.UV = function ( u, v ) {
  2950. this.u = u || 0;
  2951. this.v = v || 0;
  2952. };
  2953. THREE.UV.prototype = {
  2954. constructor: THREE.UV,
  2955. set: function ( u, v ) {
  2956. this.u = u;
  2957. this.v = v;
  2958. return this;
  2959. },
  2960. copy: function ( uv ) {
  2961. this.u = uv.u;
  2962. this.v = uv.v;
  2963. return this;
  2964. },
  2965. lerpSelf: function ( uv, alpha ) {
  2966. this.u += ( uv.u - this.u ) * alpha;
  2967. this.v += ( uv.v - this.v ) * alpha;
  2968. return this;
  2969. },
  2970. clone: function () {
  2971. return new THREE.UV( this.u, this.v );
  2972. }
  2973. };
  2974. /**
  2975. * @author mrdoob / http://mrdoob.com/
  2976. * @author kile / http://kile.stravaganza.org/
  2977. * @author alteredq / http://alteredqualia.com/
  2978. * @author mikael emtinger / http://gomo.se/
  2979. * @author zz85 / http://www.lab4games.net/zz85/blog
  2980. */
  2981. THREE.Geometry = function () {
  2982. THREE.GeometryLibrary.push( this );
  2983. this.id = THREE.GeometryIdCount ++;
  2984. this.name = '';
  2985. this.vertices = [];
  2986. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2987. this.materials = [];
  2988. this.faces = [];
  2989. this.faceUvs = [[]];
  2990. this.faceVertexUvs = [[]];
  2991. this.morphTargets = [];
  2992. this.morphColors = [];
  2993. this.morphNormals = [];
  2994. this.skinWeights = [];
  2995. this.skinIndices = [];
  2996. this.boundingBox = null;
  2997. this.boundingSphere = null;
  2998. this.hasTangents = false;
  2999. this.dynamic = true; // the intermediate typearrays will be deleted when set to false
  3000. // update flags
  3001. this.verticesNeedUpdate = false;
  3002. this.elementsNeedUpdate = false;
  3003. this.uvsNeedUpdate = false;
  3004. this.normalsNeedUpdate = false;
  3005. this.tangentsNeedUpdate = false;
  3006. this.colorsNeedUpdate = false;
  3007. };
  3008. THREE.Geometry.prototype = {
  3009. constructor : THREE.Geometry,
  3010. applyMatrix: function ( matrix ) {
  3011. var matrixRotation = new THREE.Matrix4();
  3012. matrixRotation.extractRotation( matrix );
  3013. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3014. var vertex = this.vertices[ i ];
  3015. matrix.multiplyVector3( vertex );
  3016. }
  3017. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3018. var face = this.faces[ i ];
  3019. matrixRotation.multiplyVector3( face.normal );
  3020. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3021. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  3022. }
  3023. matrix.multiplyVector3( face.centroid );
  3024. }
  3025. },
  3026. computeCentroids: function () {
  3027. var f, fl, face;
  3028. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3029. face = this.faces[ f ];
  3030. face.centroid.set( 0, 0, 0 );
  3031. if ( face instanceof THREE.Face3 ) {
  3032. face.centroid.addSelf( this.vertices[ face.a ] );
  3033. face.centroid.addSelf( this.vertices[ face.b ] );
  3034. face.centroid.addSelf( this.vertices[ face.c ] );
  3035. face.centroid.divideScalar( 3 );
  3036. } else if ( face instanceof THREE.Face4 ) {
  3037. face.centroid.addSelf( this.vertices[ face.a ] );
  3038. face.centroid.addSelf( this.vertices[ face.b ] );
  3039. face.centroid.addSelf( this.vertices[ face.c ] );
  3040. face.centroid.addSelf( this.vertices[ face.d ] );
  3041. face.centroid.divideScalar( 4 );
  3042. }
  3043. }
  3044. },
  3045. computeFaceNormals: function () {
  3046. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3047. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3048. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3049. face = this.faces[ f ];
  3050. vA = this.vertices[ face.a ];
  3051. vB = this.vertices[ face.b ];
  3052. vC = this.vertices[ face.c ];
  3053. cb.sub( vC, vB );
  3054. ab.sub( vA, vB );
  3055. cb.crossSelf( ab );
  3056. if ( !cb.isZero() ) {
  3057. cb.normalize();
  3058. }
  3059. face.normal.copy( cb );
  3060. }
  3061. },
  3062. computeVertexNormals: function () {
  3063. var v, vl, f, fl, face, vertices;
  3064. // create internal buffers for reuse when calling this method repeatedly
  3065. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3066. if ( this.__tmpVertices === undefined ) {
  3067. this.__tmpVertices = new Array( this.vertices.length );
  3068. vertices = this.__tmpVertices;
  3069. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3070. vertices[ v ] = new THREE.Vector3();
  3071. }
  3072. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3073. face = this.faces[ f ];
  3074. if ( face instanceof THREE.Face3 ) {
  3075. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3076. } else if ( face instanceof THREE.Face4 ) {
  3077. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3078. }
  3079. }
  3080. } else {
  3081. vertices = this.__tmpVertices;
  3082. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3083. vertices[ v ].set( 0, 0, 0 );
  3084. }
  3085. }
  3086. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3087. face = this.faces[ f ];
  3088. if ( face instanceof THREE.Face3 ) {
  3089. vertices[ face.a ].addSelf( face.normal );
  3090. vertices[ face.b ].addSelf( face.normal );
  3091. vertices[ face.c ].addSelf( face.normal );
  3092. } else if ( face instanceof THREE.Face4 ) {
  3093. vertices[ face.a ].addSelf( face.normal );
  3094. vertices[ face.b ].addSelf( face.normal );
  3095. vertices[ face.c ].addSelf( face.normal );
  3096. vertices[ face.d ].addSelf( face.normal );
  3097. }
  3098. }
  3099. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3100. vertices[ v ].normalize();
  3101. }
  3102. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3103. face = this.faces[ f ];
  3104. if ( face instanceof THREE.Face3 ) {
  3105. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3106. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3107. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3108. } else if ( face instanceof THREE.Face4 ) {
  3109. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3110. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3111. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3112. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3113. }
  3114. }
  3115. },
  3116. computeMorphNormals: function () {
  3117. var i, il, f, fl, face;
  3118. // save original normals
  3119. // - create temp variables on first access
  3120. // otherwise just copy (for faster repeated calls)
  3121. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3122. face = this.faces[ f ];
  3123. if ( ! face.__originalFaceNormal ) {
  3124. face.__originalFaceNormal = face.normal.clone();
  3125. } else {
  3126. face.__originalFaceNormal.copy( face.normal );
  3127. }
  3128. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3129. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3130. if ( ! face.__originalVertexNormals[ i ] ) {
  3131. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3132. } else {
  3133. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3134. }
  3135. }
  3136. }
  3137. // use temp geometry to compute face and vertex normals for each morph
  3138. var tmpGeo = new THREE.Geometry();
  3139. tmpGeo.faces = this.faces;
  3140. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3141. // create on first access
  3142. if ( ! this.morphNormals[ i ] ) {
  3143. this.morphNormals[ i ] = {};
  3144. this.morphNormals[ i ].faceNormals = [];
  3145. this.morphNormals[ i ].vertexNormals = [];
  3146. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3147. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3148. var faceNormal, vertexNormals;
  3149. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3150. face = this.faces[ f ];
  3151. faceNormal = new THREE.Vector3();
  3152. if ( face instanceof THREE.Face3 ) {
  3153. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3154. } else {
  3155. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3156. }
  3157. dstNormalsFace.push( faceNormal );
  3158. dstNormalsVertex.push( vertexNormals );
  3159. }
  3160. }
  3161. var morphNormals = this.morphNormals[ i ];
  3162. // set vertices to morph target
  3163. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3164. // compute morph normals
  3165. tmpGeo.computeFaceNormals();
  3166. tmpGeo.computeVertexNormals();
  3167. // store morph normals
  3168. var faceNormal, vertexNormals;
  3169. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3170. face = this.faces[ f ];
  3171. faceNormal = morphNormals.faceNormals[ f ];
  3172. vertexNormals = morphNormals.vertexNormals[ f ];
  3173. faceNormal.copy( face.normal );
  3174. if ( face instanceof THREE.Face3 ) {
  3175. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3176. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3177. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3178. } else {
  3179. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3180. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3181. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3182. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3183. }
  3184. }
  3185. }
  3186. // restore original normals
  3187. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3188. face = this.faces[ f ];
  3189. face.normal = face.__originalFaceNormal;
  3190. face.vertexNormals = face.__originalVertexNormals;
  3191. }
  3192. },
  3193. computeTangents: function () {
  3194. // based on http://www.terathon.com/code/tangent.html
  3195. // tangents go to vertices
  3196. var f, fl, v, vl, i, il, vertexIndex,
  3197. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3198. x1, x2, y1, y2, z1, z2,
  3199. s1, s2, t1, t2, r, t, test,
  3200. tan1 = [], tan2 = [],
  3201. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3202. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3203. n = new THREE.Vector3(), w;
  3204. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3205. tan1[ v ] = new THREE.Vector3();
  3206. tan2[ v ] = new THREE.Vector3();
  3207. }
  3208. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  3209. vA = context.vertices[ a ];
  3210. vB = context.vertices[ b ];
  3211. vC = context.vertices[ c ];
  3212. uvA = uv[ ua ];
  3213. uvB = uv[ ub ];
  3214. uvC = uv[ uc ];
  3215. x1 = vB.x - vA.x;
  3216. x2 = vC.x - vA.x;
  3217. y1 = vB.y - vA.y;
  3218. y2 = vC.y - vA.y;
  3219. z1 = vB.z - vA.z;
  3220. z2 = vC.z - vA.z;
  3221. s1 = uvB.u - uvA.u;
  3222. s2 = uvC.u - uvA.u;
  3223. t1 = uvB.v - uvA.v;
  3224. t2 = uvC.v - uvA.v;
  3225. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3226. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  3227. ( t2 * y1 - t1 * y2 ) * r,
  3228. ( t2 * z1 - t1 * z2 ) * r );
  3229. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  3230. ( s1 * y2 - s2 * y1 ) * r,
  3231. ( s1 * z2 - s2 * z1 ) * r );
  3232. tan1[ a ].addSelf( sdir );
  3233. tan1[ b ].addSelf( sdir );
  3234. tan1[ c ].addSelf( sdir );
  3235. tan2[ a ].addSelf( tdir );
  3236. tan2[ b ].addSelf( tdir );
  3237. tan2[ c ].addSelf( tdir );
  3238. }
  3239. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3240. face = this.faces[ f ];
  3241. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  3242. if ( face instanceof THREE.Face3 ) {
  3243. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  3244. } else if ( face instanceof THREE.Face4 ) {
  3245. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  3246. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  3247. }
  3248. }
  3249. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  3250. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3251. face = this.faces[ f ];
  3252. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  3253. n.copy( face.vertexNormals[ i ] );
  3254. vertexIndex = face[ faceIndex[ i ] ];
  3255. t = tan1[ vertexIndex ];
  3256. // Gram-Schmidt orthogonalize
  3257. tmp.copy( t );
  3258. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3259. // Calculate handedness
  3260. tmp2.cross( face.vertexNormals[ i ], t );
  3261. test = tmp2.dot( tan2[ vertexIndex ] );
  3262. w = (test < 0.0) ? -1.0 : 1.0;
  3263. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  3264. }
  3265. }
  3266. this.hasTangents = true;
  3267. },
  3268. computeBoundingBox: function () {
  3269. if ( ! this.boundingBox ) {
  3270. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  3271. }
  3272. if ( this.vertices.length > 0 ) {
  3273. var position, firstPosition = this.vertices[ 0 ];
  3274. this.boundingBox.min.copy( firstPosition );
  3275. this.boundingBox.max.copy( firstPosition );
  3276. var min = this.boundingBox.min,
  3277. max = this.boundingBox.max;
  3278. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  3279. position = this.vertices[ v ];
  3280. if ( position.x < min.x ) {
  3281. min.x = position.x;
  3282. } else if ( position.x > max.x ) {
  3283. max.x = position.x;
  3284. }
  3285. if ( position.y < min.y ) {
  3286. min.y = position.y;
  3287. } else if ( position.y > max.y ) {
  3288. max.y = position.y;
  3289. }
  3290. if ( position.z < min.z ) {
  3291. min.z = position.z;
  3292. } else if ( position.z > max.z ) {
  3293. max.z = position.z;
  3294. }
  3295. }
  3296. } else {
  3297. this.boundingBox.min.set( 0, 0, 0 );
  3298. this.boundingBox.max.set( 0, 0, 0 );
  3299. }
  3300. },
  3301. computeBoundingSphere: function () {
  3302. var maxRadiusSq = 0;
  3303. if ( this.boundingSphere === null ) this.boundingSphere = { radius: 0 };
  3304. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  3305. var radiusSq = this.vertices[ i ].lengthSq();
  3306. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3307. }
  3308. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3309. },
  3310. /*
  3311. * Checks for duplicate vertices with hashmap.
  3312. * Duplicated vertices are removed
  3313. * and faces' vertices are updated.
  3314. */
  3315. mergeVertices: function () {
  3316. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  3317. var unique = [], changes = [];
  3318. var v, key;
  3319. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  3320. var precision = Math.pow( 10, precisionPoints );
  3321. var i,il, face;
  3322. var abcd = 'abcd', o, k, j, jl, u;
  3323. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  3324. v = this.vertices[ i ];
  3325. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  3326. if ( verticesMap[ key ] === undefined ) {
  3327. verticesMap[ key ] = i;
  3328. unique.push( this.vertices[ i ] );
  3329. changes[ i ] = unique.length - 1;
  3330. } else {
  3331. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  3332. changes[ i ] = changes[ verticesMap[ key ] ];
  3333. }
  3334. };
  3335. // Start to patch face indices
  3336. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  3337. face = this.faces[ i ];
  3338. if ( face instanceof THREE.Face3 ) {
  3339. face.a = changes[ face.a ];
  3340. face.b = changes[ face.b ];
  3341. face.c = changes[ face.c ];
  3342. } else if ( face instanceof THREE.Face4 ) {
  3343. face.a = changes[ face.a ];
  3344. face.b = changes[ face.b ];
  3345. face.c = changes[ face.c ];
  3346. face.d = changes[ face.d ];
  3347. // check dups in (a, b, c, d) and convert to -> face3
  3348. o = [ face.a, face.b, face.c, face.d ];
  3349. for ( k = 3; k > 0; k -- ) {
  3350. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  3351. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  3352. o.splice( k, 1 );
  3353. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  3354. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  3355. u = this.faceVertexUvs[ j ][ i ];
  3356. if ( u ) u.splice( k, 1 );
  3357. }
  3358. this.faces[ i ].vertexColors = face.vertexColors;
  3359. break;
  3360. }
  3361. }
  3362. }
  3363. }
  3364. // Use unique set of vertices
  3365. var diff = this.vertices.length - unique.length;
  3366. this.vertices = unique;
  3367. return diff;
  3368. },
  3369. clone: function () {
  3370. // TODO
  3371. },
  3372. deallocate: function () {
  3373. var index = THREE.GeometryLibrary.indexOf( this );
  3374. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  3375. }
  3376. };
  3377. THREE.GeometryIdCount = 0;
  3378. THREE.GeometryLibrary = [];
  3379. /**
  3380. * @author alteredq / http://alteredqualia.com/
  3381. */
  3382. THREE.BufferGeometry = function () {
  3383. this.id = THREE.GeometryCount ++;
  3384. // attributes
  3385. this.attributes = {};
  3386. // attributes typed arrays are kept only if dynamic flag is set
  3387. this.dynamic = false;
  3388. // boundings
  3389. this.boundingBox = null;
  3390. this.boundingSphere = null;
  3391. this.hasTangents = false;
  3392. // for compatibility
  3393. this.morphTargets = [];
  3394. };
  3395. THREE.BufferGeometry.prototype = {
  3396. constructor : THREE.BufferGeometry,
  3397. applyMatrix: function ( matrix ) {
  3398. var positionArray;
  3399. var normalArray;
  3400. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  3401. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  3402. if ( positionArray !== undefined ) {
  3403. matrix.multiplyVector3Array( positionArray );
  3404. this.verticesNeedUpdate = true;
  3405. }
  3406. if ( normalArray !== undefined ) {
  3407. var matrixRotation = new THREE.Matrix4();
  3408. matrixRotation.extractRotation( matrix );
  3409. matrixRotation.multiplyVector3Array( normalArray );
  3410. this.normalsNeedUpdate = true;
  3411. }
  3412. },
  3413. computeBoundingBox: function () {
  3414. if ( ! this.boundingBox ) {
  3415. this.boundingBox = {
  3416. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  3417. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  3418. };
  3419. }
  3420. var positions = this.attributes[ "position" ].array;
  3421. if ( positions ) {
  3422. var bb = this.boundingBox;
  3423. var x, y, z;
  3424. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3425. x = positions[ i ];
  3426. y = positions[ i + 1 ];
  3427. z = positions[ i + 2 ];
  3428. // bounding box
  3429. if ( x < bb.min.x ) {
  3430. bb.min.x = x;
  3431. } else if ( x > bb.max.x ) {
  3432. bb.max.x = x;
  3433. }
  3434. if ( y < bb.min.y ) {
  3435. bb.min.y = y;
  3436. } else if ( y > bb.max.y ) {
  3437. bb.max.y = y;
  3438. }
  3439. if ( z < bb.min.z ) {
  3440. bb.min.z = z;
  3441. } else if ( z > bb.max.z ) {
  3442. bb.max.z = z;
  3443. }
  3444. }
  3445. }
  3446. if ( positions === undefined || positions.length === 0 ) {
  3447. this.boundingBox.min.set( 0, 0, 0 );
  3448. this.boundingBox.max.set( 0, 0, 0 );
  3449. }
  3450. },
  3451. computeBoundingSphere: function () {
  3452. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  3453. var positions = this.attributes[ "position" ].array;
  3454. if ( positions ) {
  3455. var radiusSq, maxRadiusSq = 0;
  3456. var x, y, z;
  3457. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  3458. x = positions[ i ];
  3459. y = positions[ i + 1 ];
  3460. z = positions[ i + 2 ];
  3461. radiusSq = x * x + y * y + z * z;
  3462. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  3463. }
  3464. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  3465. }
  3466. },
  3467. computeVertexNormals: function () {
  3468. if ( this.attributes[ "position" ] && this.attributes[ "index" ] ) {
  3469. var i, il;
  3470. var j, jl;
  3471. var nVertexElements = this.attributes[ "position" ].array.length;
  3472. if ( this.attributes[ "normal" ] === undefined ) {
  3473. this.attributes[ "normal" ] = {
  3474. itemSize: 3,
  3475. array: new Float32Array( nVertexElements ),
  3476. numItems: nVertexElements
  3477. };
  3478. } else {
  3479. // reset existing normals to zero
  3480. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  3481. this.attributes[ "normal" ].array[ i ] = 0;
  3482. }
  3483. }
  3484. var offsets = this.offsets;
  3485. var indices = this.attributes[ "index" ].array;
  3486. var positions = this.attributes[ "position" ].array;
  3487. var normals = this.attributes[ "normal" ].array;
  3488. var vA, vB, vC, x, y, z,
  3489. pA = new THREE.Vector3(),
  3490. pB = new THREE.Vector3(),
  3491. pC = new THREE.Vector3(),
  3492. cb = new THREE.Vector3(),
  3493. ab = new THREE.Vector3();
  3494. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3495. var start = offsets[ j ].start;
  3496. var count = offsets[ j ].count;
  3497. var index = offsets[ j ].index;
  3498. for ( i = start, il = start + count; i < il; i += 3 ) {
  3499. vA = index + indices[ i ];
  3500. vB = index + indices[ i + 1 ];
  3501. vC = index + indices[ i + 2 ];
  3502. x = positions[ vA * 3 ];
  3503. y = positions[ vA * 3 + 1 ];
  3504. z = positions[ vA * 3 + 2 ];
  3505. pA.set( x, y, z );
  3506. x = positions[ vB * 3 ];
  3507. y = positions[ vB * 3 + 1 ];
  3508. z = positions[ vB * 3 + 2 ];
  3509. pB.set( x, y, z );
  3510. x = positions[ vC * 3 ];
  3511. y = positions[ vC * 3 + 1 ];
  3512. z = positions[ vC * 3 + 2 ];
  3513. pC.set( x, y, z );
  3514. cb.sub( pC, pB );
  3515. ab.sub( pA, pB );
  3516. cb.crossSelf( ab );
  3517. normals[ vA * 3 ] += cb.x;
  3518. normals[ vA * 3 + 1 ] += cb.y;
  3519. normals[ vA * 3 + 2 ] += cb.z;
  3520. normals[ vB * 3 ] += cb.x;
  3521. normals[ vB * 3 + 1 ] += cb.y;
  3522. normals[ vB * 3 + 2 ] += cb.z;
  3523. normals[ vC * 3 ] += cb.x;
  3524. normals[ vC * 3 + 1 ] += cb.y;
  3525. normals[ vC * 3 + 2 ] += cb.z;
  3526. }
  3527. }
  3528. // normalize normals
  3529. for ( i = 0, il = normals.length; i < il; i += 3 ) {
  3530. x = normals[ i ];
  3531. y = normals[ i + 1 ];
  3532. z = normals[ i + 2 ];
  3533. var n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  3534. normals[ i ] *= n;
  3535. normals[ i + 1 ] *= n;
  3536. normals[ i + 2 ] *= n;
  3537. }
  3538. this.normalsNeedUpdate = true;
  3539. }
  3540. },
  3541. computeTangents: function () {
  3542. // based on http://www.terathon.com/code/tangent.html
  3543. // (per vertex tangents)
  3544. if ( this.attributes[ "index" ] === undefined ||
  3545. this.attributes[ "position" ] === undefined ||
  3546. this.attributes[ "normal" ] === undefined ||
  3547. this.attributes[ "uv" ] === undefined ) {
  3548. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  3549. return;
  3550. }
  3551. var indices = this.attributes[ "index" ].array;
  3552. var positions = this.attributes[ "position" ].array;
  3553. var normals = this.attributes[ "normal" ].array;
  3554. var uvs = this.attributes[ "uv" ].array;
  3555. var nVertices = positions.length / 3;
  3556. if ( this.attributes[ "tangent" ] === undefined ) {
  3557. var nTangentElements = 4 * nVertices;
  3558. this.attributes[ "tangent" ] = {
  3559. itemSize: 4,
  3560. array: new Float32Array( nTangentElements ),
  3561. numItems: nTangentElements
  3562. };
  3563. }
  3564. var tangents = this.attributes[ "tangent" ].array;
  3565. var tan1 = [], tan2 = [];
  3566. for ( var k = 0; k < nVertices; k ++ ) {
  3567. tan1[ k ] = new THREE.Vector3();
  3568. tan2[ k ] = new THREE.Vector3();
  3569. }
  3570. var xA, yA, zA,
  3571. xB, yB, zB,
  3572. xC, yC, zC,
  3573. uA, vA,
  3574. uB, vB,
  3575. uC, vC,
  3576. x1, x2, y1, y2, z1, z2,
  3577. s1, s2, t1, t2, r;
  3578. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  3579. function handleTriangle( a, b, c ) {
  3580. xA = positions[ a * 3 ];
  3581. yA = positions[ a * 3 + 1 ];
  3582. zA = positions[ a * 3 + 2 ];
  3583. xB = positions[ b * 3 ];
  3584. yB = positions[ b * 3 + 1 ];
  3585. zB = positions[ b * 3 + 2 ];
  3586. xC = positions[ c * 3 ];
  3587. yC = positions[ c * 3 + 1 ];
  3588. zC = positions[ c * 3 + 2 ];
  3589. uA = uvs[ a * 2 ];
  3590. vA = uvs[ a * 2 + 1 ];
  3591. uB = uvs[ b * 2 ];
  3592. vB = uvs[ b * 2 + 1 ];
  3593. uC = uvs[ c * 2 ];
  3594. vC = uvs[ c * 2 + 1 ];
  3595. x1 = xB - xA;
  3596. x2 = xC - xA;
  3597. y1 = yB - yA;
  3598. y2 = yC - yA;
  3599. z1 = zB - zA;
  3600. z2 = zC - zA;
  3601. s1 = uB - uA;
  3602. s2 = uC - uA;
  3603. t1 = vB - vA;
  3604. t2 = vC - vA;
  3605. r = 1.0 / ( s1 * t2 - s2 * t1 );
  3606. sdir.set(
  3607. ( t2 * x1 - t1 * x2 ) * r,
  3608. ( t2 * y1 - t1 * y2 ) * r,
  3609. ( t2 * z1 - t1 * z2 ) * r
  3610. );
  3611. tdir.set(
  3612. ( s1 * x2 - s2 * x1 ) * r,
  3613. ( s1 * y2 - s2 * y1 ) * r,
  3614. ( s1 * z2 - s2 * z1 ) * r
  3615. );
  3616. tan1[ a ].addSelf( sdir );
  3617. tan1[ b ].addSelf( sdir );
  3618. tan1[ c ].addSelf( sdir );
  3619. tan2[ a ].addSelf( tdir );
  3620. tan2[ b ].addSelf( tdir );
  3621. tan2[ c ].addSelf( tdir );
  3622. }
  3623. var i, il;
  3624. var j, jl;
  3625. var iA, iB, iC;
  3626. var offsets = this.offsets;
  3627. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3628. var start = offsets[ j ].start;
  3629. var count = offsets[ j ].count;
  3630. var index = offsets[ j ].index;
  3631. for ( i = start, il = start + count; i < il; i += 3 ) {
  3632. iA = index + indices[ i ];
  3633. iB = index + indices[ i + 1 ];
  3634. iC = index + indices[ i + 2 ];
  3635. handleTriangle( iA, iB, iC );
  3636. }
  3637. }
  3638. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  3639. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  3640. var w, t, test;
  3641. var nx, ny, nz;
  3642. function handleVertex( v ) {
  3643. n.x = normals[ v * 3 ];
  3644. n.y = normals[ v * 3 + 1 ];
  3645. n.z = normals[ v * 3 + 2 ];
  3646. n2.copy( n );
  3647. t = tan1[ v ];
  3648. // Gram-Schmidt orthogonalize
  3649. tmp.copy( t );
  3650. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  3651. // Calculate handedness
  3652. tmp2.cross( n2, t );
  3653. test = tmp2.dot( tan2[ v ] );
  3654. w = ( test < 0.0 ) ? -1.0 : 1.0;
  3655. tangents[ v * 4 ] = tmp.x;
  3656. tangents[ v * 4 + 1 ] = tmp.y;
  3657. tangents[ v * 4 + 2 ] = tmp.z;
  3658. tangents[ v * 4 + 3 ] = w;
  3659. }
  3660. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  3661. var start = offsets[ j ].start;
  3662. var count = offsets[ j ].count;
  3663. var index = offsets[ j ].index;
  3664. for ( i = start, il = start + count; i < il; i += 3 ) {
  3665. iA = index + indices[ i ];
  3666. iB = index + indices[ i + 1 ];
  3667. iC = index + indices[ i + 2 ];
  3668. handleVertex( iA );
  3669. handleVertex( iB );
  3670. handleVertex( iC );
  3671. }
  3672. }
  3673. this.hasTangents = true;
  3674. this.tangentsNeedUpdate = true;
  3675. }
  3676. };
  3677. /**
  3678. * Spline from Tween.js, slightly optimized (and trashed)
  3679. * http://sole.github.com/tween.js/examples/05_spline.html
  3680. *
  3681. * @author mrdoob / http://mrdoob.com/
  3682. * @author alteredq / http://alteredqualia.com/
  3683. */
  3684. THREE.Spline = function ( points ) {
  3685. this.points = points;
  3686. var c = [], v3 = { x: 0, y: 0, z: 0 },
  3687. point, intPoint, weight, w2, w3,
  3688. pa, pb, pc, pd;
  3689. this.initFromArray = function( a ) {
  3690. this.points = [];
  3691. for ( var i = 0; i < a.length; i++ ) {
  3692. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  3693. }
  3694. };
  3695. this.getPoint = function ( k ) {
  3696. point = ( this.points.length - 1 ) * k;
  3697. intPoint = Math.floor( point );
  3698. weight = point - intPoint;
  3699. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3700. c[ 1 ] = intPoint;
  3701. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  3702. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  3703. pa = this.points[ c[ 0 ] ];
  3704. pb = this.points[ c[ 1 ] ];
  3705. pc = this.points[ c[ 2 ] ];
  3706. pd = this.points[ c[ 3 ] ];
  3707. w2 = weight * weight;
  3708. w3 = weight * w2;
  3709. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  3710. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  3711. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  3712. return v3;
  3713. };
  3714. this.getControlPointsArray = function () {
  3715. var i, p, l = this.points.length,
  3716. coords = [];
  3717. for ( i = 0; i < l; i ++ ) {
  3718. p = this.points[ i ];
  3719. coords[ i ] = [ p.x, p.y, p.z ];
  3720. }
  3721. return coords;
  3722. };
  3723. // approximate length by summing linear segments
  3724. this.getLength = function ( nSubDivisions ) {
  3725. var i, index, nSamples, position,
  3726. point = 0, intPoint = 0, oldIntPoint = 0,
  3727. oldPosition = new THREE.Vector3(),
  3728. tmpVec = new THREE.Vector3(),
  3729. chunkLengths = [],
  3730. totalLength = 0;
  3731. // first point has 0 length
  3732. chunkLengths[ 0 ] = 0;
  3733. if ( !nSubDivisions ) nSubDivisions = 100;
  3734. nSamples = this.points.length * nSubDivisions;
  3735. oldPosition.copy( this.points[ 0 ] );
  3736. for ( i = 1; i < nSamples; i ++ ) {
  3737. index = i / nSamples;
  3738. position = this.getPoint( index );
  3739. tmpVec.copy( position );
  3740. totalLength += tmpVec.distanceTo( oldPosition );
  3741. oldPosition.copy( position );
  3742. point = ( this.points.length - 1 ) * index;
  3743. intPoint = Math.floor( point );
  3744. if ( intPoint != oldIntPoint ) {
  3745. chunkLengths[ intPoint ] = totalLength;
  3746. oldIntPoint = intPoint;
  3747. }
  3748. }
  3749. // last point ends with total length
  3750. chunkLengths[ chunkLengths.length ] = totalLength;
  3751. return { chunks: chunkLengths, total: totalLength };
  3752. };
  3753. this.reparametrizeByArcLength = function ( samplingCoef ) {
  3754. var i, j,
  3755. index, indexCurrent, indexNext,
  3756. linearDistance, realDistance,
  3757. sampling, position,
  3758. newpoints = [],
  3759. tmpVec = new THREE.Vector3(),
  3760. sl = this.getLength();
  3761. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  3762. for ( i = 1; i < this.points.length; i++ ) {
  3763. //tmpVec.copy( this.points[ i - 1 ] );
  3764. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  3765. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  3766. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  3767. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  3768. indexNext = i / ( this.points.length - 1 );
  3769. for ( j = 1; j < sampling - 1; j++ ) {
  3770. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  3771. position = this.getPoint( index );
  3772. newpoints.push( tmpVec.copy( position ).clone() );
  3773. }
  3774. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  3775. }
  3776. this.points = newpoints;
  3777. };
  3778. // Catmull-Rom
  3779. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  3780. var v0 = ( p2 - p0 ) * 0.5,
  3781. v1 = ( p3 - p1 ) * 0.5;
  3782. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3783. };
  3784. };
  3785. /**
  3786. * @author mrdoob / http://mrdoob.com/
  3787. * @author mikael emtinger / http://gomo.se/
  3788. */
  3789. THREE.Camera = function () {
  3790. THREE.Object3D.call( this );
  3791. this.matrixWorldInverse = new THREE.Matrix4();
  3792. this.projectionMatrix = new THREE.Matrix4();
  3793. this.projectionMatrixInverse = new THREE.Matrix4();
  3794. };
  3795. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  3796. THREE.Camera.prototype.lookAt = function ( vector ) {
  3797. // TODO: Add hierarchy support.
  3798. this.matrix.lookAt( this.position, vector, this.up );
  3799. if ( this.rotationAutoUpdate === true ) {
  3800. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  3801. }
  3802. };
  3803. /**
  3804. * @author alteredq / http://alteredqualia.com/
  3805. */
  3806. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  3807. THREE.Camera.call( this );
  3808. this.left = left;
  3809. this.right = right;
  3810. this.top = top;
  3811. this.bottom = bottom;
  3812. this.near = ( near !== undefined ) ? near : 0.1;
  3813. this.far = ( far !== undefined ) ? far : 2000;
  3814. this.updateProjectionMatrix();
  3815. };
  3816. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  3817. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  3818. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  3819. };
  3820. /**
  3821. * @author mrdoob / http://mrdoob.com/
  3822. * @author greggman / http://games.greggman.com/
  3823. * @author zz85 / http://www.lab4games.net/zz85/blog
  3824. */
  3825. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  3826. THREE.Camera.call( this );
  3827. this.fov = fov !== undefined ? fov : 50;
  3828. this.aspect = aspect !== undefined ? aspect : 1;
  3829. this.near = near !== undefined ? near : 0.1;
  3830. this.far = far !== undefined ? far : 2000;
  3831. this.updateProjectionMatrix();
  3832. };
  3833. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  3834. /**
  3835. * Uses Focal Length (in mm) to estimate and set FOV
  3836. * 35mm (fullframe) camera is used if frame size is not specified;
  3837. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3838. */
  3839. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3840. if ( frameHeight === undefined ) frameHeight = 24;
  3841. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3842. this.updateProjectionMatrix();
  3843. }
  3844. /**
  3845. * Sets an offset in a larger frustum. This is useful for multi-window or
  3846. * multi-monitor/multi-machine setups.
  3847. *
  3848. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  3849. * the monitors are in grid like this
  3850. *
  3851. * +---+---+---+
  3852. * | A | B | C |
  3853. * +---+---+---+
  3854. * | D | E | F |
  3855. * +---+---+---+
  3856. *
  3857. * then for each monitor you would call it like this
  3858. *
  3859. * var w = 1920;
  3860. * var h = 1080;
  3861. * var fullWidth = w * 3;
  3862. * var fullHeight = h * 2;
  3863. *
  3864. * --A--
  3865. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  3866. * --B--
  3867. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  3868. * --C--
  3869. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  3870. * --D--
  3871. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  3872. * --E--
  3873. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  3874. * --F--
  3875. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  3876. *
  3877. * Note there is no reason monitors have to be the same size or in a grid.
  3878. */
  3879. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  3880. this.fullWidth = fullWidth;
  3881. this.fullHeight = fullHeight;
  3882. this.x = x;
  3883. this.y = y;
  3884. this.width = width;
  3885. this.height = height;
  3886. this.updateProjectionMatrix();
  3887. };
  3888. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  3889. if ( this.fullWidth ) {
  3890. var aspect = this.fullWidth / this.fullHeight;
  3891. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  3892. var bottom = -top;
  3893. var left = aspect * bottom;
  3894. var right = aspect * top;
  3895. var width = Math.abs( right - left );
  3896. var height = Math.abs( top - bottom );
  3897. this.projectionMatrix.makeFrustum(
  3898. left + this.x * width / this.fullWidth,
  3899. left + ( this.x + this.width ) * width / this.fullWidth,
  3900. top - ( this.y + this.height ) * height / this.fullHeight,
  3901. top - this.y * height / this.fullHeight,
  3902. this.near,
  3903. this.far
  3904. );
  3905. } else {
  3906. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3907. }
  3908. };
  3909. /**
  3910. * @author mrdoob / http://mrdoob.com/
  3911. * @author alteredq / http://alteredqualia.com/
  3912. */
  3913. THREE.Light = function ( hex ) {
  3914. THREE.Object3D.call( this );
  3915. this.color = new THREE.Color( hex );
  3916. };
  3917. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  3918. /**
  3919. * @author mrdoob / http://mrdoob.com/
  3920. */
  3921. THREE.AmbientLight = function ( hex ) {
  3922. THREE.Light.call( this, hex );
  3923. };
  3924. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  3925. /**
  3926. * @author mrdoob / http://mrdoob.com/
  3927. * @author alteredq / http://alteredqualia.com/
  3928. */
  3929. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3930. THREE.Light.call( this, hex );
  3931. this.position = new THREE.Vector3( 0, 1, 0 );
  3932. this.target = new THREE.Object3D();
  3933. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3934. this.distance = ( distance !== undefined ) ? distance : 0;
  3935. this.castShadow = false;
  3936. this.onlyShadow = false;
  3937. //
  3938. this.shadowCameraNear = 50;
  3939. this.shadowCameraFar = 5000;
  3940. this.shadowCameraLeft = -500;
  3941. this.shadowCameraRight = 500;
  3942. this.shadowCameraTop = 500;
  3943. this.shadowCameraBottom = -500;
  3944. this.shadowCameraVisible = false;
  3945. this.shadowBias = 0;
  3946. this.shadowDarkness = 0.5;
  3947. this.shadowMapWidth = 512;
  3948. this.shadowMapHeight = 512;
  3949. //
  3950. this.shadowCascade = false;
  3951. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3952. this.shadowCascadeCount = 2;
  3953. this.shadowCascadeBias = [ 0, 0, 0 ];
  3954. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3955. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3956. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3957. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3958. this.shadowCascadeArray = [];
  3959. //
  3960. this.shadowMap = null;
  3961. this.shadowMapSize = null;
  3962. this.shadowCamera = null;
  3963. this.shadowMatrix = null;
  3964. };
  3965. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  3966. /**
  3967. * @author alteredq / http://alteredqualia.com/
  3968. */
  3969. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  3970. THREE.Light.call( this, skyColorHex );
  3971. this.groundColor = new THREE.Color( groundColorHex );
  3972. this.position = new THREE.Vector3( 0, 100, 0 );
  3973. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3974. };
  3975. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  3976. /**
  3977. * @author mrdoob / http://mrdoob.com/
  3978. */
  3979. THREE.PointLight = function ( hex, intensity, distance ) {
  3980. THREE.Light.call( this, hex );
  3981. this.position = new THREE.Vector3( 0, 0, 0 );
  3982. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3983. this.distance = ( distance !== undefined ) ? distance : 0;
  3984. };
  3985. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  3986. /**
  3987. * @author alteredq / http://alteredqualia.com/
  3988. */
  3989. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  3990. THREE.Light.call( this, hex );
  3991. this.position = new THREE.Vector3( 0, 1, 0 );
  3992. this.target = new THREE.Object3D();
  3993. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3994. this.distance = ( distance !== undefined ) ? distance : 0;
  3995. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  3996. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  3997. this.castShadow = false;
  3998. this.onlyShadow = false;
  3999. //
  4000. this.shadowCameraNear = 50;
  4001. this.shadowCameraFar = 5000;
  4002. this.shadowCameraFov = 50;
  4003. this.shadowCameraVisible = false;
  4004. this.shadowBias = 0;
  4005. this.shadowDarkness = 0.5;
  4006. this.shadowMapWidth = 512;
  4007. this.shadowMapHeight = 512;
  4008. //
  4009. this.shadowMap = null;
  4010. this.shadowMapSize = null;
  4011. this.shadowCamera = null;
  4012. this.shadowMatrix = null;
  4013. };
  4014. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4015. /**
  4016. * @author alteredq / http://alteredqualia.com/
  4017. */
  4018. THREE.Loader = function ( showStatus ) {
  4019. this.showStatus = showStatus;
  4020. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4021. this.onLoadStart = function () {};
  4022. this.onLoadProgress = function () {};
  4023. this.onLoadComplete = function () {};
  4024. };
  4025. THREE.Loader.prototype = {
  4026. constructor: THREE.Loader,
  4027. crossOrigin: 'anonymous',
  4028. addStatusElement: function () {
  4029. var e = document.createElement( "div" );
  4030. e.style.position = "absolute";
  4031. e.style.right = "0px";
  4032. e.style.top = "0px";
  4033. e.style.fontSize = "0.8em";
  4034. e.style.textAlign = "left";
  4035. e.style.background = "rgba(0,0,0,0.25)";
  4036. e.style.color = "#fff";
  4037. e.style.width = "120px";
  4038. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4039. e.style.zIndex = 1000;
  4040. e.innerHTML = "Loading ...";
  4041. return e;
  4042. },
  4043. updateProgress: function ( progress ) {
  4044. var message = "Loaded ";
  4045. if ( progress.total ) {
  4046. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4047. } else {
  4048. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4049. }
  4050. this.statusDomElement.innerHTML = message;
  4051. },
  4052. extractUrlBase: function ( url ) {
  4053. var parts = url.split( '/' );
  4054. parts.pop();
  4055. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4056. },
  4057. initMaterials: function ( scope, materials, texturePath ) {
  4058. scope.materials = [];
  4059. for ( var i = 0; i < materials.length; ++ i ) {
  4060. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4061. }
  4062. },
  4063. hasNormals: function ( scope ) {
  4064. var m, i, il = scope.materials.length;
  4065. for( i = 0; i < il; i ++ ) {
  4066. m = scope.materials[ i ];
  4067. if ( m instanceof THREE.ShaderMaterial ) return true;
  4068. }
  4069. return false;
  4070. },
  4071. createMaterial: function ( m, texturePath ) {
  4072. var _this = this;
  4073. function is_pow2( n ) {
  4074. var l = Math.log( n ) / Math.LN2;
  4075. return Math.floor( l ) == l;
  4076. }
  4077. function nearest_pow2( n ) {
  4078. var l = Math.log( n ) / Math.LN2;
  4079. return Math.pow( 2, Math.round( l ) );
  4080. }
  4081. function load_image( where, url ) {
  4082. var image = new Image();
  4083. image.onload = function () {
  4084. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4085. var width = nearest_pow2( this.width );
  4086. var height = nearest_pow2( this.height );
  4087. where.image.width = width;
  4088. where.image.height = height;
  4089. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4090. } else {
  4091. where.image = this;
  4092. }
  4093. where.needsUpdate = true;
  4094. };
  4095. image.crossOrigin = _this.crossOrigin;
  4096. image.src = url;
  4097. }
  4098. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4099. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4100. var fullPath = texturePath + "/" + sourceFile;
  4101. if ( isCompressed ) {
  4102. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4103. where[ name ] = texture;
  4104. } else {
  4105. var texture = document.createElement( 'canvas' );
  4106. where[ name ] = new THREE.Texture( texture );
  4107. }
  4108. where[ name ].sourceFile = sourceFile;
  4109. if( repeat ) {
  4110. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4111. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4112. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4113. }
  4114. if ( offset ) {
  4115. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4116. }
  4117. if ( wrap ) {
  4118. var wrapMap = {
  4119. "repeat": THREE.RepeatWrapping,
  4120. "mirror": THREE.MirroredRepeatWrapping
  4121. }
  4122. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4123. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4124. }
  4125. if ( anisotropy ) {
  4126. where[ name ].anisotropy = anisotropy;
  4127. }
  4128. if ( ! isCompressed ) {
  4129. load_image( where[ name ], fullPath );
  4130. }
  4131. }
  4132. function rgb2hex( rgb ) {
  4133. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4134. }
  4135. // defaults
  4136. var mtype = "MeshLambertMaterial";
  4137. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4138. // parameters from model file
  4139. if ( m.shading ) {
  4140. var shading = m.shading.toLowerCase();
  4141. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4142. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4143. }
  4144. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4145. mpars.blending = THREE[ m.blending ];
  4146. }
  4147. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4148. mpars.transparent = m.transparent;
  4149. }
  4150. if ( m.depthTest !== undefined ) {
  4151. mpars.depthTest = m.depthTest;
  4152. }
  4153. if ( m.depthWrite !== undefined ) {
  4154. mpars.depthWrite = m.depthWrite;
  4155. }
  4156. if ( m.visible !== undefined ) {
  4157. mpars.visible = m.visible;
  4158. }
  4159. if ( m.flipSided !== undefined ) {
  4160. mpars.side = THREE.BackSide;
  4161. }
  4162. if ( m.doubleSided !== undefined ) {
  4163. mpars.side = THREE.DoubleSide;
  4164. }
  4165. if ( m.wireframe !== undefined ) {
  4166. mpars.wireframe = m.wireframe;
  4167. }
  4168. if ( m.vertexColors !== undefined ) {
  4169. if ( m.vertexColors === "face" ) {
  4170. mpars.vertexColors = THREE.FaceColors;
  4171. } else if ( m.vertexColors ) {
  4172. mpars.vertexColors = THREE.VertexColors;
  4173. }
  4174. }
  4175. // colors
  4176. if ( m.colorDiffuse ) {
  4177. mpars.color = rgb2hex( m.colorDiffuse );
  4178. } else if ( m.DbgColor ) {
  4179. mpars.color = m.DbgColor;
  4180. }
  4181. if ( m.colorSpecular ) {
  4182. mpars.specular = rgb2hex( m.colorSpecular );
  4183. }
  4184. if ( m.colorAmbient ) {
  4185. mpars.ambient = rgb2hex( m.colorAmbient );
  4186. }
  4187. // modifiers
  4188. if ( m.transparency ) {
  4189. mpars.opacity = m.transparency;
  4190. }
  4191. if ( m.specularCoef ) {
  4192. mpars.shininess = m.specularCoef;
  4193. }
  4194. // textures
  4195. if ( m.mapDiffuse && texturePath ) {
  4196. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  4197. }
  4198. if ( m.mapLight && texturePath ) {
  4199. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  4200. }
  4201. if ( m.mapBump && texturePath ) {
  4202. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  4203. }
  4204. if ( m.mapNormal && texturePath ) {
  4205. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  4206. }
  4207. if ( m.mapSpecular && texturePath ) {
  4208. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  4209. }
  4210. //
  4211. if ( m.mapBumpScale ) {
  4212. mpars.bumpScale = m.mapBumpScale;
  4213. }
  4214. // special case for normal mapped material
  4215. if ( m.mapNormal ) {
  4216. var shader = THREE.ShaderUtils.lib[ "normal" ];
  4217. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  4218. uniforms[ "tNormal" ].value = mpars.normalMap;
  4219. if ( m.mapNormalFactor ) {
  4220. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  4221. }
  4222. if ( mpars.map ) {
  4223. uniforms[ "tDiffuse" ].value = mpars.map;
  4224. uniforms[ "enableDiffuse" ].value = true;
  4225. }
  4226. if ( mpars.specularMap ) {
  4227. uniforms[ "tSpecular" ].value = mpars.specularMap;
  4228. uniforms[ "enableSpecular" ].value = true;
  4229. }
  4230. if ( mpars.lightMap ) {
  4231. uniforms[ "tAO" ].value = mpars.lightMap;
  4232. uniforms[ "enableAO" ].value = true;
  4233. }
  4234. // for the moment don't handle displacement texture
  4235. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  4236. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  4237. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  4238. uniforms[ "uShininess" ].value = mpars.shininess;
  4239. if ( mpars.opacity !== undefined ) {
  4240. uniforms[ "uOpacity" ].value = mpars.opacity;
  4241. }
  4242. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  4243. var material = new THREE.ShaderMaterial( parameters );
  4244. } else {
  4245. var material = new THREE[ mtype ]( mpars );
  4246. }
  4247. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  4248. return material;
  4249. }
  4250. };
  4251. /**
  4252. * @author alteredq / http://alteredqualia.com/
  4253. */
  4254. THREE.BinaryLoader = function ( showStatus ) {
  4255. THREE.Loader.call( this, showStatus );
  4256. };
  4257. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  4258. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  4259. // - binary models consist of two files: JS and BIN
  4260. // - parameters
  4261. // - url (required)
  4262. // - callback (required)
  4263. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  4264. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  4265. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  4266. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4267. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  4268. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  4269. this.onLoadStart();
  4270. // #1 load JS part via web worker
  4271. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  4272. };
  4273. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  4274. var xhr = new XMLHttpRequest();
  4275. xhr.onreadystatechange = function () {
  4276. if ( xhr.readyState == 4 ) {
  4277. if ( xhr.status == 200 || xhr.status == 0 ) {
  4278. var json = JSON.parse( xhr.responseText );
  4279. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  4280. } else {
  4281. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4282. }
  4283. }
  4284. };
  4285. xhr.open( "GET", url, true );
  4286. xhr.send( null );
  4287. };
  4288. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  4289. var xhr = new XMLHttpRequest(),
  4290. url = binaryPath + "/" + json.buffers;
  4291. var length = 0;
  4292. xhr.onreadystatechange = function () {
  4293. if ( xhr.readyState == 4 ) {
  4294. if ( xhr.status == 200 || xhr.status == 0 ) {
  4295. var buffer = xhr.response;
  4296. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  4297. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  4298. } else {
  4299. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4300. }
  4301. } else if ( xhr.readyState == 3 ) {
  4302. if ( callbackProgress ) {
  4303. if ( length == 0 ) {
  4304. length = xhr.getResponseHeader( "Content-Length" );
  4305. }
  4306. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4307. }
  4308. } else if ( xhr.readyState == 2 ) {
  4309. length = xhr.getResponseHeader( "Content-Length" );
  4310. }
  4311. };
  4312. xhr.open( "GET", url, true );
  4313. xhr.responseType = "arraybuffer";
  4314. xhr.send( null );
  4315. };
  4316. // Binary AJAX parser
  4317. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  4318. var Model = function ( texturePath ) {
  4319. var scope = this,
  4320. currentOffset = 0,
  4321. md,
  4322. normals = [],
  4323. uvs = [],
  4324. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  4325. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  4326. tri_size, quad_size,
  4327. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  4328. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  4329. THREE.Geometry.call( this );
  4330. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  4331. md = parseMetaData( data, currentOffset );
  4332. currentOffset += md.header_bytes;
  4333. /*
  4334. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4335. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  4336. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4337. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  4338. */
  4339. // buffers sizes
  4340. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  4341. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  4342. len_tri_flat = md.ntri_flat * ( tri_size );
  4343. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  4344. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  4345. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  4346. len_quad_flat = md.nquad_flat * ( quad_size );
  4347. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  4348. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  4349. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  4350. // read buffers
  4351. currentOffset += init_vertices( currentOffset );
  4352. currentOffset += init_normals( currentOffset );
  4353. currentOffset += handlePadding( md.nnormals * 3 );
  4354. currentOffset += init_uvs( currentOffset );
  4355. start_tri_flat = currentOffset;
  4356. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  4357. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  4358. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  4359. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  4360. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  4361. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  4362. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  4363. // have to first process faces with uvs
  4364. // so that face and uv indices match
  4365. init_triangles_flat_uv( start_tri_flat_uv );
  4366. init_triangles_smooth_uv( start_tri_smooth_uv );
  4367. init_quads_flat_uv( start_quad_flat_uv );
  4368. init_quads_smooth_uv( start_quad_smooth_uv );
  4369. // now we can process untextured faces
  4370. init_triangles_flat( start_tri_flat );
  4371. init_triangles_smooth( start_tri_smooth );
  4372. init_quads_flat( start_quad_flat );
  4373. init_quads_smooth( start_quad_smooth );
  4374. this.computeCentroids();
  4375. this.computeFaceNormals();
  4376. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  4377. function handlePadding( n ) {
  4378. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  4379. };
  4380. function parseMetaData( data, offset ) {
  4381. var metaData = {
  4382. 'signature' :parseString( data, offset, 12 ),
  4383. 'header_bytes' :parseUChar8( data, offset + 12 ),
  4384. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  4385. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  4386. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  4387. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  4388. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  4389. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  4390. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  4391. 'nvertices' :parseUInt32( data, offset + 20 ),
  4392. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  4393. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  4394. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  4395. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  4396. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  4397. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  4398. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  4399. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  4400. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  4401. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  4402. };
  4403. /*
  4404. console.log( "signature: " + metaData.signature );
  4405. console.log( "header_bytes: " + metaData.header_bytes );
  4406. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  4407. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  4408. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  4409. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  4410. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  4411. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  4412. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  4413. console.log( "nvertices: " + metaData.nvertices );
  4414. console.log( "nnormals: " + metaData.nnormals );
  4415. console.log( "nuvs: " + metaData.nuvs );
  4416. console.log( "ntri_flat: " + metaData.ntri_flat );
  4417. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  4418. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  4419. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  4420. console.log( "nquad_flat: " + metaData.nquad_flat );
  4421. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  4422. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  4423. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  4424. var total = metaData.header_bytes
  4425. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  4426. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  4427. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  4428. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  4429. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  4430. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  4431. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  4432. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  4433. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  4434. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  4435. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  4436. console.log( "total bytes: " + total );
  4437. */
  4438. return metaData;
  4439. };
  4440. function parseString( data, offset, length ) {
  4441. var charArray = new Uint8Array( data, offset, length );
  4442. var text = "";
  4443. for ( var i = 0; i < length; i ++ ) {
  4444. text += String.fromCharCode( charArray[ offset + i ] );
  4445. }
  4446. return text;
  4447. };
  4448. function parseUChar8( data, offset ) {
  4449. var charArray = new Uint8Array( data, offset, 1 );
  4450. return charArray[ 0 ];
  4451. };
  4452. function parseUInt32( data, offset ) {
  4453. var intArray = new Uint32Array( data, offset, 1 );
  4454. return intArray[ 0 ];
  4455. };
  4456. function init_vertices( start ) {
  4457. var nElements = md.nvertices;
  4458. var coordArray = new Float32Array( data, start, nElements * 3 );
  4459. var i, x, y, z;
  4460. for( i = 0; i < nElements; i ++ ) {
  4461. x = coordArray[ i * 3 ];
  4462. y = coordArray[ i * 3 + 1 ];
  4463. z = coordArray[ i * 3 + 2 ];
  4464. vertex( scope, x, y, z );
  4465. }
  4466. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  4467. };
  4468. function init_normals( start ) {
  4469. var nElements = md.nnormals;
  4470. if ( nElements ) {
  4471. var normalArray = new Int8Array( data, start, nElements * 3 );
  4472. var i, x, y, z;
  4473. for( i = 0; i < nElements; i ++ ) {
  4474. x = normalArray[ i * 3 ];
  4475. y = normalArray[ i * 3 + 1 ];
  4476. z = normalArray[ i * 3 + 2 ];
  4477. normals.push( x/127, y/127, z/127 );
  4478. }
  4479. }
  4480. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  4481. };
  4482. function init_uvs( start ) {
  4483. var nElements = md.nuvs;
  4484. if ( nElements ) {
  4485. var uvArray = new Float32Array( data, start, nElements * 2 );
  4486. var i, u, v;
  4487. for( i = 0; i < nElements; i ++ ) {
  4488. u = uvArray[ i * 2 ];
  4489. v = uvArray[ i * 2 + 1 ];
  4490. uvs.push( u, v );
  4491. }
  4492. }
  4493. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  4494. };
  4495. function init_uvs3( nElements, offset ) {
  4496. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  4497. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  4498. for( i = 0; i < nElements; i ++ ) {
  4499. uva = uvIndexBuffer[ i * 3 ];
  4500. uvb = uvIndexBuffer[ i * 3 + 1 ];
  4501. uvc = uvIndexBuffer[ i * 3 + 2 ];
  4502. u1 = uvs[ uva*2 ];
  4503. v1 = uvs[ uva*2 + 1 ];
  4504. u2 = uvs[ uvb*2 ];
  4505. v2 = uvs[ uvb*2 + 1 ];
  4506. u3 = uvs[ uvc*2 ];
  4507. v3 = uvs[ uvc*2 + 1 ];
  4508. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  4509. }
  4510. };
  4511. function init_uvs4( nElements, offset ) {
  4512. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  4513. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  4514. for( i = 0; i < nElements; i ++ ) {
  4515. uva = uvIndexBuffer[ i * 4 ];
  4516. uvb = uvIndexBuffer[ i * 4 + 1 ];
  4517. uvc = uvIndexBuffer[ i * 4 + 2 ];
  4518. uvd = uvIndexBuffer[ i * 4 + 3 ];
  4519. u1 = uvs[ uva*2 ];
  4520. v1 = uvs[ uva*2 + 1 ];
  4521. u2 = uvs[ uvb*2 ];
  4522. v2 = uvs[ uvb*2 + 1 ];
  4523. u3 = uvs[ uvc*2 ];
  4524. v3 = uvs[ uvc*2 + 1 ];
  4525. u4 = uvs[ uvd*2 ];
  4526. v4 = uvs[ uvd*2 + 1 ];
  4527. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  4528. }
  4529. };
  4530. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  4531. var i, a, b, c, m;
  4532. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4533. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4534. for( i = 0; i < nElements; i ++ ) {
  4535. a = vertexIndexBuffer[ i * 3 ];
  4536. b = vertexIndexBuffer[ i * 3 + 1 ];
  4537. c = vertexIndexBuffer[ i * 3 + 2 ];
  4538. m = materialIndexBuffer[ i ];
  4539. f3( scope, a, b, c, m );
  4540. }
  4541. };
  4542. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  4543. var i, a, b, c, d, m;
  4544. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4545. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4546. for( i = 0; i < nElements; i ++ ) {
  4547. a = vertexIndexBuffer[ i * 4 ];
  4548. b = vertexIndexBuffer[ i * 4 + 1 ];
  4549. c = vertexIndexBuffer[ i * 4 + 2 ];
  4550. d = vertexIndexBuffer[ i * 4 + 3 ];
  4551. m = materialIndexBuffer[ i ];
  4552. f4( scope, a, b, c, d, m );
  4553. }
  4554. };
  4555. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4556. var i, a, b, c, m;
  4557. var na, nb, nc;
  4558. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  4559. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  4560. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4561. for( i = 0; i < nElements; i ++ ) {
  4562. a = vertexIndexBuffer[ i * 3 ];
  4563. b = vertexIndexBuffer[ i * 3 + 1 ];
  4564. c = vertexIndexBuffer[ i * 3 + 2 ];
  4565. na = normalIndexBuffer[ i * 3 ];
  4566. nb = normalIndexBuffer[ i * 3 + 1 ];
  4567. nc = normalIndexBuffer[ i * 3 + 2 ];
  4568. m = materialIndexBuffer[ i ];
  4569. f3n( scope, normals, a, b, c, m, na, nb, nc );
  4570. }
  4571. };
  4572. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  4573. var i, a, b, c, d, m;
  4574. var na, nb, nc, nd;
  4575. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  4576. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  4577. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  4578. for( i = 0; i < nElements; i ++ ) {
  4579. a = vertexIndexBuffer[ i * 4 ];
  4580. b = vertexIndexBuffer[ i * 4 + 1 ];
  4581. c = vertexIndexBuffer[ i * 4 + 2 ];
  4582. d = vertexIndexBuffer[ i * 4 + 3 ];
  4583. na = normalIndexBuffer[ i * 4 ];
  4584. nb = normalIndexBuffer[ i * 4 + 1 ];
  4585. nc = normalIndexBuffer[ i * 4 + 2 ];
  4586. nd = normalIndexBuffer[ i * 4 + 3 ];
  4587. m = materialIndexBuffer[ i ];
  4588. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  4589. }
  4590. };
  4591. function init_triangles_flat( start ) {
  4592. var nElements = md.ntri_flat;
  4593. if ( nElements ) {
  4594. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4595. init_faces3_flat( nElements, start, offsetMaterials );
  4596. }
  4597. };
  4598. function init_triangles_flat_uv( start ) {
  4599. var nElements = md.ntri_flat_uv;
  4600. if ( nElements ) {
  4601. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4602. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4603. init_faces3_flat( nElements, start, offsetMaterials );
  4604. init_uvs3( nElements, offsetUvs );
  4605. }
  4606. };
  4607. function init_triangles_smooth( start ) {
  4608. var nElements = md.ntri_smooth;
  4609. if ( nElements ) {
  4610. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4611. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4612. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4613. }
  4614. };
  4615. function init_triangles_smooth_uv( start ) {
  4616. var nElements = md.ntri_smooth_uv;
  4617. if ( nElements ) {
  4618. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4619. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4620. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  4621. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  4622. init_uvs3( nElements, offsetUvs );
  4623. }
  4624. };
  4625. function init_quads_flat( start ) {
  4626. var nElements = md.nquad_flat;
  4627. if ( nElements ) {
  4628. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4629. init_faces4_flat( nElements, start, offsetMaterials );
  4630. }
  4631. };
  4632. function init_quads_flat_uv( start ) {
  4633. var nElements = md.nquad_flat_uv;
  4634. if ( nElements ) {
  4635. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4636. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4637. init_faces4_flat( nElements, start, offsetMaterials );
  4638. init_uvs4( nElements, offsetUvs );
  4639. }
  4640. };
  4641. function init_quads_smooth( start ) {
  4642. var nElements = md.nquad_smooth;
  4643. if ( nElements ) {
  4644. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4645. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4646. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4647. }
  4648. };
  4649. function init_quads_smooth_uv( start ) {
  4650. var nElements = md.nquad_smooth_uv;
  4651. if ( nElements ) {
  4652. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4653. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4654. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  4655. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  4656. init_uvs4( nElements, offsetUvs );
  4657. }
  4658. };
  4659. };
  4660. function vertex ( scope, x, y, z ) {
  4661. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  4662. };
  4663. function f3 ( scope, a, b, c, mi ) {
  4664. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  4665. };
  4666. function f4 ( scope, a, b, c, d, mi ) {
  4667. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  4668. };
  4669. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  4670. var nax = normals[ na*3 ],
  4671. nay = normals[ na*3 + 1 ],
  4672. naz = normals[ na*3 + 2 ],
  4673. nbx = normals[ nb*3 ],
  4674. nby = normals[ nb*3 + 1 ],
  4675. nbz = normals[ nb*3 + 2 ],
  4676. ncx = normals[ nc*3 ],
  4677. ncy = normals[ nc*3 + 1 ],
  4678. ncz = normals[ nc*3 + 2 ];
  4679. scope.faces.push( new THREE.Face3( a, b, c,
  4680. [new THREE.Vector3( nax, nay, naz ),
  4681. new THREE.Vector3( nbx, nby, nbz ),
  4682. new THREE.Vector3( ncx, ncy, ncz )],
  4683. null,
  4684. mi ) );
  4685. };
  4686. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  4687. var nax = normals[ na*3 ],
  4688. nay = normals[ na*3 + 1 ],
  4689. naz = normals[ na*3 + 2 ],
  4690. nbx = normals[ nb*3 ],
  4691. nby = normals[ nb*3 + 1 ],
  4692. nbz = normals[ nb*3 + 2 ],
  4693. ncx = normals[ nc*3 ],
  4694. ncy = normals[ nc*3 + 1 ],
  4695. ncz = normals[ nc*3 + 2 ],
  4696. ndx = normals[ nd*3 ],
  4697. ndy = normals[ nd*3 + 1 ],
  4698. ndz = normals[ nd*3 + 2 ];
  4699. scope.faces.push( new THREE.Face4( a, b, c, d,
  4700. [new THREE.Vector3( nax, nay, naz ),
  4701. new THREE.Vector3( nbx, nby, nbz ),
  4702. new THREE.Vector3( ncx, ncy, ncz ),
  4703. new THREE.Vector3( ndx, ndy, ndz )],
  4704. null,
  4705. mi ) );
  4706. };
  4707. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  4708. var uv = [];
  4709. uv.push( new THREE.UV( u1, v1 ) );
  4710. uv.push( new THREE.UV( u2, v2 ) );
  4711. uv.push( new THREE.UV( u3, v3 ) );
  4712. where.push( uv );
  4713. };
  4714. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  4715. var uv = [];
  4716. uv.push( new THREE.UV( u1, v1 ) );
  4717. uv.push( new THREE.UV( u2, v2 ) );
  4718. uv.push( new THREE.UV( u3, v3 ) );
  4719. uv.push( new THREE.UV( u4, v4 ) );
  4720. where.push( uv );
  4721. };
  4722. Model.prototype = Object.create( THREE.Geometry.prototype );
  4723. callback( new Model( texturePath ) );
  4724. };
  4725. /**
  4726. * @author mrdoob / http://mrdoob.com/
  4727. */
  4728. THREE.ImageLoader = function () {
  4729. THREE.EventTarget.call( this );
  4730. this.crossOrigin = null;
  4731. };
  4732. THREE.ImageLoader.prototype = {
  4733. constructor: THREE.ImageLoader,
  4734. load: function ( url, image ) {
  4735. var scope = this;
  4736. if ( image === undefined ) image = new Image();
  4737. image.addEventListener( 'load', function () {
  4738. scope.dispatchEvent( { type: 'load', content: image } );
  4739. }, false );
  4740. image.addEventListener( 'error', function () {
  4741. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  4742. }, false );
  4743. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  4744. image.src = url;
  4745. }
  4746. }
  4747. /**
  4748. * @author mrdoob / http://mrdoob.com/
  4749. * @author alteredq / http://alteredqualia.com/
  4750. */
  4751. THREE.JSONLoader = function ( showStatus ) {
  4752. THREE.Loader.call( this, showStatus );
  4753. };
  4754. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  4755. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  4756. var scope = this;
  4757. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  4758. this.onLoadStart();
  4759. this.loadAjaxJSON( this, url, callback, texturePath );
  4760. };
  4761. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  4762. var xhr = new XMLHttpRequest();
  4763. var length = 0;
  4764. xhr.onreadystatechange = function () {
  4765. if ( xhr.readyState === xhr.DONE ) {
  4766. if ( xhr.status === 200 || xhr.status === 0 ) {
  4767. if ( xhr.responseText ) {
  4768. var json = JSON.parse( xhr.responseText );
  4769. context.createModel( json, callback, texturePath );
  4770. } else {
  4771. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  4772. }
  4773. // in context of more complex asset initialization
  4774. // do not block on single failed file
  4775. // maybe should go even one more level up
  4776. context.onLoadComplete();
  4777. } else {
  4778. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  4779. }
  4780. } else if ( xhr.readyState === xhr.LOADING ) {
  4781. if ( callbackProgress ) {
  4782. if ( length === 0 ) {
  4783. length = xhr.getResponseHeader( "Content-Length" );
  4784. }
  4785. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  4786. }
  4787. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  4788. length = xhr.getResponseHeader( "Content-Length" );
  4789. }
  4790. };
  4791. xhr.open( "GET", url, true );
  4792. xhr.send( null );
  4793. };
  4794. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  4795. var scope = this,
  4796. geometry = new THREE.Geometry(),
  4797. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  4798. this.initMaterials( geometry, json.materials, texturePath );
  4799. parseModel( scale );
  4800. parseSkin();
  4801. parseMorphing( scale );
  4802. geometry.computeCentroids();
  4803. geometry.computeFaceNormals();
  4804. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  4805. function parseModel( scale ) {
  4806. function isBitSet( value, position ) {
  4807. return value & ( 1 << position );
  4808. }
  4809. var i, j, fi,
  4810. offset, zLength, nVertices,
  4811. colorIndex, normalIndex, uvIndex, materialIndex,
  4812. type,
  4813. isQuad,
  4814. hasMaterial,
  4815. hasFaceUv, hasFaceVertexUv,
  4816. hasFaceNormal, hasFaceVertexNormal,
  4817. hasFaceColor, hasFaceVertexColor,
  4818. vertex, face, color, normal,
  4819. uvLayer, uvs, u, v,
  4820. faces = json.faces,
  4821. vertices = json.vertices,
  4822. normals = json.normals,
  4823. colors = json.colors,
  4824. nUvLayers = 0;
  4825. // disregard empty arrays
  4826. for ( i = 0; i < json.uvs.length; i++ ) {
  4827. if ( json.uvs[ i ].length ) nUvLayers ++;
  4828. }
  4829. for ( i = 0; i < nUvLayers; i++ ) {
  4830. geometry.faceUvs[ i ] = [];
  4831. geometry.faceVertexUvs[ i ] = [];
  4832. }
  4833. offset = 0;
  4834. zLength = vertices.length;
  4835. while ( offset < zLength ) {
  4836. vertex = new THREE.Vector3();
  4837. vertex.x = vertices[ offset ++ ] * scale;
  4838. vertex.y = vertices[ offset ++ ] * scale;
  4839. vertex.z = vertices[ offset ++ ] * scale;
  4840. geometry.vertices.push( vertex );
  4841. }
  4842. offset = 0;
  4843. zLength = faces.length;
  4844. while ( offset < zLength ) {
  4845. type = faces[ offset ++ ];
  4846. isQuad = isBitSet( type, 0 );
  4847. hasMaterial = isBitSet( type, 1 );
  4848. hasFaceUv = isBitSet( type, 2 );
  4849. hasFaceVertexUv = isBitSet( type, 3 );
  4850. hasFaceNormal = isBitSet( type, 4 );
  4851. hasFaceVertexNormal = isBitSet( type, 5 );
  4852. hasFaceColor = isBitSet( type, 6 );
  4853. hasFaceVertexColor = isBitSet( type, 7 );
  4854. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  4855. if ( isQuad ) {
  4856. face = new THREE.Face4();
  4857. face.a = faces[ offset ++ ];
  4858. face.b = faces[ offset ++ ];
  4859. face.c = faces[ offset ++ ];
  4860. face.d = faces[ offset ++ ];
  4861. nVertices = 4;
  4862. } else {
  4863. face = new THREE.Face3();
  4864. face.a = faces[ offset ++ ];
  4865. face.b = faces[ offset ++ ];
  4866. face.c = faces[ offset ++ ];
  4867. nVertices = 3;
  4868. }
  4869. if ( hasMaterial ) {
  4870. materialIndex = faces[ offset ++ ];
  4871. face.materialIndex = materialIndex;
  4872. }
  4873. // to get face <=> uv index correspondence
  4874. fi = geometry.faces.length;
  4875. if ( hasFaceUv ) {
  4876. for ( i = 0; i < nUvLayers; i++ ) {
  4877. uvLayer = json.uvs[ i ];
  4878. uvIndex = faces[ offset ++ ];
  4879. u = uvLayer[ uvIndex * 2 ];
  4880. v = uvLayer[ uvIndex * 2 + 1 ];
  4881. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  4882. }
  4883. }
  4884. if ( hasFaceVertexUv ) {
  4885. for ( i = 0; i < nUvLayers; i++ ) {
  4886. uvLayer = json.uvs[ i ];
  4887. uvs = [];
  4888. for ( j = 0; j < nVertices; j ++ ) {
  4889. uvIndex = faces[ offset ++ ];
  4890. u = uvLayer[ uvIndex * 2 ];
  4891. v = uvLayer[ uvIndex * 2 + 1 ];
  4892. uvs[ j ] = new THREE.UV( u, v );
  4893. }
  4894. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  4895. }
  4896. }
  4897. if ( hasFaceNormal ) {
  4898. normalIndex = faces[ offset ++ ] * 3;
  4899. normal = new THREE.Vector3();
  4900. normal.x = normals[ normalIndex ++ ];
  4901. normal.y = normals[ normalIndex ++ ];
  4902. normal.z = normals[ normalIndex ];
  4903. face.normal = normal;
  4904. }
  4905. if ( hasFaceVertexNormal ) {
  4906. for ( i = 0; i < nVertices; i++ ) {
  4907. normalIndex = faces[ offset ++ ] * 3;
  4908. normal = new THREE.Vector3();
  4909. normal.x = normals[ normalIndex ++ ];
  4910. normal.y = normals[ normalIndex ++ ];
  4911. normal.z = normals[ normalIndex ];
  4912. face.vertexNormals.push( normal );
  4913. }
  4914. }
  4915. if ( hasFaceColor ) {
  4916. colorIndex = faces[ offset ++ ];
  4917. color = new THREE.Color( colors[ colorIndex ] );
  4918. face.color = color;
  4919. }
  4920. if ( hasFaceVertexColor ) {
  4921. for ( i = 0; i < nVertices; i++ ) {
  4922. colorIndex = faces[ offset ++ ];
  4923. color = new THREE.Color( colors[ colorIndex ] );
  4924. face.vertexColors.push( color );
  4925. }
  4926. }
  4927. geometry.faces.push( face );
  4928. }
  4929. };
  4930. function parseSkin() {
  4931. var i, l, x, y, z, w, a, b, c, d;
  4932. if ( json.skinWeights ) {
  4933. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  4934. x = json.skinWeights[ i ];
  4935. y = json.skinWeights[ i + 1 ];
  4936. z = 0;
  4937. w = 0;
  4938. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  4939. }
  4940. }
  4941. if ( json.skinIndices ) {
  4942. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  4943. a = json.skinIndices[ i ];
  4944. b = json.skinIndices[ i + 1 ];
  4945. c = 0;
  4946. d = 0;
  4947. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  4948. }
  4949. }
  4950. geometry.bones = json.bones;
  4951. geometry.animation = json.animation;
  4952. };
  4953. function parseMorphing( scale ) {
  4954. if ( json.morphTargets !== undefined ) {
  4955. var i, l, v, vl, dstVertices, srcVertices;
  4956. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  4957. geometry.morphTargets[ i ] = {};
  4958. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  4959. geometry.morphTargets[ i ].vertices = [];
  4960. dstVertices = geometry.morphTargets[ i ].vertices;
  4961. srcVertices = json.morphTargets [ i ].vertices;
  4962. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  4963. var vertex = new THREE.Vector3();
  4964. vertex.x = srcVertices[ v ] * scale;
  4965. vertex.y = srcVertices[ v + 1 ] * scale;
  4966. vertex.z = srcVertices[ v + 2 ] * scale;
  4967. dstVertices.push( vertex );
  4968. }
  4969. }
  4970. }
  4971. if ( json.morphColors !== undefined ) {
  4972. var i, l, c, cl, dstColors, srcColors, color;
  4973. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  4974. geometry.morphColors[ i ] = {};
  4975. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  4976. geometry.morphColors[ i ].colors = [];
  4977. dstColors = geometry.morphColors[ i ].colors;
  4978. srcColors = json.morphColors [ i ].colors;
  4979. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  4980. color = new THREE.Color( 0xffaa00 );
  4981. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  4982. dstColors.push( color );
  4983. }
  4984. }
  4985. }
  4986. };
  4987. callback( geometry );
  4988. };
  4989. /**
  4990. * @author mrdoob / http://mrdoob.com/
  4991. */
  4992. THREE.LoadingMonitor = function () {
  4993. THREE.EventTarget.call( this );
  4994. var scope = this;
  4995. var loaded = 0;
  4996. var total = 0;
  4997. var onLoad = function ( event ) {
  4998. loaded ++;
  4999. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5000. if ( loaded === total ) {
  5001. scope.dispatchEvent( { type: 'load' } );
  5002. }
  5003. };
  5004. this.add = function ( loader ) {
  5005. total ++;
  5006. loader.addEventListener( 'load', onLoad, false );
  5007. };
  5008. };
  5009. /**
  5010. * @author mrdoob / http://mrdoob.com/
  5011. * @author alteredq / http://alteredqualia.com/
  5012. */
  5013. THREE.GeometryLoader = function () {
  5014. THREE.EventTarget.call( this );
  5015. this.crossOrigin = null;
  5016. this.path = null;
  5017. };
  5018. THREE.GeometryLoader.prototype = {
  5019. constructor: THREE.GeometryLoader,
  5020. load: function ( url ) {
  5021. var scope = this;
  5022. var geometry = null;
  5023. if ( scope.path === null ) {
  5024. var parts = url.split( '/' ); parts.pop();
  5025. scope.path = ( parts.length < 1 ? '.' : parts.join( '/' ) );
  5026. }
  5027. //
  5028. var xhr = new XMLHttpRequest();
  5029. xhr.addEventListener( 'load', function ( event ) {
  5030. if ( event.target.responseText ) {
  5031. geometry = scope.parse( JSON.parse( event.target.responseText ), monitor );
  5032. } else {
  5033. scope.dispatchEvent( { type: 'error', message: 'Invalid file [' + url + ']' } );
  5034. }
  5035. }, false );
  5036. xhr.addEventListener( 'error', function () {
  5037. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5038. }, false );
  5039. xhr.open( 'GET', url, true );
  5040. xhr.send( null );
  5041. //
  5042. var monitor = new THREE.LoadingMonitor();
  5043. monitor.addEventListener( 'load', function ( event ) {
  5044. scope.dispatchEvent( { type: 'load', content: geometry } );
  5045. } );
  5046. monitor.add( xhr );
  5047. },
  5048. parse: function ( data, monitor ) {
  5049. var scope = this;
  5050. var geometry = new THREE.Geometry();
  5051. var scale = ( data.scale !== undefined ) ? 1 / data.scale : 1;
  5052. // materials
  5053. if ( data.materials ) {
  5054. geometry.materials = [];
  5055. for ( var i = 0; i < data.materials.length; ++ i ) {
  5056. var m = data.materials[ i ];
  5057. function isPow2( n ) {
  5058. var l = Math.log( n ) / Math.LN2;
  5059. return Math.floor( l ) == l;
  5060. }
  5061. function nearestPow2( n ) {
  5062. var l = Math.log( n ) / Math.LN2;
  5063. return Math.pow( 2, Math.round( l ) );
  5064. }
  5065. function createTexture( where, name, sourceFile, repeat, offset, wrap ) {
  5066. where[ name ] = new THREE.Texture();
  5067. where[ name ].sourceFile = sourceFile;
  5068. if ( repeat ) {
  5069. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  5070. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  5071. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  5072. }
  5073. if ( offset ) {
  5074. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  5075. }
  5076. if ( wrap ) {
  5077. var wrapMap = {
  5078. "repeat": THREE.RepeatWrapping,
  5079. "mirror": THREE.MirroredRepeatWrapping
  5080. }
  5081. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  5082. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  5083. }
  5084. // load image
  5085. var texture = where[ name ];
  5086. var loader = new THREE.ImageLoader();
  5087. loader.addEventListener( 'load', function ( event ) {
  5088. var image = event.content;
  5089. if ( !isPow2( image.width ) || !isPow2( image.height ) ) {
  5090. var width = nearestPow2( image.width );
  5091. var height = nearestPow2( image.height );
  5092. texture.image = document.createElement( 'canvas' );
  5093. texture.image.width = width;
  5094. texture.image.height = height;
  5095. texture.image.getContext( '2d' ).drawImage( image, 0, 0, width, height );
  5096. } else {
  5097. texture.image = image;
  5098. }
  5099. texture.needsUpdate = true;
  5100. } );
  5101. loader.crossOrigin = scope.crossOrigin;
  5102. loader.load( scope.path + '/' + sourceFile );
  5103. if ( monitor ) monitor.add( loader );
  5104. }
  5105. function rgb2hex( rgb ) {
  5106. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  5107. }
  5108. // defaults
  5109. var mtype = "MeshLambertMaterial";
  5110. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  5111. // parameters from model file
  5112. if ( m.shading ) {
  5113. var shading = m.shading.toLowerCase();
  5114. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  5115. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  5116. }
  5117. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  5118. mpars.blending = THREE[ m.blending ];
  5119. }
  5120. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  5121. mpars.transparent = m.transparent;
  5122. }
  5123. if ( m.depthTest !== undefined ) {
  5124. mpars.depthTest = m.depthTest;
  5125. }
  5126. if ( m.depthWrite !== undefined ) {
  5127. mpars.depthWrite = m.depthWrite;
  5128. }
  5129. if ( m.vertexColors !== undefined ) {
  5130. if ( m.vertexColors == "face" ) {
  5131. mpars.vertexColors = THREE.FaceColors;
  5132. } else if ( m.vertexColors ) {
  5133. mpars.vertexColors = THREE.VertexColors;
  5134. }
  5135. }
  5136. // colors
  5137. if ( m.colorDiffuse ) {
  5138. mpars.color = rgb2hex( m.colorDiffuse );
  5139. } else if ( m.DbgColor ) {
  5140. mpars.color = m.DbgColor;
  5141. }
  5142. if ( m.colorSpecular ) {
  5143. mpars.specular = rgb2hex( m.colorSpecular );
  5144. }
  5145. if ( m.colorAmbient ) {
  5146. mpars.ambient = rgb2hex( m.colorAmbient );
  5147. }
  5148. // modifiers
  5149. if ( m.transparency ) {
  5150. mpars.opacity = m.transparency;
  5151. }
  5152. if ( m.specularCoef ) {
  5153. mpars.shininess = m.specularCoef;
  5154. }
  5155. if ( m.visible !== undefined ) {
  5156. mpars.visible = m.visible;
  5157. }
  5158. if ( m.flipSided !== undefined ) {
  5159. mpars.side = THREE.BackSide;
  5160. }
  5161. if ( m.doubleSided !== undefined ) {
  5162. mpars.side = THREE.DoubleSide;
  5163. }
  5164. if ( m.wireframe !== undefined ) {
  5165. mpars.wireframe = m.wireframe;
  5166. }
  5167. // textures
  5168. if ( m.mapDiffuse ) {
  5169. createTexture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  5170. }
  5171. if ( m.mapLight ) {
  5172. createTexture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  5173. }
  5174. if ( m.mapBump ) {
  5175. createTexture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap );
  5176. }
  5177. if ( m.mapNormal ) {
  5178. createTexture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  5179. }
  5180. if ( m.mapSpecular ) {
  5181. createTexture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  5182. }
  5183. // special case for normal mapped material
  5184. if ( m.mapNormal ) {
  5185. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5186. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5187. uniforms[ "tNormal" ].value = mpars.normalMap;
  5188. if ( m.mapNormalFactor ) {
  5189. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5190. }
  5191. if ( mpars.map ) {
  5192. uniforms[ "tDiffuse" ].value = mpars.map;
  5193. uniforms[ "enableDiffuse" ].value = true;
  5194. }
  5195. if ( mpars.specularMap ) {
  5196. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5197. uniforms[ "enableSpecular" ].value = true;
  5198. }
  5199. if ( mpars.lightMap ) {
  5200. uniforms[ "tAO" ].value = mpars.lightMap;
  5201. uniforms[ "enableAO" ].value = true;
  5202. }
  5203. // for the moment don't handle displacement texture
  5204. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5205. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5206. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5207. uniforms[ "uShininess" ].value = mpars.shininess;
  5208. if ( mpars.opacity !== undefined ) {
  5209. uniforms[ "uOpacity" ].value = mpars.opacity;
  5210. }
  5211. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5212. var material = new THREE.ShaderMaterial( parameters );
  5213. } else {
  5214. var material = new THREE[ mtype ]( mpars );
  5215. }
  5216. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5217. geometry.materials[ i ] = material;
  5218. }
  5219. }
  5220. // geometry
  5221. function isBitSet( value, position ) {
  5222. return value & ( 1 << position );
  5223. }
  5224. var faces = data.faces;
  5225. var vertices = data.vertices;
  5226. var normals = data.normals;
  5227. var colors = data.colors;
  5228. var nUvLayers = 0;
  5229. // disregard empty arrays
  5230. if ( data.uvs ) {
  5231. for ( var i = 0; i < data.uvs.length; i ++ ) {
  5232. if ( data.uvs[ i ].length ) nUvLayers ++;
  5233. }
  5234. }
  5235. for ( var i = 0; i < nUvLayers; i ++ ) {
  5236. geometry.faceUvs[ i ] = [];
  5237. geometry.faceVertexUvs[ i ] = [];
  5238. }
  5239. var offset = 0;
  5240. var zLength = vertices.length;
  5241. while ( offset < zLength ) {
  5242. var vertex = new THREE.Vector3();
  5243. vertex.x = vertices[ offset ++ ] * scale;
  5244. vertex.y = vertices[ offset ++ ] * scale;
  5245. vertex.z = vertices[ offset ++ ] * scale;
  5246. geometry.vertices.push( vertex );
  5247. }
  5248. offset = 0;
  5249. zLength = faces.length;
  5250. while ( offset < zLength ) {
  5251. var type = faces[ offset ++ ];
  5252. var isQuad = isBitSet( type, 0 );
  5253. var hasMaterial = isBitSet( type, 1 );
  5254. var hasFaceUv = isBitSet( type, 2 );
  5255. var hasFaceVertexUv = isBitSet( type, 3 );
  5256. var hasFaceNormal = isBitSet( type, 4 );
  5257. var hasFaceVertexNormal = isBitSet( type, 5 );
  5258. var hasFaceColor = isBitSet( type, 6 );
  5259. var hasFaceVertexColor = isBitSet( type, 7 );
  5260. // console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5261. if ( isQuad ) {
  5262. var face = new THREE.Face4();
  5263. face.a = faces[ offset ++ ];
  5264. face.b = faces[ offset ++ ];
  5265. face.c = faces[ offset ++ ];
  5266. face.d = faces[ offset ++ ];
  5267. var nVertices = 4;
  5268. } else {
  5269. var face = new THREE.Face3();
  5270. face.a = faces[ offset ++ ];
  5271. face.b = faces[ offset ++ ];
  5272. face.c = faces[ offset ++ ];
  5273. var nVertices = 3;
  5274. }
  5275. if ( hasMaterial ) {
  5276. var materialIndex = faces[ offset ++ ];
  5277. face.materialIndex = materialIndex;
  5278. }
  5279. // to get face <=> uv index correspondence
  5280. var fi = geometry.faces.length;
  5281. if ( hasFaceUv ) {
  5282. for ( var i = 0; i < nUvLayers; i ++ ) {
  5283. var uvLayer = data.uvs[ i ];
  5284. var uvIndex = faces[ offset ++ ];
  5285. var u = uvLayer[ uvIndex * 2 ];
  5286. var v = uvLayer[ uvIndex * 2 + 1 ];
  5287. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5288. }
  5289. }
  5290. if ( hasFaceVertexUv ) {
  5291. for ( var i = 0; i < nUvLayers; i ++ ) {
  5292. var uvLayer = data.uvs[ i ];
  5293. var uvs = [];
  5294. for ( var j = 0; j < nVertices; j ++ ) {
  5295. var uvIndex = faces[ offset ++ ];
  5296. var u = uvLayer[ uvIndex * 2 ];
  5297. var v = uvLayer[ uvIndex * 2 + 1 ];
  5298. uvs[ j ] = new THREE.UV( u, v );
  5299. }
  5300. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5301. }
  5302. }
  5303. if ( hasFaceNormal ) {
  5304. var normalIndex = faces[ offset ++ ] * 3;
  5305. var normal = new THREE.Vector3();
  5306. normal.x = normals[ normalIndex ++ ];
  5307. normal.y = normals[ normalIndex ++ ];
  5308. normal.z = normals[ normalIndex ];
  5309. face.normal = normal;
  5310. }
  5311. if ( hasFaceVertexNormal ) {
  5312. for ( i = 0; i < nVertices; i ++ ) {
  5313. var normalIndex = faces[ offset ++ ] * 3;
  5314. var normal = new THREE.Vector3();
  5315. normal.x = normals[ normalIndex ++ ];
  5316. normal.y = normals[ normalIndex ++ ];
  5317. normal.z = normals[ normalIndex ];
  5318. face.vertexNormals.push( normal );
  5319. }
  5320. }
  5321. if ( hasFaceColor ) {
  5322. var colorIndex = faces[ offset ++ ];
  5323. face.color = new THREE.Color( colors[ colorIndex ] );
  5324. }
  5325. if ( hasFaceVertexColor ) {
  5326. for ( var i = 0; i < nVertices; i ++ ) {
  5327. var colorIndex = faces[ offset ++ ];
  5328. face.vertexColors.push( new THREE.Color( colors[ colorIndex ] ) );
  5329. }
  5330. }
  5331. geometry.faces.push( face );
  5332. }
  5333. // skin
  5334. if ( data.skinWeights ) {
  5335. for ( var i = 0, l = data.skinWeights.length; i < l; i += 2 ) {
  5336. var x = data.skinWeights[ i ];
  5337. var y = data.skinWeights[ i + 1 ];
  5338. var z = 0;
  5339. var w = 0;
  5340. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5341. }
  5342. }
  5343. if ( data.skinIndices ) {
  5344. for ( var i = 0, l = data.skinIndices.length; i < l; i += 2 ) {
  5345. var a = data.skinIndices[ i ];
  5346. var b = data.skinIndices[ i + 1 ];
  5347. var c = 0;
  5348. var d = 0;
  5349. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5350. }
  5351. }
  5352. geometry.bones = data.bones;
  5353. geometry.animation = data.animation;
  5354. // morphing
  5355. if ( data.morphTargets ) {
  5356. for ( var i = 0, l = data.morphTargets.length; i < l; i ++ ) {
  5357. geometry.morphTargets[ i ] = {};
  5358. geometry.morphTargets[ i ].name = data.morphTargets[ i ].name;
  5359. geometry.morphTargets[ i ].vertices = [];
  5360. var dstVertices = geometry.morphTargets[ i ].vertices;
  5361. var srcVertices = data.morphTargets [ i ].vertices;
  5362. for( var v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5363. var vertex = new THREE.Vector3();
  5364. vertex.x = srcVertices[ v ] * scale;
  5365. vertex.y = srcVertices[ v + 1 ] * scale;
  5366. vertex.z = srcVertices[ v + 2 ] * scale;
  5367. dstVertices.push( vertex );
  5368. }
  5369. }
  5370. }
  5371. if ( data.morphColors ) {
  5372. for ( var i = 0, l = data.morphColors.length; i < l; i++ ) {
  5373. geometry.morphColors[ i ] = {};
  5374. geometry.morphColors[ i ].name = data.morphColors[ i ].name;
  5375. geometry.morphColors[ i ].colors = [];
  5376. var dstColors = geometry.morphColors[ i ].colors;
  5377. var srcColors = data.morphColors [ i ].colors;
  5378. for ( var c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5379. var color = new THREE.Color( 0xffaa00 );
  5380. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5381. dstColors.push( color );
  5382. }
  5383. }
  5384. }
  5385. geometry.computeCentroids();
  5386. geometry.computeFaceNormals();
  5387. return geometry;
  5388. }
  5389. };
  5390. /**
  5391. * @author alteredq / http://alteredqualia.com/
  5392. */
  5393. THREE.SceneLoader = function () {
  5394. this.onLoadStart = function () {};
  5395. this.onLoadProgress = function() {};
  5396. this.onLoadComplete = function () {};
  5397. this.callbackSync = function () {};
  5398. this.callbackProgress = function () {};
  5399. this.geometryHandlerMap = {};
  5400. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5401. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5402. };
  5403. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5404. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5405. var scope = this;
  5406. var xhr = new XMLHttpRequest();
  5407. xhr.onreadystatechange = function () {
  5408. if ( xhr.readyState === 4 ) {
  5409. if ( xhr.status === 200 || xhr.status === 0 ) {
  5410. var json = JSON.parse( xhr.responseText );
  5411. scope.parse( json, callbackFinished, url );
  5412. } else {
  5413. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5414. }
  5415. }
  5416. };
  5417. xhr.open( "GET", url, true );
  5418. xhr.send( null );
  5419. };
  5420. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5421. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5422. };
  5423. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5424. var scope = this;
  5425. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5426. var dg, dm, dl, dc, df, dt,
  5427. g, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  5428. geometry, material, camera, fog,
  5429. texture, images,
  5430. light,
  5431. counter_models, counter_textures,
  5432. total_models, total_textures,
  5433. result;
  5434. var data = json;
  5435. // async geometry loaders
  5436. for ( var typeID in this.geometryHandlerMap ) {
  5437. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5438. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5439. }
  5440. counter_models = 0;
  5441. counter_textures = 0;
  5442. result = {
  5443. scene: new THREE.Scene(),
  5444. geometries: {},
  5445. materials: {},
  5446. textures: {},
  5447. objects: {},
  5448. cameras: {},
  5449. lights: {},
  5450. fogs: {},
  5451. empties: {}
  5452. };
  5453. if ( data.transform ) {
  5454. var position = data.transform.position,
  5455. rotation = data.transform.rotation,
  5456. scale = data.transform.scale;
  5457. if ( position )
  5458. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5459. if ( rotation )
  5460. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5461. if ( scale )
  5462. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5463. if ( position || rotation || scale ) {
  5464. result.scene.updateMatrix();
  5465. result.scene.updateMatrixWorld();
  5466. }
  5467. }
  5468. function get_url( source_url, url_type ) {
  5469. if ( url_type == "relativeToHTML" ) {
  5470. return source_url;
  5471. } else {
  5472. return urlBase + "/" + source_url;
  5473. }
  5474. };
  5475. // toplevel loader function, delegates to handle_children
  5476. function handle_objects() {
  5477. handle_children( result.scene, data.objects );
  5478. }
  5479. // handle all the children from the loaded json and attach them to given parent
  5480. function handle_children( parent, children ) {
  5481. for ( var dd in children ) {
  5482. // check by id if child has already been handled,
  5483. // if not, create new object
  5484. if ( result.objects[ dd ] === undefined ) {
  5485. var o = children[ dd ];
  5486. var object = null;
  5487. if ( o.geometry !== undefined ) {
  5488. geometry = result.geometries[ o.geometry ];
  5489. // geometry already loaded
  5490. if ( geometry ) {
  5491. var hasNormals = false;
  5492. // not anymore support for multiple materials
  5493. // shouldn't really be array
  5494. material = result.materials[ o.materials[ 0 ] ];
  5495. hasNormals = material instanceof THREE.ShaderMaterial;
  5496. if ( hasNormals ) {
  5497. geometry.computeTangents();
  5498. }
  5499. p = o.position;
  5500. r = o.rotation;
  5501. q = o.quaternion;
  5502. s = o.scale;
  5503. m = o.matrix;
  5504. // turn off quaternions, for the moment
  5505. q = 0;
  5506. if ( o.materials.length === 0 ) {
  5507. material = new THREE.MeshFaceMaterial();
  5508. }
  5509. // dirty hack to handle meshes with multiple materials
  5510. // just use face materials defined in model
  5511. if ( o.materials.length > 1 ) {
  5512. material = new THREE.MeshFaceMaterial();
  5513. }
  5514. if ( o.morph ) {
  5515. object = new THREE.MorphAnimMesh( geometry, material );
  5516. if ( o.duration !== undefined ) {
  5517. object.duration = o.duration;
  5518. }
  5519. if ( o.time !== undefined ) {
  5520. object.time = o.time;
  5521. }
  5522. if ( o.mirroredLoop !== undefined ) {
  5523. object.mirroredLoop = o.mirroredLoop;
  5524. }
  5525. if ( material.morphNormals ) {
  5526. geometry.computeMorphNormals();
  5527. }
  5528. } else {
  5529. object = new THREE.Mesh( geometry, material );
  5530. }
  5531. object.name = dd;
  5532. if ( m ) {
  5533. object.matrixAutoUpdate = false;
  5534. object.matrix.set(
  5535. m[0], m[1], m[2], m[3],
  5536. m[4], m[5], m[6], m[7],
  5537. m[8], m[9], m[10], m[11],
  5538. m[12], m[13], m[14], m[15]
  5539. );
  5540. } else {
  5541. object.position.set( p[0], p[1], p[2] );
  5542. if ( q ) {
  5543. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5544. object.useQuaternion = true;
  5545. } else {
  5546. object.rotation.set( r[0], r[1], r[2] );
  5547. }
  5548. object.scale.set( s[0], s[1], s[2] );
  5549. }
  5550. object.visible = o.visible;
  5551. object.castShadow = o.castShadow;
  5552. object.receiveShadow = o.receiveShadow;
  5553. parent.add( object );
  5554. result.objects[ dd ] = object;
  5555. }
  5556. // pure Object3D
  5557. } else {
  5558. p = o.position;
  5559. r = o.rotation;
  5560. q = o.quaternion;
  5561. s = o.scale;
  5562. // turn off quaternions, for the moment
  5563. q = 0;
  5564. object = new THREE.Object3D();
  5565. object.name = dd;
  5566. object.position.set( p[0], p[1], p[2] );
  5567. if ( q ) {
  5568. object.quaternion.set( q[0], q[1], q[2], q[3] );
  5569. object.useQuaternion = true;
  5570. } else {
  5571. object.rotation.set( r[0], r[1], r[2] );
  5572. }
  5573. object.scale.set( s[0], s[1], s[2] );
  5574. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  5575. parent.add( object );
  5576. result.objects[ dd ] = object;
  5577. result.empties[ dd ] = object;
  5578. }
  5579. if ( object ) {
  5580. if ( o.properties !== undefined ) {
  5581. for ( var key in o.properties ) {
  5582. var value = o.properties[ key ];
  5583. object.properties[ key ] = value;
  5584. }
  5585. }
  5586. if ( o.children !== undefined ) {
  5587. handle_children( object, o.children );
  5588. }
  5589. }
  5590. }
  5591. }
  5592. };
  5593. function handle_mesh( geo, id ) {
  5594. result.geometries[ id ] = geo;
  5595. handle_objects();
  5596. };
  5597. function create_callback( id ) {
  5598. return function( geo ) {
  5599. handle_mesh( geo, id );
  5600. counter_models -= 1;
  5601. scope.onLoadComplete();
  5602. async_callback_gate();
  5603. }
  5604. };
  5605. function create_callback_embed( id ) {
  5606. return function( geo ) {
  5607. result.geometries[ id ] = geo;
  5608. }
  5609. };
  5610. function async_callback_gate() {
  5611. var progress = {
  5612. totalModels : total_models,
  5613. totalTextures : total_textures,
  5614. loadedModels : total_models - counter_models,
  5615. loadedTextures : total_textures - counter_textures
  5616. };
  5617. scope.callbackProgress( progress, result );
  5618. scope.onLoadProgress();
  5619. if ( counter_models === 0 && counter_textures === 0 ) {
  5620. callbackFinished( result );
  5621. }
  5622. };
  5623. var callbackTexture = function ( count ) {
  5624. counter_textures -= count;
  5625. async_callback_gate();
  5626. scope.onLoadComplete();
  5627. };
  5628. // must use this instead of just directly calling callbackTexture
  5629. // because of closure in the calling context loop
  5630. var generateTextureCallback = function ( count ) {
  5631. return function() {
  5632. callbackTexture( count );
  5633. };
  5634. };
  5635. // first go synchronous elements
  5636. // cameras
  5637. for( dc in data.cameras ) {
  5638. c = data.cameras[ dc ];
  5639. if ( c.type === "perspective" ) {
  5640. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  5641. } else if ( c.type === "ortho" ) {
  5642. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  5643. }
  5644. p = c.position;
  5645. t = c.target;
  5646. u = c.up;
  5647. camera.position.set( p[0], p[1], p[2] );
  5648. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  5649. if ( u ) camera.up.set( u[0], u[1], u[2] );
  5650. result.cameras[ dc ] = camera;
  5651. }
  5652. // lights
  5653. var hex, intensity;
  5654. for ( dl in data.lights ) {
  5655. l = data.lights[ dl ];
  5656. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  5657. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  5658. if ( l.type === "directional" ) {
  5659. p = l.direction;
  5660. light = new THREE.DirectionalLight( hex, intensity );
  5661. light.position.set( p[0], p[1], p[2] );
  5662. light.position.normalize();
  5663. } else if ( l.type === "point" ) {
  5664. p = l.position;
  5665. d = l.distance;
  5666. light = new THREE.PointLight( hex, intensity, d );
  5667. light.position.set( p[0], p[1], p[2] );
  5668. } else if ( l.type === "ambient" ) {
  5669. light = new THREE.AmbientLight( hex );
  5670. }
  5671. result.scene.add( light );
  5672. result.lights[ dl ] = light;
  5673. }
  5674. // fogs
  5675. for( df in data.fogs ) {
  5676. f = data.fogs[ df ];
  5677. if ( f.type === "linear" ) {
  5678. fog = new THREE.Fog( 0x000000, f.near, f.far );
  5679. } else if ( f.type === "exp2" ) {
  5680. fog = new THREE.FogExp2( 0x000000, f.density );
  5681. }
  5682. c = f.color;
  5683. fog.color.setRGB( c[0], c[1], c[2] );
  5684. result.fogs[ df ] = fog;
  5685. }
  5686. // defaults
  5687. if ( result.cameras && data.defaults.camera ) {
  5688. result.currentCamera = result.cameras[ data.defaults.camera ];
  5689. }
  5690. if ( result.fogs && data.defaults.fog ) {
  5691. result.scene.fog = result.fogs[ data.defaults.fog ];
  5692. }
  5693. c = data.defaults.bgcolor;
  5694. result.bgColor = new THREE.Color();
  5695. result.bgColor.setRGB( c[0], c[1], c[2] );
  5696. result.bgColorAlpha = data.defaults.bgalpha;
  5697. // now come potentially asynchronous elements
  5698. // geometries
  5699. // count how many models will be loaded asynchronously
  5700. for( dg in data.geometries ) {
  5701. g = data.geometries[ dg ];
  5702. if ( g.type in this.geometryHandlerMap ) {
  5703. counter_models += 1;
  5704. scope.onLoadStart();
  5705. }
  5706. }
  5707. total_models = counter_models;
  5708. for ( dg in data.geometries ) {
  5709. g = data.geometries[ dg ];
  5710. if ( g.type === "cube" ) {
  5711. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.widthSegments, g.heightSegments, g.depthSegments, null, g.flipped, g.sides );
  5712. result.geometries[ dg ] = geometry;
  5713. } else if ( g.type === "plane" ) {
  5714. geometry = new THREE.PlaneGeometry( g.width, g.height, g.widthSegments, g.heightSegments );
  5715. result.geometries[ dg ] = geometry;
  5716. } else if ( g.type === "sphere" ) {
  5717. geometry = new THREE.SphereGeometry( g.radius, g.widthSegments, g.heightSegments );
  5718. result.geometries[ dg ] = geometry;
  5719. } else if ( g.type === "cylinder" ) {
  5720. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  5721. result.geometries[ dg ] = geometry;
  5722. } else if ( g.type === "torus" ) {
  5723. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  5724. result.geometries[ dg ] = geometry;
  5725. } else if ( g.type === "icosahedron" ) {
  5726. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  5727. result.geometries[ dg ] = geometry;
  5728. } else if ( g.type in this.geometryHandlerMap ) {
  5729. var loaderParameters = {};
  5730. for ( var parType in g ) {
  5731. if ( parType !== "type" && parType !== "url" ) {
  5732. loaderParameters[ parType ] = g[ parType ];
  5733. }
  5734. }
  5735. var loader = this.geometryHandlerMap[ g.type ][ "loaderObject" ];
  5736. loader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ), loaderParameters );
  5737. } else if ( g.type === "embedded" ) {
  5738. var modelJson = data.embeds[ g.id ],
  5739. texture_path = "";
  5740. // pass metadata along to jsonLoader so it knows the format version
  5741. modelJson.metadata = data.metadata;
  5742. if ( modelJson ) {
  5743. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  5744. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  5745. }
  5746. }
  5747. }
  5748. // textures
  5749. // count how many textures will be loaded asynchronously
  5750. for( dt in data.textures ) {
  5751. tt = data.textures[ dt ];
  5752. if( tt.url instanceof Array ) {
  5753. counter_textures += tt.url.length;
  5754. for( var n = 0; n < tt.url.length; n ++ ) {
  5755. scope.onLoadStart();
  5756. }
  5757. } else {
  5758. counter_textures += 1;
  5759. scope.onLoadStart();
  5760. }
  5761. }
  5762. total_textures = counter_textures;
  5763. for ( dt in data.textures ) {
  5764. tt = data.textures[ dt ];
  5765. if ( tt.mapping !== undefined && THREE[ tt.mapping ] !== undefined ) {
  5766. tt.mapping = new THREE[ tt.mapping ]();
  5767. }
  5768. if ( tt.url instanceof Array ) {
  5769. var count = tt.url.length;
  5770. var url_array = [];
  5771. for( var i = 0; i < count; i ++ ) {
  5772. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  5773. }
  5774. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  5775. if ( isCompressed ) {
  5776. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5777. } else {
  5778. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, generateTextureCallback( count ) );
  5779. }
  5780. } else {
  5781. var isCompressed = tt.url.toLowerCase().endsWith( ".dds" );
  5782. var fullUrl = get_url( tt.url, data.urlBaseType );
  5783. var textureCallback = generateTextureCallback( 1 );
  5784. if ( isCompressed ) {
  5785. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, tt.mapping, textureCallback );
  5786. } else {
  5787. texture = THREE.ImageUtils.loadTexture( fullUrl, tt.mapping, textureCallback );
  5788. }
  5789. if ( THREE[ tt.minFilter ] !== undefined )
  5790. texture.minFilter = THREE[ tt.minFilter ];
  5791. if ( THREE[ tt.magFilter ] !== undefined )
  5792. texture.magFilter = THREE[ tt.magFilter ];
  5793. if ( tt.anisotropy ) texture.anisotropy = tt.anisotropy;
  5794. if ( tt.repeat ) {
  5795. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  5796. if ( tt.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  5797. if ( tt.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  5798. }
  5799. if ( tt.offset ) {
  5800. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  5801. }
  5802. // handle wrap after repeat so that default repeat can be overriden
  5803. if ( tt.wrap ) {
  5804. var wrapMap = {
  5805. "repeat" : THREE.RepeatWrapping,
  5806. "mirror" : THREE.MirroredRepeatWrapping
  5807. }
  5808. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  5809. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  5810. }
  5811. }
  5812. result.textures[ dt ] = texture;
  5813. }
  5814. // materials
  5815. for ( dm in data.materials ) {
  5816. m = data.materials[ dm ];
  5817. for ( pp in m.parameters ) {
  5818. if ( pp === "envMap" || pp === "map" || pp === "lightMap" || pp === "bumpMap" ) {
  5819. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  5820. } else if ( pp === "shading" ) {
  5821. m.parameters[ pp ] = ( m.parameters[ pp ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  5822. } else if ( pp === "side" ) {
  5823. if ( m.parameters[ pp ] == "double" ) {
  5824. m.parameters[ pp ] = THREE.DoubleSide;
  5825. } else if ( m.parameters[ pp ] == "back" ) {
  5826. m.parameters[ pp ] = THREE.BackSide;
  5827. } else {
  5828. m.parameters[ pp ] = THREE.FrontSide;
  5829. }
  5830. } else if ( pp === "blending" ) {
  5831. m.parameters[ pp ] = m.parameters[ pp ] in THREE ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  5832. } else if ( pp === "combine" ) {
  5833. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  5834. } else if ( pp === "vertexColors" ) {
  5835. if ( m.parameters[ pp ] == "face" ) {
  5836. m.parameters[ pp ] = THREE.FaceColors;
  5837. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  5838. } else if ( m.parameters[ pp ] ) {
  5839. m.parameters[ pp ] = THREE.VertexColors;
  5840. }
  5841. } else if ( pp === "wrapRGB" ) {
  5842. var v3 = m.parameters[ pp ];
  5843. m.parameters[ pp ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  5844. }
  5845. }
  5846. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  5847. m.parameters.transparent = true;
  5848. }
  5849. if ( m.parameters.normalMap ) {
  5850. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5851. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5852. var diffuse = m.parameters.color;
  5853. var specular = m.parameters.specular;
  5854. var ambient = m.parameters.ambient;
  5855. var shininess = m.parameters.shininess;
  5856. uniforms[ "tNormal" ].value = result.textures[ m.parameters.normalMap ];
  5857. if ( m.parameters.normalScale ) {
  5858. uniforms[ "uNormalScale" ].value.set( m.parameters.normalScale[ 0 ], m.parameters.normalScale[ 1 ] );
  5859. }
  5860. if ( m.parameters.map ) {
  5861. uniforms[ "tDiffuse" ].value = m.parameters.map;
  5862. uniforms[ "enableDiffuse" ].value = true;
  5863. }
  5864. if ( m.parameters.envMap ) {
  5865. uniforms[ "tCube" ].value = m.parameters.envMap;
  5866. uniforms[ "enableReflection" ].value = true;
  5867. uniforms[ "uReflectivity" ].value = m.parameters.reflectivity;
  5868. }
  5869. if ( m.parameters.lightMap ) {
  5870. uniforms[ "tAO" ].value = m.parameters.lightMap;
  5871. uniforms[ "enableAO" ].value = true;
  5872. }
  5873. if ( m.parameters.specularMap ) {
  5874. uniforms[ "tSpecular" ].value = result.textures[ m.parameters.specularMap ];
  5875. uniforms[ "enableSpecular" ].value = true;
  5876. }
  5877. if ( m.parameters.displacementMap ) {
  5878. uniforms[ "tDisplacement" ].value = result.textures[ m.parameters.displacementMap ];
  5879. uniforms[ "enableDisplacement" ].value = true;
  5880. uniforms[ "uDisplacementBias" ].value = m.parameters.displacementBias;
  5881. uniforms[ "uDisplacementScale" ].value = m.parameters.displacementScale;
  5882. }
  5883. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  5884. uniforms[ "uSpecularColor" ].value.setHex( specular );
  5885. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  5886. uniforms[ "uShininess" ].value = shininess;
  5887. if ( m.parameters.opacity ) {
  5888. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  5889. }
  5890. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5891. material = new THREE.ShaderMaterial( parameters );
  5892. } else {
  5893. material = new THREE[ m.type ]( m.parameters );
  5894. }
  5895. result.materials[ dm ] = material;
  5896. }
  5897. // objects ( synchronous init of procedural primitives )
  5898. handle_objects();
  5899. // synchronous callback
  5900. scope.callbackSync( result );
  5901. // just in case there are no async elements
  5902. async_callback_gate();
  5903. };
  5904. /**
  5905. * @author mrdoob / http://mrdoob.com/
  5906. */
  5907. THREE.TextureLoader = function () {
  5908. THREE.EventTarget.call( this );
  5909. this.crossOrigin = null;
  5910. };
  5911. THREE.TextureLoader.prototype = {
  5912. constructor: THREE.TextureLoader,
  5913. load: function ( url ) {
  5914. var scope = this;
  5915. var image = new Image();
  5916. image.addEventListener( 'load', function () {
  5917. var texture = new THREE.Texture( image );
  5918. texture.needsUpdate = true;
  5919. scope.dispatchEvent( { type: 'load', content: texture } );
  5920. }, false );
  5921. image.addEventListener( 'error', function () {
  5922. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5923. }, false );
  5924. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5925. image.src = url;
  5926. }
  5927. }
  5928. /**
  5929. * @author mrdoob / http://mrdoob.com/
  5930. * @author alteredq / http://alteredqualia.com/
  5931. */
  5932. THREE.Material = function () {
  5933. THREE.MaterialLibrary.push( this );
  5934. this.id = THREE.MaterialIdCount ++;
  5935. this.name = '';
  5936. this.side = THREE.FrontSide;
  5937. this.opacity = 1;
  5938. this.transparent = false;
  5939. this.blending = THREE.NormalBlending;
  5940. this.blendSrc = THREE.SrcAlphaFactor;
  5941. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  5942. this.blendEquation = THREE.AddEquation;
  5943. this.depthTest = true;
  5944. this.depthWrite = true;
  5945. this.polygonOffset = false;
  5946. this.polygonOffsetFactor = 0;
  5947. this.polygonOffsetUnits = 0;
  5948. this.alphaTest = 0;
  5949. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  5950. this.visible = true;
  5951. this.needsUpdate = true;
  5952. };
  5953. THREE.Material.prototype.setValues = function ( values ) {
  5954. if ( values === undefined ) return;
  5955. for ( var key in values ) {
  5956. var newValue = values[ key ];
  5957. if ( newValue === undefined ) {
  5958. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  5959. continue;
  5960. }
  5961. if ( key in this ) {
  5962. var currentValue = this[ key ];
  5963. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  5964. currentValue.copy( newValue );
  5965. } else if ( currentValue instanceof THREE.Color && typeof( newValue ) === "number" ) {
  5966. currentValue.setHex( newValue );
  5967. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  5968. currentValue.copy( newValue );
  5969. } else {
  5970. this[ key ] = newValue;
  5971. }
  5972. }
  5973. }
  5974. };
  5975. THREE.Material.prototype.clone = function ( material ) {
  5976. if ( material === undefined ) material = new THREE.Material();
  5977. material.name = this.name;
  5978. material.side = this.side;
  5979. material.opacity = this.opacity;
  5980. material.transparent = this.transparent;
  5981. material.blending = this.blending;
  5982. material.blendSrc = this.blendSrc;
  5983. material.blendDst = this.blendDst;
  5984. material.blendEquation = this.blendEquation;
  5985. material.depthTest = this.depthTest;
  5986. material.depthWrite = this.depthWrite;
  5987. material.polygonOffset = this.polygonOffset;
  5988. material.polygonOffsetFactor = this.polygonOffsetFactor;
  5989. material.polygonOffsetUnits = this.polygonOffsetUnits;
  5990. material.alphaTest = this.alphaTest;
  5991. material.overdraw = this.overdraw;
  5992. material.visible = this.visible;
  5993. return material;
  5994. };
  5995. THREE.Material.prototype.deallocate = function () {
  5996. var index = THREE.MaterialLibrary.indexOf( this );
  5997. if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
  5998. };
  5999. THREE.MaterialIdCount = 0;
  6000. THREE.MaterialLibrary = [];
  6001. /**
  6002. * @author mrdoob / http://mrdoob.com/
  6003. * @author alteredq / http://alteredqualia.com/
  6004. *
  6005. * parameters = {
  6006. * color: <hex>,
  6007. * opacity: <float>,
  6008. *
  6009. * blending: THREE.NormalBlending,
  6010. * depthTest: <bool>,
  6011. *
  6012. * linewidth: <float>,
  6013. * linecap: "round",
  6014. * linejoin: "round",
  6015. *
  6016. * vertexColors: <bool>
  6017. *
  6018. * fog: <bool>
  6019. * }
  6020. */
  6021. THREE.LineBasicMaterial = function ( parameters ) {
  6022. THREE.Material.call( this );
  6023. this.color = new THREE.Color( 0xffffff );
  6024. this.linewidth = 1;
  6025. this.linecap = 'round';
  6026. this.linejoin = 'round';
  6027. this.vertexColors = false;
  6028. this.fog = true;
  6029. this.setValues( parameters );
  6030. };
  6031. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6032. THREE.LineBasicMaterial.prototype.clone = function () {
  6033. var material = new THREE.LineBasicMaterial();
  6034. THREE.Material.prototype.clone.call( this, material );
  6035. material.color.copy( this.color );
  6036. material.linewidth = this.linewidth;
  6037. material.linecap = this.linecap;
  6038. material.linejoin = this.linejoin;
  6039. material.vertexColors = this.vertexColors;
  6040. material.fog = this.fog;
  6041. return material;
  6042. };
  6043. /**
  6044. * @author mrdoob / http://mrdoob.com/
  6045. * @author alteredq / http://alteredqualia.com/
  6046. *
  6047. * parameters = {
  6048. * color: <hex>,
  6049. * opacity: <float>,
  6050. * map: new THREE.Texture( <Image> ),
  6051. *
  6052. * lightMap: new THREE.Texture( <Image> ),
  6053. *
  6054. * specularMap: new THREE.Texture( <Image> ),
  6055. *
  6056. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6057. * combine: THREE.Multiply,
  6058. * reflectivity: <float>,
  6059. * refractionRatio: <float>,
  6060. *
  6061. * shading: THREE.SmoothShading,
  6062. * blending: THREE.NormalBlending,
  6063. * depthTest: <bool>,
  6064. *
  6065. * wireframe: <boolean>,
  6066. * wireframeLinewidth: <float>,
  6067. *
  6068. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6069. *
  6070. * skinning: <bool>,
  6071. * morphTargets: <bool>,
  6072. *
  6073. * fog: <bool>
  6074. * }
  6075. */
  6076. THREE.MeshBasicMaterial = function ( parameters ) {
  6077. THREE.Material.call( this );
  6078. this.color = new THREE.Color( 0xffffff ); // emissive
  6079. this.map = null;
  6080. this.lightMap = null;
  6081. this.specularMap = null;
  6082. this.envMap = null;
  6083. this.combine = THREE.MultiplyOperation;
  6084. this.reflectivity = 1;
  6085. this.refractionRatio = 0.98;
  6086. this.fog = true;
  6087. this.shading = THREE.SmoothShading;
  6088. this.wireframe = false;
  6089. this.wireframeLinewidth = 1;
  6090. this.wireframeLinecap = 'round';
  6091. this.wireframeLinejoin = 'round';
  6092. this.vertexColors = THREE.NoColors;
  6093. this.skinning = false;
  6094. this.morphTargets = false;
  6095. this.setValues( parameters );
  6096. };
  6097. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6098. THREE.MeshBasicMaterial.prototype.clone = function () {
  6099. var material = new THREE.MeshBasicMaterial();
  6100. THREE.Material.prototype.clone.call( this, material );
  6101. material.color.copy( this.color );
  6102. material.map = this.map;
  6103. material.lightMap = this.lightMap;
  6104. material.specularMap = this.specularMap;
  6105. material.envMap = this.envMap;
  6106. material.combine = this.combine;
  6107. material.reflectivity = this.reflectivity;
  6108. material.refractionRatio = this.refractionRatio;
  6109. material.fog = this.fog;
  6110. material.shading = this.shading;
  6111. material.wireframe = this.wireframe;
  6112. material.wireframeLinewidth = this.wireframeLinewidth;
  6113. material.wireframeLinecap = this.wireframeLinecap;
  6114. material.wireframeLinejoin = this.wireframeLinejoin;
  6115. material.vertexColors = this.vertexColors;
  6116. material.skinning = this.skinning;
  6117. material.morphTargets = this.morphTargets;
  6118. return material;
  6119. };
  6120. /**
  6121. * @author mrdoob / http://mrdoob.com/
  6122. * @author alteredq / http://alteredqualia.com/
  6123. *
  6124. * parameters = {
  6125. * color: <hex>,
  6126. * ambient: <hex>,
  6127. * emissive: <hex>,
  6128. * opacity: <float>,
  6129. *
  6130. * map: new THREE.Texture( <Image> ),
  6131. *
  6132. * lightMap: new THREE.Texture( <Image> ),
  6133. *
  6134. * specularMap: new THREE.Texture( <Image> ),
  6135. *
  6136. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6137. * combine: THREE.Multiply,
  6138. * reflectivity: <float>,
  6139. * refractionRatio: <float>,
  6140. *
  6141. * shading: THREE.SmoothShading,
  6142. * blending: THREE.NormalBlending,
  6143. * depthTest: <bool>,
  6144. *
  6145. * wireframe: <boolean>,
  6146. * wireframeLinewidth: <float>,
  6147. *
  6148. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6149. *
  6150. * skinning: <bool>,
  6151. * morphTargets: <bool>,
  6152. * morphNormals: <bool>,
  6153. *
  6154. * fog: <bool>
  6155. * }
  6156. */
  6157. THREE.MeshLambertMaterial = function ( parameters ) {
  6158. THREE.Material.call( this );
  6159. this.color = new THREE.Color( 0xffffff ); // diffuse
  6160. this.ambient = new THREE.Color( 0xffffff );
  6161. this.emissive = new THREE.Color( 0x000000 );
  6162. this.wrapAround = false;
  6163. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6164. this.map = null;
  6165. this.lightMap = null;
  6166. this.specularMap = null;
  6167. this.envMap = null;
  6168. this.combine = THREE.MultiplyOperation;
  6169. this.reflectivity = 1;
  6170. this.refractionRatio = 0.98;
  6171. this.fog = true;
  6172. this.shading = THREE.SmoothShading;
  6173. this.wireframe = false;
  6174. this.wireframeLinewidth = 1;
  6175. this.wireframeLinecap = 'round';
  6176. this.wireframeLinejoin = 'round';
  6177. this.vertexColors = THREE.NoColors;
  6178. this.skinning = false;
  6179. this.morphTargets = false;
  6180. this.morphNormals = false;
  6181. this.setValues( parameters );
  6182. };
  6183. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6184. THREE.MeshLambertMaterial.prototype.clone = function () {
  6185. var material = new THREE.MeshLambertMaterial();
  6186. THREE.Material.prototype.clone.call( this, material );
  6187. material.color.copy( this.color );
  6188. material.ambient.copy( this.ambient );
  6189. material.emissive.copy( this.emissive );
  6190. material.wrapAround = this.wrapAround;
  6191. material.wrapRGB.copy( this.wrapRGB );
  6192. material.map = this.map;
  6193. material.lightMap = this.lightMap;
  6194. material.specularMap = this.specularMap;
  6195. material.envMap = this.envMap;
  6196. material.combine = this.combine;
  6197. material.reflectivity = this.reflectivity;
  6198. material.refractionRatio = this.refractionRatio;
  6199. material.fog = this.fog;
  6200. material.shading = this.shading;
  6201. material.wireframe = this.wireframe;
  6202. material.wireframeLinewidth = this.wireframeLinewidth;
  6203. material.wireframeLinecap = this.wireframeLinecap;
  6204. material.wireframeLinejoin = this.wireframeLinejoin;
  6205. material.vertexColors = this.vertexColors;
  6206. material.skinning = this.skinning;
  6207. material.morphTargets = this.morphTargets;
  6208. material.morphNormals = this.morphNormals;
  6209. return material;
  6210. };
  6211. /**
  6212. * @author mrdoob / http://mrdoob.com/
  6213. * @author alteredq / http://alteredqualia.com/
  6214. *
  6215. * parameters = {
  6216. * color: <hex>,
  6217. * ambient: <hex>,
  6218. * emissive: <hex>,
  6219. * specular: <hex>,
  6220. * shininess: <float>,
  6221. * opacity: <float>,
  6222. *
  6223. * map: new THREE.Texture( <Image> ),
  6224. *
  6225. * lightMap: new THREE.Texture( <Image> ),
  6226. *
  6227. * bumpMap: new THREE.Texture( <Image> ),
  6228. * bumpScale: <float>,
  6229. *
  6230. * normalMap: new THREE.Texture( <Image> ),
  6231. * normalScale: <Vector2>,
  6232. *
  6233. * specularMap: new THREE.Texture( <Image> ),
  6234. *
  6235. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6236. * combine: THREE.Multiply,
  6237. * reflectivity: <float>,
  6238. * refractionRatio: <float>,
  6239. *
  6240. * shading: THREE.SmoothShading,
  6241. * blending: THREE.NormalBlending,
  6242. * depthTest: <bool>,
  6243. *
  6244. * wireframe: <boolean>,
  6245. * wireframeLinewidth: <float>,
  6246. *
  6247. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6248. *
  6249. * skinning: <bool>,
  6250. * morphTargets: <bool>,
  6251. * morphNormals: <bool>,
  6252. *
  6253. * fog: <bool>
  6254. * }
  6255. */
  6256. THREE.MeshPhongMaterial = function ( parameters ) {
  6257. THREE.Material.call( this );
  6258. this.color = new THREE.Color( 0xffffff ); // diffuse
  6259. this.ambient = new THREE.Color( 0xffffff );
  6260. this.emissive = new THREE.Color( 0x000000 );
  6261. this.specular = new THREE.Color( 0x111111 );
  6262. this.shininess = 30;
  6263. this.metal = false;
  6264. this.perPixel = false;
  6265. this.wrapAround = false;
  6266. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6267. this.map = null;
  6268. this.lightMap = null;
  6269. this.bumpMap = null;
  6270. this.bumpScale = 1;
  6271. this.normalMap = null;
  6272. this.normalScale = new THREE.Vector2( 1, 1 );
  6273. this.specularMap = null;
  6274. this.envMap = null;
  6275. this.combine = THREE.MultiplyOperation;
  6276. this.reflectivity = 1;
  6277. this.refractionRatio = 0.98;
  6278. this.fog = true;
  6279. this.shading = THREE.SmoothShading;
  6280. this.wireframe = false;
  6281. this.wireframeLinewidth = 1;
  6282. this.wireframeLinecap = 'round';
  6283. this.wireframeLinejoin = 'round';
  6284. this.vertexColors = THREE.NoColors;
  6285. this.skinning = false;
  6286. this.morphTargets = false;
  6287. this.morphNormals = false;
  6288. this.setValues( parameters );
  6289. };
  6290. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6291. THREE.MeshPhongMaterial.prototype.clone = function () {
  6292. var material = new THREE.MeshPhongMaterial();
  6293. THREE.Material.prototype.clone.call( this, material );
  6294. material.color.copy( this.color );
  6295. material.ambient.copy( this.ambient );
  6296. material.emissive.copy( this.emissive );
  6297. material.specular.copy( this.specular );
  6298. material.shininess = this.shininess;
  6299. material.metal = this.metal;
  6300. material.perPixel = this.perPixel;
  6301. material.wrapAround = this.wrapAround;
  6302. material.wrapRGB.copy( this.wrapRGB );
  6303. material.map = this.map;
  6304. material.lightMap = this.lightMap;
  6305. material.bumpMap = this.bumpMap;
  6306. material.bumpScale = this.bumpScale;
  6307. material.normalMap = this.normalMap;
  6308. material.normalScale.copy( this.normalScale );
  6309. material.specularMap = this.specularMap;
  6310. material.envMap = this.envMap;
  6311. material.combine = this.combine;
  6312. material.reflectivity = this.reflectivity;
  6313. material.refractionRatio = this.refractionRatio;
  6314. material.fog = this.fog;
  6315. material.shading = this.shading;
  6316. material.wireframe = this.wireframe;
  6317. material.wireframeLinewidth = this.wireframeLinewidth;
  6318. material.wireframeLinecap = this.wireframeLinecap;
  6319. material.wireframeLinejoin = this.wireframeLinejoin;
  6320. material.vertexColors = this.vertexColors;
  6321. material.skinning = this.skinning;
  6322. material.morphTargets = this.morphTargets;
  6323. material.morphNormals = this.morphNormals;
  6324. return material;
  6325. };
  6326. /**
  6327. * @author mrdoob / http://mrdoob.com/
  6328. * @author alteredq / http://alteredqualia.com/
  6329. *
  6330. * parameters = {
  6331. * opacity: <float>,
  6332. * blending: THREE.NormalBlending,
  6333. * depthTest: <bool>,
  6334. * wireframe: <boolean>,
  6335. * wireframeLinewidth: <float>
  6336. * }
  6337. */
  6338. THREE.MeshDepthMaterial = function ( parameters ) {
  6339. THREE.Material.call( this );
  6340. this.wireframe = false;
  6341. this.wireframeLinewidth = 1;
  6342. this.setValues( parameters );
  6343. };
  6344. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6345. THREE.MeshDepthMaterial.prototype.clone = function () {
  6346. var material = new THREE.LineBasicMaterial();
  6347. THREE.Material.prototype.clone.call( this, material );
  6348. material.wireframe = this.wireframe;
  6349. material.wireframeLinewidth = this.wireframeLinewidth;
  6350. return material;
  6351. };
  6352. /**
  6353. * @author mrdoob / http://mrdoob.com/
  6354. *
  6355. * parameters = {
  6356. * opacity: <float>,
  6357. * shading: THREE.FlatShading,
  6358. * blending: THREE.NormalBlending,
  6359. * depthTest: <bool>,
  6360. * wireframe: <boolean>,
  6361. * wireframeLinewidth: <float>
  6362. * }
  6363. */
  6364. THREE.MeshNormalMaterial = function ( parameters ) {
  6365. THREE.Material.call( this, parameters );
  6366. this.shading = THREE.FlatShading;
  6367. this.wireframe = false;
  6368. this.wireframeLinewidth = 1;
  6369. this.setValues( parameters );
  6370. };
  6371. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  6372. THREE.MeshNormalMaterial.prototype.clone = function () {
  6373. var material = new THREE.MeshNormalMaterial();
  6374. THREE.Material.prototype.clone.call( this, material );
  6375. material.shading = this.shading;
  6376. material.wireframe = this.wireframe;
  6377. material.wireframeLinewidth = this.wireframeLinewidth;
  6378. return material;
  6379. };
  6380. /**
  6381. * @author mrdoob / http://mrdoob.com/
  6382. */
  6383. THREE.MeshFaceMaterial = function () {};
  6384. THREE.MeshFaceMaterial.prototype.clone = function () {
  6385. return new THREE.MeshFaceMaterial();
  6386. };
  6387. /**
  6388. * @author mrdoob / http://mrdoob.com/
  6389. * @author alteredq / http://alteredqualia.com/
  6390. *
  6391. * parameters = {
  6392. * color: <hex>,
  6393. * opacity: <float>,
  6394. * map: new THREE.Texture( <Image> ),
  6395. *
  6396. * size: <float>,
  6397. *
  6398. * blending: THREE.NormalBlending,
  6399. * depthTest: <bool>,
  6400. *
  6401. * vertexColors: <bool>,
  6402. *
  6403. * fog: <bool>
  6404. * }
  6405. */
  6406. THREE.ParticleBasicMaterial = function ( parameters ) {
  6407. THREE.Material.call( this );
  6408. this.color = new THREE.Color( 0xffffff );
  6409. this.map = null;
  6410. this.size = 1;
  6411. this.sizeAttenuation = true;
  6412. this.vertexColors = false;
  6413. this.fog = true;
  6414. this.setValues( parameters );
  6415. };
  6416. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6417. THREE.ParticleBasicMaterial.prototype.clone = function () {
  6418. var material = new THREE.ParticleBasicMaterial();
  6419. THREE.Material.prototype.clone.call( this, material );
  6420. material.color.copy( this.color );
  6421. material.map = this.map;
  6422. material.size = this.size;
  6423. material.sizeAttenuation = this.sizeAttenuation;
  6424. material.vertexColors = this.vertexColors;
  6425. material.fog = this.fog;
  6426. return material;
  6427. };
  6428. /**
  6429. * @author mrdoob / http://mrdoob.com/
  6430. *
  6431. * parameters = {
  6432. * color: <hex>,
  6433. * program: <function>,
  6434. * opacity: <float>,
  6435. * blending: THREE.NormalBlending
  6436. * }
  6437. */
  6438. THREE.ParticleCanvasMaterial = function ( parameters ) {
  6439. THREE.Material.call( this );
  6440. this.color = new THREE.Color( 0xffffff );
  6441. this.program = function ( context, color ) {};
  6442. this.setValues( parameters );
  6443. };
  6444. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  6445. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  6446. var material = new THREE.ParticleCanvasMaterial();
  6447. THREE.Material.prototype.clone.call( this, material );
  6448. material.color.copy( this.color );
  6449. material.program = this.program;
  6450. return material;
  6451. };
  6452. /**
  6453. * @author mrdoob / http://mrdoob.com/
  6454. */
  6455. THREE.ParticleDOMMaterial = function ( element ) {
  6456. this.element = element;
  6457. };
  6458. THREE.ParticleDOMMaterial.prototype.clone = function(){
  6459. return new THREE.ParticleDOMMaterial( this.element );
  6460. };
  6461. /**
  6462. * @author alteredq / http://alteredqualia.com/
  6463. *
  6464. * parameters = {
  6465. * fragmentShader: <string>,
  6466. * vertexShader: <string>,
  6467. *
  6468. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  6469. *
  6470. * defines: { "label" : "value" },
  6471. *
  6472. * shading: THREE.SmoothShading,
  6473. * blending: THREE.NormalBlending,
  6474. * depthTest: <bool>,
  6475. *
  6476. * wireframe: <boolean>,
  6477. * wireframeLinewidth: <float>,
  6478. *
  6479. * lights: <bool>,
  6480. *
  6481. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6482. *
  6483. * skinning: <bool>,
  6484. * morphTargets: <bool>,
  6485. * morphNormals: <bool>,
  6486. *
  6487. * fog: <bool>
  6488. * }
  6489. */
  6490. THREE.ShaderMaterial = function ( parameters ) {
  6491. THREE.Material.call( this );
  6492. this.fragmentShader = "void main() {}";
  6493. this.vertexShader = "void main() {}";
  6494. this.uniforms = {};
  6495. this.defines = {};
  6496. this.attributes = null;
  6497. this.shading = THREE.SmoothShading;
  6498. this.wireframe = false;
  6499. this.wireframeLinewidth = 1;
  6500. this.fog = false; // set to use scene fog
  6501. this.lights = false; // set to use scene lights
  6502. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  6503. this.skinning = false; // set to use skinning attribute streams
  6504. this.morphTargets = false; // set to use morph targets
  6505. this.morphNormals = false; // set to use morph normals
  6506. this.setValues( parameters );
  6507. };
  6508. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  6509. THREE.ShaderMaterial.prototype.clone = function () {
  6510. var material = new THREE.ShaderMaterial();
  6511. THREE.Material.prototype.clone.call( this, material );
  6512. material.fragmentShader = this.fragmentShader;
  6513. material.vertexShader = this.vertexShader;
  6514. material.uniforms = this.uniforms;
  6515. material.attributes = this.attributes;
  6516. material.defines = this.defines;
  6517. material.shading = this.shading;
  6518. material.wireframe = this.wireframe;
  6519. material.wireframeLinewidth = this.wireframeLinewidth;
  6520. material.fog = this.fog;
  6521. material.lights = this.lights;
  6522. material.vertexColors = this.vertexColors;
  6523. material.skinning = this.skinning;
  6524. material.morphTargets = this.morphTargets;
  6525. material.morphNormals = this.morphNormals;
  6526. return material;
  6527. };
  6528. /**
  6529. * @author mrdoob / http://mrdoob.com/
  6530. * @author alteredq / http://alteredqualia.com/
  6531. * @author szimek / https://github.com/szimek/
  6532. */
  6533. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  6534. THREE.TextureLibrary.push( this );
  6535. this.id = THREE.TextureIdCount ++;
  6536. this.image = image;
  6537. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  6538. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  6539. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  6540. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  6541. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  6542. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  6543. this.format = format !== undefined ? format : THREE.RGBAFormat;
  6544. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  6545. this.offset = new THREE.Vector2( 0, 0 );
  6546. this.repeat = new THREE.Vector2( 1, 1 );
  6547. this.generateMipmaps = true;
  6548. this.premultiplyAlpha = false;
  6549. this.flipY = true;
  6550. this.needsUpdate = false;
  6551. this.onUpdate = null;
  6552. };
  6553. THREE.Texture.prototype = {
  6554. constructor: THREE.Texture,
  6555. clone: function () {
  6556. var texture = new THREE.Texture();
  6557. texture.image = this.image;
  6558. texture.mapping = this.mapping;
  6559. texture.wrapS = this.wrapS;
  6560. texture.wrapT = this.wrapT;
  6561. texture.magFilter = this.magFilter;
  6562. texture.minFilter = this.minFilter;
  6563. texture.anisotropy = this.anisotropy;
  6564. texture.format = this.format;
  6565. texture.type = this.type;
  6566. texture.offset.copy( this.offset );
  6567. texture.repeat.copy( this.repeat );
  6568. texture.generateMipmaps = this.generateMipmaps;
  6569. texture.premultiplyAlpha = this.premultiplyAlpha;
  6570. texture.flipY = this.flipY;
  6571. return texture;
  6572. },
  6573. deallocate: function () {
  6574. var index = THREE.TextureLibrary.indexOf( this );
  6575. if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
  6576. }
  6577. };
  6578. THREE.TextureIdCount = 0;
  6579. THREE.TextureLibrary = [];
  6580. /**
  6581. * @author alteredq / http://alteredqualia.com/
  6582. */
  6583. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6584. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6585. this.image = { width: width, height: height };
  6586. this.mipmaps = mipmaps;
  6587. };
  6588. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  6589. THREE.CompressedTexture.prototype.clone = function () {
  6590. var texture = new THREE.CompressedTexture();
  6591. texture.image = this.image;
  6592. texture.mipmaps = this.mipmaps;
  6593. texture.format = this.format;
  6594. texture.type = this.type;
  6595. texture.mapping = this.mapping;
  6596. texture.wrapS = this.wrapS;
  6597. texture.wrapT = this.wrapT;
  6598. texture.magFilter = this.magFilter;
  6599. texture.minFilter = this.minFilter;
  6600. texture.anisotropy = this.anisotropy;
  6601. texture.offset.copy( this.offset );
  6602. texture.repeat.copy( this.repeat );
  6603. return texture;
  6604. };
  6605. /**
  6606. * @author alteredq / http://alteredqualia.com/
  6607. */
  6608. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  6609. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  6610. this.image = { data: data, width: width, height: height };
  6611. };
  6612. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  6613. THREE.DataTexture.prototype.clone = function () {
  6614. 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 );
  6615. clonedTexture.offset.copy( this.offset );
  6616. clonedTexture.repeat.copy( this.repeat );
  6617. return clonedTexture;
  6618. };
  6619. /**
  6620. * @author mrdoob / http://mrdoob.com/
  6621. */
  6622. THREE.Particle = function ( material ) {
  6623. THREE.Object3D.call( this );
  6624. this.material = material;
  6625. };
  6626. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  6627. THREE.Particle.prototype.clone = function ( object ) {
  6628. if ( object === undefined ) object = new THREE.Particle( this.material );
  6629. THREE.Object3D.prototype.clone.call( this, object );
  6630. return object;
  6631. };
  6632. /**
  6633. * @author alteredq / http://alteredqualia.com/
  6634. */
  6635. THREE.ParticleSystem = function ( geometry, material ) {
  6636. THREE.Object3D.call( this );
  6637. this.geometry = geometry;
  6638. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  6639. this.sortParticles = false;
  6640. if ( this.geometry ) {
  6641. // calc bound radius
  6642. if( this.geometry.boundingSphere === null ) {
  6643. this.geometry.computeBoundingSphere();
  6644. }
  6645. this.boundRadius = geometry.boundingSphere.radius;
  6646. }
  6647. this.frustumCulled = false;
  6648. };
  6649. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  6650. THREE.ParticleSystem.prototype.clone = function ( object ) {
  6651. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  6652. object.sortParticles = this.sortParticles;
  6653. THREE.Object3D.prototype.clone.call( this, object );
  6654. return object;
  6655. };
  6656. /**
  6657. * @author mrdoob / http://mrdoob.com/
  6658. */
  6659. THREE.Line = function ( geometry, material, type ) {
  6660. THREE.Object3D.call( this );
  6661. this.geometry = geometry;
  6662. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  6663. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  6664. if ( this.geometry ) {
  6665. if ( ! this.geometry.boundingSphere ) {
  6666. this.geometry.computeBoundingSphere();
  6667. }
  6668. }
  6669. };
  6670. THREE.LineStrip = 0;
  6671. THREE.LinePieces = 1;
  6672. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  6673. THREE.Line.prototype.clone = function ( object ) {
  6674. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  6675. THREE.Object3D.prototype.clone.call( this, object );
  6676. return object;
  6677. };
  6678. /**
  6679. * @author mrdoob / http://mrdoob.com/
  6680. * @author alteredq / http://alteredqualia.com/
  6681. * @author mikael emtinger / http://gomo.se/
  6682. */
  6683. THREE.Mesh = function ( geometry, material ) {
  6684. THREE.Object3D.call( this );
  6685. this.geometry = geometry;
  6686. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  6687. if ( this.geometry ) {
  6688. // calc bound radius
  6689. if ( this.geometry.boundingSphere === null ) {
  6690. this.geometry.computeBoundingSphere();
  6691. }
  6692. this.boundRadius = geometry.boundingSphere.radius;
  6693. // setup morph targets
  6694. if ( this.geometry.morphTargets.length ) {
  6695. this.morphTargetBase = -1;
  6696. this.morphTargetForcedOrder = [];
  6697. this.morphTargetInfluences = [];
  6698. this.morphTargetDictionary = {};
  6699. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  6700. this.morphTargetInfluences.push( 0 );
  6701. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  6702. }
  6703. }
  6704. }
  6705. }
  6706. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  6707. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  6708. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  6709. return this.morphTargetDictionary[ name ];
  6710. }
  6711. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  6712. return 0;
  6713. };
  6714. THREE.Mesh.prototype.clone = function ( object ) {
  6715. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  6716. THREE.Object3D.prototype.clone.call( this, object );
  6717. return object;
  6718. };
  6719. /**
  6720. * @author mikael emtinger / http://gomo.se/
  6721. * @author alteredq / http://alteredqualia.com/
  6722. */
  6723. THREE.Bone = function( belongsToSkin ) {
  6724. THREE.Object3D.call( this );
  6725. this.skin = belongsToSkin;
  6726. this.skinMatrix = new THREE.Matrix4();
  6727. };
  6728. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  6729. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  6730. // update local
  6731. if ( this.matrixAutoUpdate ) {
  6732. forceUpdate |= this.updateMatrix();
  6733. }
  6734. // update skin matrix
  6735. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  6736. if( parentSkinMatrix ) {
  6737. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  6738. } else {
  6739. this.skinMatrix.copy( this.matrix );
  6740. }
  6741. this.matrixWorldNeedsUpdate = false;
  6742. forceUpdate = true;
  6743. }
  6744. // update children
  6745. var child, i, l = this.children.length;
  6746. for ( i = 0; i < l; i ++ ) {
  6747. this.children[ i ].update( this.skinMatrix, forceUpdate );
  6748. }
  6749. };
  6750. /**
  6751. * @author mikael emtinger / http://gomo.se/
  6752. * @author alteredq / http://alteredqualia.com/
  6753. */
  6754. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  6755. THREE.Mesh.call( this, geometry, material );
  6756. //
  6757. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  6758. // init bones
  6759. this.identityMatrix = new THREE.Matrix4();
  6760. this.bones = [];
  6761. this.boneMatrices = [];
  6762. var b, bone, gbone, p, q, s;
  6763. if ( this.geometry.bones !== undefined ) {
  6764. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  6765. gbone = this.geometry.bones[ b ];
  6766. p = gbone.pos;
  6767. q = gbone.rotq;
  6768. s = gbone.scl;
  6769. bone = this.addBone();
  6770. bone.name = gbone.name;
  6771. bone.position.set( p[0], p[1], p[2] );
  6772. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  6773. bone.useQuaternion = true;
  6774. if ( s !== undefined ) {
  6775. bone.scale.set( s[0], s[1], s[2] );
  6776. } else {
  6777. bone.scale.set( 1, 1, 1 );
  6778. }
  6779. }
  6780. for ( b = 0; b < this.bones.length; b ++ ) {
  6781. gbone = this.geometry.bones[ b ];
  6782. bone = this.bones[ b ];
  6783. if ( gbone.parent === -1 ) {
  6784. this.add( bone );
  6785. } else {
  6786. this.bones[ gbone.parent ].add( bone );
  6787. }
  6788. }
  6789. //
  6790. var nBones = this.bones.length;
  6791. if ( this.useVertexTexture ) {
  6792. // layout (1 matrix = 4 pixels)
  6793. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  6794. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  6795. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  6796. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  6797. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  6798. var size;
  6799. if ( nBones > 256 )
  6800. size = 64;
  6801. else if ( nBones > 64 )
  6802. size = 32;
  6803. else if ( nBones > 16 )
  6804. size = 16;
  6805. else
  6806. size = 8;
  6807. this.boneTextureWidth = size;
  6808. this.boneTextureHeight = size;
  6809. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  6810. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  6811. this.boneTexture.minFilter = THREE.NearestFilter;
  6812. this.boneTexture.magFilter = THREE.NearestFilter;
  6813. this.boneTexture.generateMipmaps = false;
  6814. this.boneTexture.flipY = false;
  6815. } else {
  6816. this.boneMatrices = new Float32Array( 16 * nBones );
  6817. }
  6818. this.pose();
  6819. }
  6820. };
  6821. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  6822. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  6823. if ( bone === undefined ) {
  6824. bone = new THREE.Bone( this );
  6825. }
  6826. this.bones.push( bone );
  6827. return bone;
  6828. };
  6829. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  6830. this.matrixAutoUpdate && this.updateMatrix();
  6831. // update matrixWorld
  6832. if ( this.matrixWorldNeedsUpdate || force ) {
  6833. if ( this.parent ) {
  6834. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  6835. } else {
  6836. this.matrixWorld.copy( this.matrix );
  6837. }
  6838. this.matrixWorldNeedsUpdate = false;
  6839. force = true;
  6840. }
  6841. // update children
  6842. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  6843. var child = this.children[ i ];
  6844. if ( child instanceof THREE.Bone ) {
  6845. child.update( this.identityMatrix, false );
  6846. } else {
  6847. child.updateMatrixWorld( true );
  6848. }
  6849. }
  6850. // make a snapshot of the bones' rest position
  6851. if ( this.boneInverses == undefined ) {
  6852. this.boneInverses = [];
  6853. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6854. var inverse = new THREE.Matrix4();
  6855. inverse.getInverse( this.bones[ b ].skinMatrix );
  6856. this.boneInverses.push( inverse );
  6857. }
  6858. }
  6859. // flatten bone matrices to array
  6860. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  6861. // compute the offset between the current and the original transform;
  6862. //TODO: we could get rid of this multiplication step if the skinMatrix
  6863. // was already representing the offset; however, this requires some
  6864. // major changes to the animation system
  6865. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  6866. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  6867. }
  6868. if ( this.useVertexTexture ) {
  6869. this.boneTexture.needsUpdate = true;
  6870. }
  6871. };
  6872. THREE.SkinnedMesh.prototype.pose = function() {
  6873. this.updateMatrixWorld( true );
  6874. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  6875. // normalize weights
  6876. var sw = this.geometry.skinWeights[ i ];
  6877. var scale = 1.0 / sw.lengthManhattan();
  6878. if ( scale !== Infinity ) {
  6879. sw.multiplyScalar( scale );
  6880. } else {
  6881. sw.set( 1 ); // this will be normalized by the shader anyway
  6882. }
  6883. }
  6884. };
  6885. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  6886. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  6887. THREE.Mesh.prototype.clone.call( this, object );
  6888. return object;
  6889. };
  6890. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  6891. /**
  6892. * @author alteredq / http://alteredqualia.com/
  6893. */
  6894. THREE.MorphAnimMesh = function ( geometry, material ) {
  6895. THREE.Mesh.call( this, geometry, material );
  6896. // API
  6897. this.duration = 1000; // milliseconds
  6898. this.mirroredLoop = false;
  6899. this.time = 0;
  6900. // internals
  6901. this.lastKeyframe = 0;
  6902. this.currentKeyframe = 0;
  6903. this.direction = 1;
  6904. this.directionBackwards = false;
  6905. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  6906. };
  6907. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  6908. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  6909. this.startKeyframe = start;
  6910. this.endKeyframe = end;
  6911. this.length = this.endKeyframe - this.startKeyframe + 1;
  6912. };
  6913. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  6914. this.direction = 1;
  6915. this.directionBackwards = false;
  6916. };
  6917. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  6918. this.direction = -1;
  6919. this.directionBackwards = true;
  6920. };
  6921. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  6922. var geometry = this.geometry;
  6923. if ( ! geometry.animations ) geometry.animations = {};
  6924. var firstAnimation, animations = geometry.animations;
  6925. var pattern = /([a-z]+)(\d+)/;
  6926. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  6927. var morph = geometry.morphTargets[ i ];
  6928. var parts = morph.name.match( pattern );
  6929. if ( parts && parts.length > 1 ) {
  6930. var label = parts[ 1 ];
  6931. var num = parts[ 2 ];
  6932. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  6933. var animation = animations[ label ];
  6934. if ( i < animation.start ) animation.start = i;
  6935. if ( i > animation.end ) animation.end = i;
  6936. if ( ! firstAnimation ) firstAnimation = label;
  6937. }
  6938. }
  6939. geometry.firstAnimation = firstAnimation;
  6940. };
  6941. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  6942. if ( ! this.geometry.animations ) this.geometry.animations = {};
  6943. this.geometry.animations[ label ] = { start: start, end: end };
  6944. };
  6945. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  6946. var animation = this.geometry.animations[ label ];
  6947. if ( animation ) {
  6948. this.setFrameRange( animation.start, animation.end );
  6949. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  6950. this.time = 0;
  6951. } else {
  6952. console.warn( "animation[" + label + "] undefined" );
  6953. }
  6954. };
  6955. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  6956. var frameTime = this.duration / this.length;
  6957. this.time += this.direction * delta;
  6958. if ( this.mirroredLoop ) {
  6959. if ( this.time > this.duration || this.time < 0 ) {
  6960. this.direction *= -1;
  6961. if ( this.time > this.duration ) {
  6962. this.time = this.duration;
  6963. this.directionBackwards = true;
  6964. }
  6965. if ( this.time < 0 ) {
  6966. this.time = 0;
  6967. this.directionBackwards = false;
  6968. }
  6969. }
  6970. } else {
  6971. this.time = this.time % this.duration;
  6972. if ( this.time < 0 ) this.time += this.duration;
  6973. }
  6974. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  6975. if ( keyframe !== this.currentKeyframe ) {
  6976. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  6977. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  6978. this.morphTargetInfluences[ keyframe ] = 0;
  6979. this.lastKeyframe = this.currentKeyframe;
  6980. this.currentKeyframe = keyframe;
  6981. }
  6982. var mix = ( this.time % frameTime ) / frameTime;
  6983. if ( this.directionBackwards ) {
  6984. mix = 1 - mix;
  6985. }
  6986. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  6987. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  6988. };
  6989. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  6990. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  6991. object.duration = this.duration;
  6992. object.mirroredLoop = this.mirroredLoop;
  6993. object.time = this.time;
  6994. object.lastKeyframe = this.lastKeyframe;
  6995. object.currentKeyframe = this.currentKeyframe;
  6996. object.direction = this.direction;
  6997. object.directionBackwards = this.directionBackwards;
  6998. THREE.Mesh.prototype.clone.call( this, object );
  6999. return object;
  7000. };
  7001. /**
  7002. * @author alteredq / http://alteredqualia.com/
  7003. */
  7004. THREE.Ribbon = function ( geometry, material ) {
  7005. THREE.Object3D.call( this );
  7006. this.geometry = geometry;
  7007. this.material = material;
  7008. };
  7009. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7010. THREE.Ribbon.prototype.clone = function ( object ) {
  7011. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7012. THREE.Object3D.prototype.clone.call( this, object );
  7013. return object;
  7014. };
  7015. /**
  7016. * @author mikael emtinger / http://gomo.se/
  7017. * @author alteredq / http://alteredqualia.com/
  7018. * @author mrdoob / http://mrdoob.com/
  7019. */
  7020. THREE.LOD = function () {
  7021. THREE.Object3D.call( this );
  7022. this.LODs = [];
  7023. };
  7024. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7025. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7026. if ( visibleAtDistance === undefined ) {
  7027. visibleAtDistance = 0;
  7028. }
  7029. visibleAtDistance = Math.abs( visibleAtDistance );
  7030. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7031. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7032. break;
  7033. }
  7034. }
  7035. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7036. this.add( object3D );
  7037. };
  7038. THREE.LOD.prototype.update = function ( camera ) {
  7039. if ( this.LODs.length > 1 ) {
  7040. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7041. var inverse = camera.matrixWorldInverse;
  7042. 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] );
  7043. this.LODs[ 0 ].object3D.visible = true;
  7044. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7045. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7046. this.LODs[ l - 1 ].object3D.visible = false;
  7047. this.LODs[ l ].object3D.visible = true;
  7048. } else {
  7049. break;
  7050. }
  7051. }
  7052. for( ; l < this.LODs.length; l ++ ) {
  7053. this.LODs[ l ].object3D.visible = false;
  7054. }
  7055. }
  7056. };
  7057. THREE.LOD.prototype.clone = function () {
  7058. // TODO
  7059. };
  7060. /**
  7061. * @author mikael emtinger / http://gomo.se/
  7062. */
  7063. THREE.Sprite = function ( parameters ) {
  7064. THREE.Object3D.call( this );
  7065. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  7066. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  7067. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  7068. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  7069. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  7070. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  7071. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  7072. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  7073. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  7074. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  7075. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  7076. this.rotation3d = this.rotation;
  7077. this.rotation = 0;
  7078. this.opacity = 1;
  7079. this.uvOffset = new THREE.Vector2( 0, 0 );
  7080. this.uvScale = new THREE.Vector2( 1, 1 );
  7081. };
  7082. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7083. /*
  7084. * Custom update matrix
  7085. */
  7086. THREE.Sprite.prototype.updateMatrix = function () {
  7087. this.matrix.setPosition( this.position );
  7088. this.rotation3d.set( 0, 0, this.rotation );
  7089. this.matrix.setRotationFromEuler( this.rotation3d );
  7090. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7091. this.matrix.scale( this.scale );
  7092. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7093. }
  7094. this.matrixWorldNeedsUpdate = true;
  7095. };
  7096. THREE.Sprite.prototype.clone = function ( object ) {
  7097. if ( object === undefined ) object = new THREE.Sprite( {} );
  7098. object.color.copy( this.color );
  7099. object.map = this.map;
  7100. object.blending = this.blending;
  7101. object.useScreenCoordinates = this.useScreenCoordinates;
  7102. object.mergeWith3D = this.mergeWith3D;
  7103. object.affectedByDistance = this.affectedByDistance;
  7104. object.scaleByViewport = this.scaleByViewport;
  7105. object.alignment = this.alignment;
  7106. object.rotation3d.copy( this.rotation3d );
  7107. object.rotation = this.rotation;
  7108. object.opacity = this.opacity;
  7109. object.uvOffset.copy( this.uvOffset );
  7110. object.uvScale.copy( this.uvScale);
  7111. THREE.Object3D.prototype.clone.call( this, object );
  7112. return object;
  7113. };
  7114. /*
  7115. * Alignment
  7116. */
  7117. THREE.SpriteAlignment = {};
  7118. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7119. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7120. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7121. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7122. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7123. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7124. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7125. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7126. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7127. /**
  7128. * @author mrdoob / http://mrdoob.com/
  7129. */
  7130. THREE.Scene = function () {
  7131. THREE.Object3D.call( this );
  7132. this.fog = null;
  7133. this.overrideMaterial = null;
  7134. this.matrixAutoUpdate = false;
  7135. this.__objects = [];
  7136. this.__lights = [];
  7137. this.__objectsAdded = [];
  7138. this.__objectsRemoved = [];
  7139. };
  7140. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7141. THREE.Scene.prototype.__addObject = function ( object ) {
  7142. if ( object instanceof THREE.Light ) {
  7143. if ( this.__lights.indexOf( object ) === - 1 ) {
  7144. this.__lights.push( object );
  7145. }
  7146. if ( object.target && object.target.parent === undefined ) {
  7147. this.add( object.target );
  7148. }
  7149. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7150. if ( this.__objects.indexOf( object ) === - 1 ) {
  7151. this.__objects.push( object );
  7152. this.__objectsAdded.push( object );
  7153. // check if previously removed
  7154. var i = this.__objectsRemoved.indexOf( object );
  7155. if ( i !== -1 ) {
  7156. this.__objectsRemoved.splice( i, 1 );
  7157. }
  7158. }
  7159. }
  7160. for ( var c = 0; c < object.children.length; c ++ ) {
  7161. this.__addObject( object.children[ c ] );
  7162. }
  7163. };
  7164. THREE.Scene.prototype.__removeObject = function ( object ) {
  7165. if ( object instanceof THREE.Light ) {
  7166. var i = this.__lights.indexOf( object );
  7167. if ( i !== -1 ) {
  7168. this.__lights.splice( i, 1 );
  7169. }
  7170. } else if ( !( object instanceof THREE.Camera ) ) {
  7171. var i = this.__objects.indexOf( object );
  7172. if( i !== -1 ) {
  7173. this.__objects.splice( i, 1 );
  7174. this.__objectsRemoved.push( object );
  7175. // check if previously added
  7176. var ai = this.__objectsAdded.indexOf( object );
  7177. if ( ai !== -1 ) {
  7178. this.__objectsAdded.splice( ai, 1 );
  7179. }
  7180. }
  7181. }
  7182. for ( var c = 0; c < object.children.length; c ++ ) {
  7183. this.__removeObject( object.children[ c ] );
  7184. }
  7185. };
  7186. /**
  7187. * @author mrdoob / http://mrdoob.com/
  7188. * @author alteredq / http://alteredqualia.com/
  7189. */
  7190. THREE.Fog = function ( hex, near, far ) {
  7191. this.color = new THREE.Color( hex );
  7192. this.near = ( near !== undefined ) ? near : 1;
  7193. this.far = ( far !== undefined ) ? far : 1000;
  7194. };
  7195. /**
  7196. * @author mrdoob / http://mrdoob.com/
  7197. * @author alteredq / http://alteredqualia.com/
  7198. */
  7199. THREE.FogExp2 = function ( hex, density ) {
  7200. this.color = new THREE.Color( hex );
  7201. this.density = ( density !== undefined ) ? density : 0.00025;
  7202. };
  7203. /**
  7204. * @author mrdoob / http://mrdoob.com/
  7205. */
  7206. THREE.CanvasRenderer = function ( parameters ) {
  7207. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7208. parameters = parameters || {};
  7209. var _this = this,
  7210. _renderData, _elements, _lights,
  7211. _projector = new THREE.Projector(),
  7212. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7213. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7214. _context = _canvas.getContext( '2d' ),
  7215. _clearColor = new THREE.Color( 0x000000 ),
  7216. _clearOpacity = 0,
  7217. _contextGlobalAlpha = 1,
  7218. _contextGlobalCompositeOperation = 0,
  7219. _contextStrokeStyle = null,
  7220. _contextFillStyle = null,
  7221. _contextLineWidth = null,
  7222. _contextLineCap = null,
  7223. _contextLineJoin = null,
  7224. _v1, _v2, _v3, _v4,
  7225. _v5 = new THREE.RenderableVertex(),
  7226. _v6 = new THREE.RenderableVertex(),
  7227. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7228. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7229. _color = new THREE.Color(),
  7230. _color1 = new THREE.Color(),
  7231. _color2 = new THREE.Color(),
  7232. _color3 = new THREE.Color(),
  7233. _color4 = new THREE.Color(),
  7234. _diffuseColor = new THREE.Color(),
  7235. _emissiveColor = new THREE.Color(),
  7236. _patterns = {}, _imagedatas = {},
  7237. _near, _far,
  7238. _image, _uvs,
  7239. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7240. _clipRect = new THREE.Rectangle(),
  7241. _clearRect = new THREE.Rectangle(),
  7242. _bboxRect = new THREE.Rectangle(),
  7243. _enableLighting = false,
  7244. _ambientLight = new THREE.Color(),
  7245. _directionalLights = new THREE.Color(),
  7246. _pointLights = new THREE.Color(),
  7247. _pi2 = Math.PI * 2,
  7248. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7249. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7250. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7251. _pixelMap = document.createElement( 'canvas' );
  7252. _pixelMap.width = _pixelMap.height = 2;
  7253. _pixelMapContext = _pixelMap.getContext( '2d' );
  7254. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7255. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7256. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7257. _pixelMapData = _pixelMapImage.data;
  7258. _gradientMap = document.createElement( 'canvas' );
  7259. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7260. _gradientMapContext = _gradientMap.getContext( '2d' );
  7261. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7262. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7263. _gradientMapQuality --; // Fix UVs
  7264. this.domElement = _canvas;
  7265. this.autoClear = true;
  7266. this.sortObjects = true;
  7267. this.sortElements = true;
  7268. this.info = {
  7269. render: {
  7270. vertices: 0,
  7271. faces: 0
  7272. }
  7273. }
  7274. this.setSize = function ( width, height ) {
  7275. _canvasWidth = width;
  7276. _canvasHeight = height;
  7277. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7278. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7279. _canvas.width = _canvasWidth;
  7280. _canvas.height = _canvasHeight;
  7281. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7282. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7283. _contextGlobalAlpha = 1;
  7284. _contextGlobalCompositeOperation = 0;
  7285. _contextStrokeStyle = null;
  7286. _contextFillStyle = null;
  7287. _contextLineWidth = null;
  7288. _contextLineCap = null;
  7289. _contextLineJoin = null;
  7290. };
  7291. this.setClearColor = function ( color, opacity ) {
  7292. _clearColor.copy( color );
  7293. _clearOpacity = opacity !== undefined ? opacity : 1;
  7294. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7295. };
  7296. this.setClearColorHex = function ( hex, opacity ) {
  7297. _clearColor.setHex( hex );
  7298. _clearOpacity = opacity !== undefined ? opacity : 1;
  7299. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7300. };
  7301. this.getMaxAnisotropy = function () {
  7302. return 0;
  7303. };
  7304. this.clear = function () {
  7305. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7306. if ( _clearRect.isEmpty() === false ) {
  7307. _clearRect.minSelf( _clipRect );
  7308. _clearRect.inflate( 2 );
  7309. if ( _clearOpacity < 1 ) {
  7310. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7311. }
  7312. if ( _clearOpacity > 0 ) {
  7313. setBlending( THREE.NormalBlending );
  7314. setOpacity( 1 );
  7315. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7316. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7317. }
  7318. _clearRect.empty();
  7319. }
  7320. };
  7321. this.render = function ( scene, camera ) {
  7322. if ( camera instanceof THREE.Camera === false ) {
  7323. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  7324. return;
  7325. }
  7326. var e, el, element, material;
  7327. this.autoClear === true
  7328. ? this.clear()
  7329. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7330. _this.info.render.vertices = 0;
  7331. _this.info.render.faces = 0;
  7332. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  7333. _elements = _renderData.elements;
  7334. _lights = _renderData.lights;
  7335. /* DEBUG
  7336. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  7337. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  7338. */
  7339. _enableLighting = _lights.length > 0;
  7340. if ( _enableLighting === true ) {
  7341. calculateLights();
  7342. }
  7343. for ( e = 0, el = _elements.length; e < el; e++ ) {
  7344. element = _elements[ e ];
  7345. material = element.material;
  7346. if ( material === undefined || material.visible === false ) continue;
  7347. _bboxRect.empty();
  7348. if ( element instanceof THREE.RenderableParticle ) {
  7349. _v1 = element;
  7350. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  7351. renderParticle( _v1, element, material, scene );
  7352. } else if ( element instanceof THREE.RenderableLine ) {
  7353. _v1 = element.v1; _v2 = element.v2;
  7354. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7355. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7356. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7357. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7358. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7359. renderLine( _v1, _v2, element, material, scene );
  7360. }
  7361. } else if ( element instanceof THREE.RenderableFace3 ) {
  7362. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  7363. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7364. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7365. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7366. if ( material.overdraw === true ) {
  7367. expand( _v1.positionScreen, _v2.positionScreen );
  7368. expand( _v2.positionScreen, _v3.positionScreen );
  7369. expand( _v3.positionScreen, _v1.positionScreen );
  7370. }
  7371. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  7372. _v2.positionScreen.x, _v2.positionScreen.y,
  7373. _v3.positionScreen.x, _v3.positionScreen.y );
  7374. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7375. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  7376. }
  7377. } else if ( element instanceof THREE.RenderableFace4 ) {
  7378. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  7379. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  7380. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  7381. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  7382. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  7383. _v5.positionScreen.copy( _v2.positionScreen );
  7384. _v6.positionScreen.copy( _v4.positionScreen );
  7385. if ( material.overdraw === true ) {
  7386. expand( _v1.positionScreen, _v2.positionScreen );
  7387. expand( _v2.positionScreen, _v4.positionScreen );
  7388. expand( _v4.positionScreen, _v1.positionScreen );
  7389. expand( _v3.positionScreen, _v5.positionScreen );
  7390. expand( _v3.positionScreen, _v6.positionScreen );
  7391. }
  7392. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  7393. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  7394. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  7395. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  7396. if ( _clipRect.intersects( _bboxRect ) === true ) {
  7397. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  7398. }
  7399. }
  7400. /* DEBUG
  7401. _context.lineWidth = 1;
  7402. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  7403. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  7404. */
  7405. _clearRect.addRectangle( _bboxRect );
  7406. }
  7407. /* DEBUG
  7408. _context.lineWidth = 1;
  7409. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  7410. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  7411. */
  7412. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  7413. //
  7414. function calculateLights() {
  7415. _ambientLight.setRGB( 0, 0, 0 );
  7416. _directionalLights.setRGB( 0, 0, 0 );
  7417. _pointLights.setRGB( 0, 0, 0 );
  7418. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7419. var light = _lights[ l ];
  7420. var lightColor = light.color;
  7421. if ( light instanceof THREE.AmbientLight ) {
  7422. _ambientLight.r += lightColor.r;
  7423. _ambientLight.g += lightColor.g;
  7424. _ambientLight.b += lightColor.b;
  7425. } else if ( light instanceof THREE.DirectionalLight ) {
  7426. // for particles
  7427. _directionalLights.r += lightColor.r;
  7428. _directionalLights.g += lightColor.g;
  7429. _directionalLights.b += lightColor.b;
  7430. } else if ( light instanceof THREE.PointLight ) {
  7431. // for particles
  7432. _pointLights.r += lightColor.r;
  7433. _pointLights.g += lightColor.g;
  7434. _pointLights.b += lightColor.b;
  7435. }
  7436. }
  7437. }
  7438. function calculateLight( position, normal, color ) {
  7439. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  7440. var light = _lights[ l ];
  7441. var lightColor = light.color;
  7442. if ( light instanceof THREE.DirectionalLight ) {
  7443. var lightPosition = light.matrixWorld.getPosition().normalize();
  7444. var amount = normal.dot( lightPosition );
  7445. if ( amount <= 0 ) continue;
  7446. amount *= light.intensity;
  7447. color.r += lightColor.r * amount;
  7448. color.g += lightColor.g * amount;
  7449. color.b += lightColor.b * amount;
  7450. } else if ( light instanceof THREE.PointLight ) {
  7451. var lightPosition = light.matrixWorld.getPosition();
  7452. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  7453. if ( amount <= 0 ) continue;
  7454. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  7455. if ( amount == 0 ) continue;
  7456. amount *= light.intensity;
  7457. color.r += lightColor.r * amount;
  7458. color.g += lightColor.g * amount;
  7459. color.b += lightColor.b * amount;
  7460. }
  7461. }
  7462. }
  7463. function renderParticle( v1, element, material, scene ) {
  7464. setOpacity( material.opacity );
  7465. setBlending( material.blending );
  7466. var width, height, scaleX, scaleY,
  7467. bitmap, bitmapWidth, bitmapHeight;
  7468. if ( material instanceof THREE.ParticleBasicMaterial ) {
  7469. if ( material.map === null ) {
  7470. scaleX = element.object.scale.x;
  7471. scaleY = element.object.scale.y;
  7472. // TODO: Be able to disable this
  7473. scaleX *= element.scale.x * _canvasWidthHalf;
  7474. scaleY *= element.scale.y * _canvasHeightHalf;
  7475. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  7476. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7477. return;
  7478. }
  7479. setFillStyle( material.color.getContextStyle() );
  7480. _context.save();
  7481. _context.translate( v1.x, v1.y );
  7482. _context.rotate( - element.rotation );
  7483. _context.scale( scaleX, scaleY );
  7484. _context.fillRect( -1, -1, 2, 2 );
  7485. _context.restore();
  7486. } else {
  7487. bitmap = material.map.image;
  7488. bitmapWidth = bitmap.width >> 1;
  7489. bitmapHeight = bitmap.height >> 1;
  7490. scaleX = element.scale.x * _canvasWidthHalf;
  7491. scaleY = element.scale.y * _canvasHeightHalf;
  7492. width = scaleX * bitmapWidth;
  7493. height = scaleY * bitmapHeight;
  7494. // TODO: Rotations break this...
  7495. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7496. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7497. return;
  7498. }
  7499. _context.save();
  7500. _context.translate( v1.x, v1.y );
  7501. _context.rotate( - element.rotation );
  7502. _context.scale( scaleX, - scaleY );
  7503. _context.translate( - bitmapWidth, - bitmapHeight );
  7504. _context.drawImage( bitmap, 0, 0 );
  7505. _context.restore();
  7506. }
  7507. /* DEBUG
  7508. setStrokeStyle( 'rgb(255,255,0)' );
  7509. _context.beginPath();
  7510. _context.moveTo( v1.x - 10, v1.y );
  7511. _context.lineTo( v1.x + 10, v1.y );
  7512. _context.moveTo( v1.x, v1.y - 10 );
  7513. _context.lineTo( v1.x, v1.y + 10 );
  7514. _context.stroke();
  7515. */
  7516. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  7517. width = element.scale.x * _canvasWidthHalf;
  7518. height = element.scale.y * _canvasHeightHalf;
  7519. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  7520. if ( _clipRect.intersects( _bboxRect ) === false ) {
  7521. return;
  7522. }
  7523. setStrokeStyle( material.color.getContextStyle() );
  7524. setFillStyle( material.color.getContextStyle() );
  7525. _context.save();
  7526. _context.translate( v1.x, v1.y );
  7527. _context.rotate( - element.rotation );
  7528. _context.scale( width, height );
  7529. material.program( _context );
  7530. _context.restore();
  7531. }
  7532. }
  7533. function renderLine( v1, v2, element, material, scene ) {
  7534. setOpacity( material.opacity );
  7535. setBlending( material.blending );
  7536. _context.beginPath();
  7537. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  7538. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  7539. if ( material instanceof THREE.LineBasicMaterial ) {
  7540. setLineWidth( material.linewidth );
  7541. setLineCap( material.linecap );
  7542. setLineJoin( material.linejoin );
  7543. setStrokeStyle( material.color.getContextStyle() );
  7544. _context.stroke();
  7545. _bboxRect.inflate( material.linewidth * 2 );
  7546. }
  7547. }
  7548. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  7549. _this.info.render.vertices += 3;
  7550. _this.info.render.faces ++;
  7551. setOpacity( material.opacity );
  7552. setBlending( material.blending );
  7553. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7554. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7555. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7556. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  7557. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  7558. _diffuseColor.copy( material.color );
  7559. _emissiveColor.copy( material.emissive );
  7560. if ( material.vertexColors === THREE.FaceColors ) {
  7561. _diffuseColor.r *= element.color.r;
  7562. _diffuseColor.g *= element.color.g;
  7563. _diffuseColor.b *= element.color.b;
  7564. }
  7565. if ( _enableLighting === true ) {
  7566. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  7567. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  7568. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  7569. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  7570. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7571. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7572. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  7573. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7574. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7575. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7576. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7577. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7578. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7579. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7580. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7581. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7582. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7583. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7584. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7585. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7586. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7587. } else {
  7588. _color.r = _ambientLight.r;
  7589. _color.g = _ambientLight.g;
  7590. _color.b = _ambientLight.b;
  7591. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7592. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7593. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7594. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7595. material.wireframe === true
  7596. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7597. : fillPath( _color );
  7598. }
  7599. } else {
  7600. material.wireframe === true
  7601. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7602. : fillPath( material.color );
  7603. }
  7604. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7605. if ( material.map !== null ) {
  7606. if ( material.map.mapping instanceof THREE.UVMapping ) {
  7607. _uvs = element.uvs[ 0 ];
  7608. 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 );
  7609. }
  7610. } else if ( material.envMap !== null ) {
  7611. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  7612. var cameraMatrix = camera.matrixWorldInverse;
  7613. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  7614. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7615. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7616. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  7617. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7618. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7619. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  7620. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  7621. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  7622. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  7623. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  7624. }*/
  7625. } else {
  7626. _color.copy( material.color );
  7627. if ( material.vertexColors === THREE.FaceColors ) {
  7628. _color.r *= element.color.r;
  7629. _color.g *= element.color.g;
  7630. _color.b *= element.color.b;
  7631. }
  7632. material.wireframe === true
  7633. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7634. : fillPath( _color );
  7635. }
  7636. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7637. _near = camera.near;
  7638. _far = camera.far;
  7639. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7640. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7641. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7642. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  7643. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  7644. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  7645. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7646. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  7647. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7648. _color.r = normalToComponent( element.normalWorld.x );
  7649. _color.g = normalToComponent( element.normalWorld.y );
  7650. _color.b = normalToComponent( element.normalWorld.z );
  7651. material.wireframe === true
  7652. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7653. : fillPath( _color );
  7654. }
  7655. }
  7656. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  7657. _this.info.render.vertices += 4;
  7658. _this.info.render.faces ++;
  7659. setOpacity( material.opacity );
  7660. setBlending( material.blending );
  7661. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  7662. // Let renderFace3() handle this
  7663. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  7664. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  7665. return;
  7666. }
  7667. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  7668. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  7669. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  7670. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  7671. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  7672. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  7673. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  7674. _diffuseColor.copy( material.color );
  7675. _emissiveColor.copy( material.emissive );
  7676. if ( material.vertexColors === THREE.FaceColors ) {
  7677. _diffuseColor.r *= element.color.r;
  7678. _diffuseColor.g *= element.color.g;
  7679. _diffuseColor.b *= element.color.b;
  7680. }
  7681. if ( _enableLighting === true ) {
  7682. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  7683. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  7684. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  7685. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  7686. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  7687. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  7688. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  7689. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  7690. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  7691. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  7692. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  7693. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  7694. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  7695. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  7696. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  7697. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  7698. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  7699. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  7700. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  7701. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  7702. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7703. // TODO: UVs are incorrect, v4->v3?
  7704. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7705. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7706. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7707. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7708. } else {
  7709. _color.r = _ambientLight.r;
  7710. _color.g = _ambientLight.g;
  7711. _color.b = _ambientLight.b;
  7712. calculateLight( element.centroidWorld, element.normalWorld, _color );
  7713. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  7714. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  7715. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  7716. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7717. material.wireframe === true
  7718. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7719. : fillPath( _color );
  7720. }
  7721. } else {
  7722. _color.r = _diffuseColor.r + _emissiveColor.r;
  7723. _color.g = _diffuseColor.g + _emissiveColor.g;
  7724. _color.b = _diffuseColor.b + _emissiveColor.b;
  7725. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7726. material.wireframe === true
  7727. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7728. : fillPath( _color );
  7729. }
  7730. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  7731. _color.copy( material.color );
  7732. if ( material.vertexColors === THREE.FaceColors ) {
  7733. _color.r *= element.color.r;
  7734. _color.g *= element.color.g;
  7735. _color.b *= element.color.b;
  7736. }
  7737. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7738. material.wireframe === true
  7739. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7740. : fillPath( _color );
  7741. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  7742. _color.r = normalToComponent( element.normalWorld.x );
  7743. _color.g = normalToComponent( element.normalWorld.y );
  7744. _color.b = normalToComponent( element.normalWorld.z );
  7745. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  7746. material.wireframe === true
  7747. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  7748. : fillPath( _color );
  7749. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  7750. _near = camera.near;
  7751. _far = camera.far;
  7752. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  7753. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  7754. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  7755. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  7756. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  7757. // TODO: UVs are incorrect, v4->v3?
  7758. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  7759. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  7760. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  7761. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  7762. }
  7763. }
  7764. //
  7765. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  7766. _context.beginPath();
  7767. _context.moveTo( x0, y0 );
  7768. _context.lineTo( x1, y1 );
  7769. _context.lineTo( x2, y2 );
  7770. _context.closePath();
  7771. }
  7772. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  7773. _context.beginPath();
  7774. _context.moveTo( x0, y0 );
  7775. _context.lineTo( x1, y1 );
  7776. _context.lineTo( x2, y2 );
  7777. _context.lineTo( x3, y3 );
  7778. _context.closePath();
  7779. }
  7780. function strokePath( color, linewidth, linecap, linejoin ) {
  7781. setLineWidth( linewidth );
  7782. setLineCap( linecap );
  7783. setLineJoin( linejoin );
  7784. setStrokeStyle( color.getContextStyle() );
  7785. _context.stroke();
  7786. _bboxRect.inflate( linewidth * 2 );
  7787. }
  7788. function fillPath( color ) {
  7789. setFillStyle( color.getContextStyle() );
  7790. _context.fill();
  7791. }
  7792. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  7793. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  7794. if ( texture.needsUpdate === true ) {
  7795. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  7796. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  7797. _patterns[ texture.id ] = _context.createPattern(
  7798. texture.image, repeatX === true && repeatY === true
  7799. ? 'repeat'
  7800. : repeatX === true && repeatY === false
  7801. ? 'repeat-x'
  7802. : repeatX === false && repeatY === true
  7803. ? 'repeat-y'
  7804. : 'no-repeat'
  7805. );
  7806. texture.needsUpdate = false;
  7807. }
  7808. _patterns[ texture.id ] === undefined
  7809. ? setFillStyle( 'rgba(0,0,0,1)' )
  7810. : setFillStyle( _patterns[ texture.id ] );
  7811. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7812. var a, b, c, d, e, f, det, idet,
  7813. offsetX = texture.offset.x / texture.repeat.x,
  7814. offsetY = texture.offset.y / texture.repeat.y,
  7815. width = texture.image.width * texture.repeat.x,
  7816. height = texture.image.height * texture.repeat.y;
  7817. u0 = ( u0 + offsetX ) * width;
  7818. v0 = ( 1.0 - v0 + offsetY ) * height;
  7819. u1 = ( u1 + offsetX ) * width;
  7820. v1 = ( 1.0 - v1 + offsetY ) * height;
  7821. u2 = ( u2 + offsetX ) * width;
  7822. v2 = ( 1.0 - v2 + offsetY ) * height;
  7823. x1 -= x0; y1 -= y0;
  7824. x2 -= x0; y2 -= y0;
  7825. u1 -= u0; v1 -= v0;
  7826. u2 -= u0; v2 -= v0;
  7827. det = u1 * v2 - u2 * v1;
  7828. if ( det === 0 ) {
  7829. if ( _imagedatas[ texture.id ] === undefined ) {
  7830. var canvas = document.createElement( 'canvas' )
  7831. canvas.width = texture.image.width;
  7832. canvas.height = texture.image.height;
  7833. var context = canvas.getContext( '2d' );
  7834. context.drawImage( texture.image, 0, 0 );
  7835. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  7836. }
  7837. var data = _imagedatas[ texture.id ];
  7838. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  7839. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  7840. fillPath( _color );
  7841. return;
  7842. }
  7843. idet = 1 / det;
  7844. a = ( v2 * x1 - v1 * x2 ) * idet;
  7845. b = ( v2 * y1 - v1 * y2 ) * idet;
  7846. c = ( u1 * x2 - u2 * x1 ) * idet;
  7847. d = ( u1 * y2 - u2 * y1 ) * idet;
  7848. e = x0 - a * u0 - c * v0;
  7849. f = y0 - b * u0 - d * v0;
  7850. _context.save();
  7851. _context.transform( a, b, c, d, e, f );
  7852. _context.fill();
  7853. _context.restore();
  7854. }
  7855. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  7856. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  7857. var a, b, c, d, e, f, det, idet,
  7858. width = image.width - 1,
  7859. height = image.height - 1;
  7860. u0 *= width; v0 *= height;
  7861. u1 *= width; v1 *= height;
  7862. u2 *= width; v2 *= height;
  7863. x1 -= x0; y1 -= y0;
  7864. x2 -= x0; y2 -= y0;
  7865. u1 -= u0; v1 -= v0;
  7866. u2 -= u0; v2 -= v0;
  7867. det = u1 * v2 - u2 * v1;
  7868. idet = 1 / det;
  7869. a = ( v2 * x1 - v1 * x2 ) * idet;
  7870. b = ( v2 * y1 - v1 * y2 ) * idet;
  7871. c = ( u1 * x2 - u2 * x1 ) * idet;
  7872. d = ( u1 * y2 - u2 * y1 ) * idet;
  7873. e = x0 - a * u0 - c * v0;
  7874. f = y0 - b * u0 - d * v0;
  7875. _context.save();
  7876. _context.transform( a, b, c, d, e, f );
  7877. _context.clip();
  7878. _context.drawImage( image, 0, 0 );
  7879. _context.restore();
  7880. }
  7881. function getGradientTexture( color1, color2, color3, color4 ) {
  7882. // http://mrdoob.com/blog/post/710
  7883. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  7884. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  7885. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  7886. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  7887. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  7888. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  7889. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  7890. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  7891. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  7892. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  7893. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  7894. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  7895. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  7896. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  7897. return _gradientMap;
  7898. }
  7899. function smoothstep( value, min, max ) {
  7900. var x = ( value - min ) / ( max - min );
  7901. return x * x * ( 3 - 2 * x );
  7902. }
  7903. function normalToComponent( normal ) {
  7904. var component = ( normal + 1 ) * 0.5;
  7905. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  7906. }
  7907. // Hide anti-alias gaps
  7908. function expand( v1, v2 ) {
  7909. var x = v2.x - v1.x, y = v2.y - v1.y,
  7910. det = x * x + y * y, idet;
  7911. if ( det === 0 ) return;
  7912. idet = 1 / Math.sqrt( det );
  7913. x *= idet; y *= idet;
  7914. v2.x += x; v2.y += y;
  7915. v1.x -= x; v1.y -= y;
  7916. }
  7917. };
  7918. // Context cached methods.
  7919. function setOpacity( value ) {
  7920. if ( _contextGlobalAlpha !== value ) {
  7921. _context.globalAlpha = value;
  7922. _contextGlobalAlpha = value;
  7923. }
  7924. }
  7925. function setBlending( value ) {
  7926. if ( _contextGlobalCompositeOperation !== value ) {
  7927. if ( value === THREE.NormalBlending ) {
  7928. _context.globalCompositeOperation = 'source-over';
  7929. } else if ( value === THREE.AdditiveBlending ) {
  7930. _context.globalCompositeOperation = 'lighter';
  7931. } else if ( value === THREE.SubtractiveBlending ) {
  7932. _context.globalCompositeOperation = 'darker';
  7933. }
  7934. _contextGlobalCompositeOperation = value;
  7935. }
  7936. }
  7937. function setLineWidth( value ) {
  7938. if ( _contextLineWidth !== value ) {
  7939. _context.lineWidth = value;
  7940. _contextLineWidth = value;
  7941. }
  7942. }
  7943. function setLineCap( value ) {
  7944. // "butt", "round", "square"
  7945. if ( _contextLineCap !== value ) {
  7946. _context.lineCap = value;
  7947. _contextLineCap = value;
  7948. }
  7949. }
  7950. function setLineJoin( value ) {
  7951. // "round", "bevel", "miter"
  7952. if ( _contextLineJoin !== value ) {
  7953. _context.lineJoin = value;
  7954. _contextLineJoin = value;
  7955. }
  7956. }
  7957. function setStrokeStyle( value ) {
  7958. if ( _contextStrokeStyle !== value ) {
  7959. _context.strokeStyle = value;
  7960. _contextStrokeStyle = value;
  7961. }
  7962. }
  7963. function setFillStyle( value ) {
  7964. if ( _contextFillStyle !== value ) {
  7965. _context.fillStyle = value;
  7966. _contextFillStyle = value;
  7967. }
  7968. }
  7969. };
  7970. /**
  7971. * @author alteredq / http://alteredqualia.com/
  7972. * @author mrdoob / http://mrdoob.com/
  7973. * @author mikael emtinger / http://gomo.se/
  7974. */
  7975. THREE.ShaderChunk = {
  7976. // FOG
  7977. fog_pars_fragment: [
  7978. "#ifdef USE_FOG",
  7979. "uniform vec3 fogColor;",
  7980. "#ifdef FOG_EXP2",
  7981. "uniform float fogDensity;",
  7982. "#else",
  7983. "uniform float fogNear;",
  7984. "uniform float fogFar;",
  7985. "#endif",
  7986. "#endif"
  7987. ].join("\n"),
  7988. fog_fragment: [
  7989. "#ifdef USE_FOG",
  7990. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  7991. "#ifdef FOG_EXP2",
  7992. "const float LOG2 = 1.442695;",
  7993. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  7994. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  7995. "#else",
  7996. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  7997. "#endif",
  7998. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  7999. "#endif"
  8000. ].join("\n"),
  8001. // ENVIRONMENT MAP
  8002. envmap_pars_fragment: [
  8003. "#ifdef USE_ENVMAP",
  8004. "uniform float reflectivity;",
  8005. "uniform samplerCube envMap;",
  8006. "uniform float flipEnvMap;",
  8007. "uniform int combine;",
  8008. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8009. "uniform bool useRefract;",
  8010. "uniform float refractionRatio;",
  8011. "#else",
  8012. "varying vec3 vReflect;",
  8013. "#endif",
  8014. "#endif"
  8015. ].join("\n"),
  8016. envmap_fragment: [
  8017. "#ifdef USE_ENVMAP",
  8018. "vec3 reflectVec;",
  8019. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8020. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8021. "if ( useRefract ) {",
  8022. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8023. "} else { ",
  8024. "reflectVec = reflect( cameraToVertex, normal );",
  8025. "}",
  8026. "#else",
  8027. "reflectVec = vReflect;",
  8028. "#endif",
  8029. "#ifdef DOUBLE_SIDED",
  8030. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8031. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8032. "#else",
  8033. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8034. "#endif",
  8035. "#ifdef GAMMA_INPUT",
  8036. "cubeColor.xyz *= cubeColor.xyz;",
  8037. "#endif",
  8038. "if ( combine == 1 ) {",
  8039. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8040. "} else {",
  8041. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8042. "}",
  8043. "#endif"
  8044. ].join("\n"),
  8045. envmap_pars_vertex: [
  8046. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8047. "varying vec3 vReflect;",
  8048. "uniform float refractionRatio;",
  8049. "uniform bool useRefract;",
  8050. "#endif"
  8051. ].join("\n"),
  8052. worldpos_vertex : [
  8053. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8054. "#ifdef USE_SKINNING",
  8055. "vec4 mPosition = modelMatrix * skinned;",
  8056. "#endif",
  8057. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8058. "vec4 mPosition = modelMatrix * vec4( morphed, 1.0 );",
  8059. "#endif",
  8060. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8061. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  8062. "#endif",
  8063. "#endif"
  8064. ].join("\n"),
  8065. envmap_vertex : [
  8066. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8067. "vec3 nWorld = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8068. "if ( useRefract ) {",
  8069. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  8070. "} else {",
  8071. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  8072. "}",
  8073. "#endif"
  8074. ].join("\n"),
  8075. // COLOR MAP (particles)
  8076. map_particle_pars_fragment: [
  8077. "#ifdef USE_MAP",
  8078. "uniform sampler2D map;",
  8079. "#endif"
  8080. ].join("\n"),
  8081. map_particle_fragment: [
  8082. "#ifdef USE_MAP",
  8083. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8084. "#endif"
  8085. ].join("\n"),
  8086. // COLOR MAP (triangles)
  8087. map_pars_vertex: [
  8088. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8089. "varying vec2 vUv;",
  8090. "uniform vec4 offsetRepeat;",
  8091. "#endif"
  8092. ].join("\n"),
  8093. map_pars_fragment: [
  8094. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8095. "varying vec2 vUv;",
  8096. "#endif",
  8097. "#ifdef USE_MAP",
  8098. "uniform sampler2D map;",
  8099. "#endif",
  8100. ].join("\n"),
  8101. map_vertex: [
  8102. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8103. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8104. "#endif"
  8105. ].join("\n"),
  8106. map_fragment: [
  8107. "#ifdef USE_MAP",
  8108. "#ifdef GAMMA_INPUT",
  8109. "vec4 texelColor = texture2D( map, vUv );",
  8110. "texelColor.xyz *= texelColor.xyz;",
  8111. "gl_FragColor = gl_FragColor * texelColor;",
  8112. "#else",
  8113. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  8114. "#endif",
  8115. "#endif"
  8116. ].join("\n"),
  8117. // LIGHT MAP
  8118. lightmap_pars_fragment: [
  8119. "#ifdef USE_LIGHTMAP",
  8120. "varying vec2 vUv2;",
  8121. "uniform sampler2D lightMap;",
  8122. "#endif"
  8123. ].join("\n"),
  8124. lightmap_pars_vertex: [
  8125. "#ifdef USE_LIGHTMAP",
  8126. "varying vec2 vUv2;",
  8127. "#endif"
  8128. ].join("\n"),
  8129. lightmap_fragment: [
  8130. "#ifdef USE_LIGHTMAP",
  8131. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8132. "#endif"
  8133. ].join("\n"),
  8134. lightmap_vertex: [
  8135. "#ifdef USE_LIGHTMAP",
  8136. "vUv2 = uv2;",
  8137. "#endif"
  8138. ].join("\n"),
  8139. // BUMP MAP
  8140. bumpmap_pars_fragment: [
  8141. "#ifdef USE_BUMPMAP",
  8142. "uniform sampler2D bumpMap;",
  8143. "uniform float bumpScale;",
  8144. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8145. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8146. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8147. "vec2 dHdxy_fwd() {",
  8148. "vec2 dSTdx = dFdx( vUv );",
  8149. "vec2 dSTdy = dFdy( vUv );",
  8150. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8151. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8152. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8153. "return vec2( dBx, dBy );",
  8154. "}",
  8155. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8156. "vec3 vSigmaX = dFdx( surf_pos );",
  8157. "vec3 vSigmaY = dFdy( surf_pos );",
  8158. "vec3 vN = surf_norm;", // normalized
  8159. "vec3 R1 = cross( vSigmaY, vN );",
  8160. "vec3 R2 = cross( vN, vSigmaX );",
  8161. "float fDet = dot( vSigmaX, R1 );",
  8162. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8163. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8164. "}",
  8165. "#endif"
  8166. ].join("\n"),
  8167. // NORMAL MAP
  8168. normalmap_pars_fragment: [
  8169. "#ifdef USE_NORMALMAP",
  8170. "uniform sampler2D normalMap;",
  8171. "uniform vec2 normalScale;",
  8172. // Per-Pixel Tangent Space Normal Mapping
  8173. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8174. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8175. "vec3 q0 = dFdx( eye_pos.xyz );",
  8176. "vec3 q1 = dFdy( eye_pos.xyz );",
  8177. "vec2 st0 = dFdx( vUv.st );",
  8178. "vec2 st1 = dFdy( vUv.st );",
  8179. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8180. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8181. "vec3 N = normalize( surf_norm );",
  8182. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8183. "mapN.xy = normalScale * mapN.xy;",
  8184. "mat3 tsn = mat3( S, T, N );",
  8185. "return normalize( tsn * mapN );",
  8186. "}",
  8187. "#endif"
  8188. ].join("\n"),
  8189. // SPECULAR MAP
  8190. specularmap_pars_fragment: [
  8191. "#ifdef USE_SPECULARMAP",
  8192. "uniform sampler2D specularMap;",
  8193. "#endif"
  8194. ].join("\n"),
  8195. specularmap_fragment: [
  8196. "float specularStrength;",
  8197. "#ifdef USE_SPECULARMAP",
  8198. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8199. "specularStrength = texelSpecular.r;",
  8200. "#else",
  8201. "specularStrength = 1.0;",
  8202. "#endif"
  8203. ].join("\n"),
  8204. // LIGHTS LAMBERT
  8205. lights_lambert_pars_vertex: [
  8206. "uniform vec3 ambient;",
  8207. "uniform vec3 diffuse;",
  8208. "uniform vec3 emissive;",
  8209. "uniform vec3 ambientLightColor;",
  8210. "#if MAX_DIR_LIGHTS > 0",
  8211. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8212. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8213. "#endif",
  8214. "#if MAX_HEMI_LIGHTS > 0",
  8215. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8216. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8217. "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
  8218. "#endif",
  8219. "#if MAX_POINT_LIGHTS > 0",
  8220. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8221. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8222. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8223. "#endif",
  8224. "#if MAX_SPOT_LIGHTS > 0",
  8225. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8226. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8227. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8228. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8229. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  8230. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8231. "#endif",
  8232. "#ifdef WRAP_AROUND",
  8233. "uniform vec3 wrapRGB;",
  8234. "#endif"
  8235. ].join("\n"),
  8236. lights_lambert_vertex: [
  8237. "vLightFront = vec3( 0.0 );",
  8238. "#ifdef DOUBLE_SIDED",
  8239. "vLightBack = vec3( 0.0 );",
  8240. "#endif",
  8241. "transformedNormal = normalize( transformedNormal );",
  8242. "#if MAX_DIR_LIGHTS > 0",
  8243. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8244. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8245. "vec3 dirVector = normalize( lDirection.xyz );",
  8246. "float dotProduct = dot( transformedNormal, dirVector );",
  8247. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8248. "#ifdef DOUBLE_SIDED",
  8249. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8250. "#ifdef WRAP_AROUND",
  8251. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8252. "#endif",
  8253. "#endif",
  8254. "#ifdef WRAP_AROUND",
  8255. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8256. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8257. "#ifdef DOUBLE_SIDED",
  8258. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8259. "#endif",
  8260. "#endif",
  8261. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8262. "#ifdef DOUBLE_SIDED",
  8263. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8264. "#endif",
  8265. "}",
  8266. "#endif",
  8267. "#if MAX_POINT_LIGHTS > 0",
  8268. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8269. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8270. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8271. "float lDistance = 1.0;",
  8272. "if ( pointLightDistance[ i ] > 0.0 )",
  8273. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8274. "lVector = normalize( lVector );",
  8275. "float dotProduct = dot( transformedNormal, lVector );",
  8276. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8277. "#ifdef DOUBLE_SIDED",
  8278. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8279. "#ifdef WRAP_AROUND",
  8280. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8281. "#endif",
  8282. "#endif",
  8283. "#ifdef WRAP_AROUND",
  8284. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8285. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8286. "#ifdef DOUBLE_SIDED",
  8287. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8288. "#endif",
  8289. "#endif",
  8290. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8291. "#ifdef DOUBLE_SIDED",
  8292. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8293. "#endif",
  8294. "}",
  8295. "#endif",
  8296. "#if MAX_SPOT_LIGHTS > 0",
  8297. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8298. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8299. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8300. "lVector = normalize( lVector );",
  8301. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - mPosition.xyz ) );",
  8302. "if ( spotEffect > spotLightAngle[ i ] ) {",
  8303. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  8304. "float lDistance = 1.0;",
  8305. "if ( spotLightDistance[ i ] > 0.0 )",
  8306. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8307. "float dotProduct = dot( transformedNormal, lVector );",
  8308. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8309. "#ifdef DOUBLE_SIDED",
  8310. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8311. "#ifdef WRAP_AROUND",
  8312. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8313. "#endif",
  8314. "#endif",
  8315. "#ifdef WRAP_AROUND",
  8316. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8317. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  8318. "#ifdef DOUBLE_SIDED",
  8319. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  8320. "#endif",
  8321. "#endif",
  8322. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  8323. "#ifdef DOUBLE_SIDED",
  8324. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  8325. "#endif",
  8326. "}",
  8327. "}",
  8328. "#endif",
  8329. "#if MAX_HEMI_LIGHTS > 0",
  8330. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8331. "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
  8332. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8333. "lVector = normalize( lVector );",
  8334. "float dotProduct = dot( transformedNormal, lVector );",
  8335. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8336. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  8337. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8338. "#ifdef DOUBLE_SIDED",
  8339. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  8340. "#endif",
  8341. "}",
  8342. "#endif",
  8343. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  8344. "#ifdef DOUBLE_SIDED",
  8345. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  8346. "#endif"
  8347. ].join("\n"),
  8348. // LIGHTS PHONG
  8349. lights_phong_pars_vertex: [
  8350. "#ifndef PHONG_PER_PIXEL",
  8351. "#if MAX_POINT_LIGHTS > 0",
  8352. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8353. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8354. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8355. "#endif",
  8356. "#if MAX_SPOT_LIGHTS > 0",
  8357. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8358. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8359. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8360. "#endif",
  8361. "#endif",
  8362. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8363. "varying vec3 vWorldPosition;",
  8364. "#endif"
  8365. ].join("\n"),
  8366. lights_phong_vertex: [
  8367. "#ifndef PHONG_PER_PIXEL",
  8368. "#if MAX_POINT_LIGHTS > 0",
  8369. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8370. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8371. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8372. "float lDistance = 1.0;",
  8373. "if ( pointLightDistance[ i ] > 0.0 )",
  8374. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8375. "vPointLight[ i ] = vec4( lVector, lDistance );",
  8376. "}",
  8377. "#endif",
  8378. "#if MAX_SPOT_LIGHTS > 0",
  8379. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8380. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8381. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8382. "float lDistance = 1.0;",
  8383. "if ( spotLightDistance[ i ] > 0.0 )",
  8384. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8385. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  8386. "}",
  8387. "#endif",
  8388. "#endif",
  8389. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8390. "vWorldPosition = mPosition.xyz;",
  8391. "#endif"
  8392. ].join("\n"),
  8393. lights_phong_pars_fragment: [
  8394. "uniform vec3 ambientLightColor;",
  8395. "#if MAX_DIR_LIGHTS > 0",
  8396. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8397. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8398. "#endif",
  8399. "#if MAX_HEMI_LIGHTS > 0",
  8400. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8401. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8402. "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
  8403. "#endif",
  8404. "#if MAX_POINT_LIGHTS > 0",
  8405. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8406. "#ifdef PHONG_PER_PIXEL",
  8407. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8408. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8409. "#else",
  8410. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  8411. "#endif",
  8412. "#endif",
  8413. "#if MAX_SPOT_LIGHTS > 0",
  8414. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8415. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8416. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8417. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  8418. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8419. "#ifdef PHONG_PER_PIXEL",
  8420. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8421. "#else",
  8422. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  8423. "#endif",
  8424. "#endif",
  8425. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  8426. "varying vec3 vWorldPosition;",
  8427. "#endif",
  8428. "#ifdef WRAP_AROUND",
  8429. "uniform vec3 wrapRGB;",
  8430. "#endif",
  8431. "varying vec3 vViewPosition;",
  8432. "varying vec3 vNormal;"
  8433. ].join("\n"),
  8434. lights_phong_fragment: [
  8435. "vec3 normal = normalize( vNormal );",
  8436. "vec3 viewPosition = normalize( vViewPosition );",
  8437. "#ifdef DOUBLE_SIDED",
  8438. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8439. "#endif",
  8440. "#ifdef USE_NORMALMAP",
  8441. "normal = perturbNormal2Arb( -viewPosition, normal );",
  8442. "#elif defined( USE_BUMPMAP )",
  8443. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  8444. "#endif",
  8445. "#if MAX_POINT_LIGHTS > 0",
  8446. "vec3 pointDiffuse = vec3( 0.0 );",
  8447. "vec3 pointSpecular = vec3( 0.0 );",
  8448. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8449. "#ifdef PHONG_PER_PIXEL",
  8450. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8451. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8452. "float lDistance = 1.0;",
  8453. "if ( pointLightDistance[ i ] > 0.0 )",
  8454. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8455. "lVector = normalize( lVector );",
  8456. "#else",
  8457. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  8458. "float lDistance = vPointLight[ i ].w;",
  8459. "#endif",
  8460. // diffuse
  8461. "float dotProduct = dot( normal, lVector );",
  8462. "#ifdef WRAP_AROUND",
  8463. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  8464. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8465. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  8466. "#else",
  8467. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  8468. "#endif",
  8469. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  8470. // specular
  8471. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  8472. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  8473. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  8474. "#ifdef PHYSICALLY_BASED_SHADING",
  8475. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8476. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8477. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  8478. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  8479. "#else",
  8480. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  8481. "#endif",
  8482. "}",
  8483. "#endif",
  8484. "#if MAX_SPOT_LIGHTS > 0",
  8485. "vec3 spotDiffuse = vec3( 0.0 );",
  8486. "vec3 spotSpecular = vec3( 0.0 );",
  8487. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8488. "#ifdef PHONG_PER_PIXEL",
  8489. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8490. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  8491. "float lDistance = 1.0;",
  8492. "if ( spotLightDistance[ i ] > 0.0 )",
  8493. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8494. "lVector = normalize( lVector );",
  8495. "#else",
  8496. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  8497. "float lDistance = vSpotLight[ i ].w;",
  8498. "#endif",
  8499. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  8500. "if ( spotEffect > spotLightAngle[ i ] ) {",
  8501. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  8502. // diffuse
  8503. "float dotProduct = dot( normal, lVector );",
  8504. "#ifdef WRAP_AROUND",
  8505. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  8506. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8507. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  8508. "#else",
  8509. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  8510. "#endif",
  8511. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  8512. // specular
  8513. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  8514. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  8515. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  8516. "#ifdef PHYSICALLY_BASED_SHADING",
  8517. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8518. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8519. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  8520. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  8521. "#else",
  8522. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  8523. "#endif",
  8524. "}",
  8525. "}",
  8526. "#endif",
  8527. "#if MAX_DIR_LIGHTS > 0",
  8528. "vec3 dirDiffuse = vec3( 0.0 );",
  8529. "vec3 dirSpecular = vec3( 0.0 );" ,
  8530. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8531. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8532. "vec3 dirVector = normalize( lDirection.xyz );",
  8533. // diffuse
  8534. "float dotProduct = dot( normal, dirVector );",
  8535. "#ifdef WRAP_AROUND",
  8536. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  8537. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  8538. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  8539. "#else",
  8540. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  8541. "#endif",
  8542. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  8543. // specular
  8544. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  8545. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  8546. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  8547. "#ifdef PHYSICALLY_BASED_SHADING",
  8548. /*
  8549. // fresnel term from skin shader
  8550. "const float F0 = 0.128;",
  8551. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  8552. "float exponential = pow( base, 5.0 );",
  8553. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  8554. */
  8555. /*
  8556. // fresnel term from fresnel shader
  8557. "const float mFresnelBias = 0.08;",
  8558. "const float mFresnelScale = 0.3;",
  8559. "const float mFresnelPower = 5.0;",
  8560. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  8561. */
  8562. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8563. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8564. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  8565. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  8566. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  8567. "#else",
  8568. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  8569. "#endif",
  8570. "}",
  8571. "#endif",
  8572. "#if MAX_HEMI_LIGHTS > 0",
  8573. "vec3 hemiDiffuse = vec3( 0.0 );",
  8574. "vec3 hemiSpecular = vec3( 0.0 );" ,
  8575. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  8576. "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
  8577. "vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",
  8578. // diffuse
  8579. "float dotProduct = dot( normal, lVector );",
  8580. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  8581. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  8582. "hemiDiffuse += diffuse * hemiColor;",
  8583. // specular (sky light)
  8584. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  8585. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  8586. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  8587. // specular (ground light)
  8588. "vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",
  8589. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  8590. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  8591. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  8592. "#ifdef PHYSICALLY_BASED_SHADING",
  8593. "float dotProductGround = dot( normal, lVectorGround );",
  8594. // 2.0 => 2.0001 is hack to work around ANGLE bug
  8595. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  8596. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  8597. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  8598. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  8599. "#else",
  8600. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  8601. "#endif",
  8602. "}",
  8603. "#endif",
  8604. "vec3 totalDiffuse = vec3( 0.0 );",
  8605. "vec3 totalSpecular = vec3( 0.0 );",
  8606. "#if MAX_DIR_LIGHTS > 0",
  8607. "totalDiffuse += dirDiffuse;",
  8608. "totalSpecular += dirSpecular;",
  8609. "#endif",
  8610. "#if MAX_HEMI_LIGHTS > 0",
  8611. "totalDiffuse += hemiDiffuse;",
  8612. "totalSpecular += hemiSpecular;",
  8613. "#endif",
  8614. "#if MAX_POINT_LIGHTS > 0",
  8615. "totalDiffuse += pointDiffuse;",
  8616. "totalSpecular += pointSpecular;",
  8617. "#endif",
  8618. "#if MAX_SPOT_LIGHTS > 0",
  8619. "totalDiffuse += spotDiffuse;",
  8620. "totalSpecular += spotSpecular;",
  8621. "#endif",
  8622. "#ifdef METAL",
  8623. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  8624. "#else",
  8625. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  8626. "#endif"
  8627. ].join("\n"),
  8628. // VERTEX COLORS
  8629. color_pars_fragment: [
  8630. "#ifdef USE_COLOR",
  8631. "varying vec3 vColor;",
  8632. "#endif"
  8633. ].join("\n"),
  8634. color_fragment: [
  8635. "#ifdef USE_COLOR",
  8636. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  8637. "#endif"
  8638. ].join("\n"),
  8639. color_pars_vertex: [
  8640. "#ifdef USE_COLOR",
  8641. "varying vec3 vColor;",
  8642. "#endif"
  8643. ].join("\n"),
  8644. color_vertex: [
  8645. "#ifdef USE_COLOR",
  8646. "#ifdef GAMMA_INPUT",
  8647. "vColor = color * color;",
  8648. "#else",
  8649. "vColor = color;",
  8650. "#endif",
  8651. "#endif"
  8652. ].join("\n"),
  8653. // SKINNING
  8654. skinning_pars_vertex: [
  8655. "#ifdef USE_SKINNING",
  8656. "#ifdef BONE_TEXTURE",
  8657. "uniform sampler2D boneTexture;",
  8658. "mat4 getBoneMatrix( const in float i ) {",
  8659. "float j = i * 4.0;",
  8660. "float x = mod( j, N_BONE_PIXEL_X );",
  8661. "float y = floor( j / N_BONE_PIXEL_X );",
  8662. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  8663. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  8664. "y = dy * ( y + 0.5 );",
  8665. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  8666. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  8667. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  8668. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  8669. "mat4 bone = mat4( v1, v2, v3, v4 );",
  8670. "return bone;",
  8671. "}",
  8672. "#else",
  8673. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  8674. "mat4 getBoneMatrix( const in float i ) {",
  8675. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  8676. "return bone;",
  8677. "}",
  8678. "#endif",
  8679. "#endif"
  8680. ].join("\n"),
  8681. skinbase_vertex: [
  8682. "#ifdef USE_SKINNING",
  8683. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  8684. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  8685. "#endif"
  8686. ].join("\n"),
  8687. skinning_vertex: [
  8688. "#ifdef USE_SKINNING",
  8689. "#ifdef USE_MORPHTARGETS",
  8690. "vec4 skinVertex = vec4( morphed, 1.0 );",
  8691. "#else",
  8692. "vec4 skinVertex = vec4( position, 1.0 );",
  8693. "#endif",
  8694. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  8695. "skinned += boneMatY * skinVertex * skinWeight.y;",
  8696. "#endif"
  8697. ].join("\n"),
  8698. // MORPHING
  8699. morphtarget_pars_vertex: [
  8700. "#ifdef USE_MORPHTARGETS",
  8701. "#ifndef USE_MORPHNORMALS",
  8702. "uniform float morphTargetInfluences[ 8 ];",
  8703. "#else",
  8704. "uniform float morphTargetInfluences[ 4 ];",
  8705. "#endif",
  8706. "#endif"
  8707. ].join("\n"),
  8708. morphtarget_vertex: [
  8709. "#ifdef USE_MORPHTARGETS",
  8710. "vec3 morphed = vec3( 0.0 );",
  8711. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  8712. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  8713. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  8714. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  8715. "#ifndef USE_MORPHNORMALS",
  8716. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  8717. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  8718. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  8719. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  8720. "#endif",
  8721. "morphed += position;",
  8722. "#endif"
  8723. ].join("\n"),
  8724. default_vertex : [
  8725. "vec4 mvPosition;",
  8726. "#ifdef USE_SKINNING",
  8727. "mvPosition = modelViewMatrix * skinned;",
  8728. "#endif",
  8729. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  8730. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  8731. "#endif",
  8732. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  8733. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  8734. "#endif",
  8735. "gl_Position = projectionMatrix * mvPosition;",
  8736. ].join("\n"),
  8737. morphnormal_vertex: [
  8738. "#ifdef USE_MORPHNORMALS",
  8739. "vec3 morphedNormal = vec3( 0.0 );",
  8740. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  8741. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  8742. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  8743. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  8744. "morphedNormal += normal;",
  8745. "#endif"
  8746. ].join("\n"),
  8747. skinnormal_vertex: [
  8748. "#ifdef USE_SKINNING",
  8749. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  8750. "skinMatrix += skinWeight.y * boneMatY;",
  8751. "#ifdef USE_MORPHNORMALS",
  8752. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  8753. "#else",
  8754. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  8755. "#endif",
  8756. "#endif"
  8757. ].join("\n"),
  8758. defaultnormal_vertex: [
  8759. "vec3 objectNormal;",
  8760. "#ifdef USE_SKINNING",
  8761. "objectNormal = skinnedNormal.xyz;",
  8762. "#endif",
  8763. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  8764. "objectNormal = morphedNormal;",
  8765. "#endif",
  8766. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  8767. "objectNormal = normal;",
  8768. "#endif",
  8769. "#ifdef FLIP_SIDED",
  8770. "objectNormal = -objectNormal;",
  8771. "#endif",
  8772. "vec3 transformedNormal = normalMatrix * objectNormal;",
  8773. ].join("\n"),
  8774. // SHADOW MAP
  8775. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  8776. // http://spidergl.org/example.php?id=6
  8777. // http://fabiensanglard.net/shadowmapping
  8778. shadowmap_pars_fragment: [
  8779. "#ifdef USE_SHADOWMAP",
  8780. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  8781. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  8782. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  8783. "uniform float shadowBias[ MAX_SHADOWS ];",
  8784. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8785. "float unpackDepth( const in vec4 rgba_depth ) {",
  8786. "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 );",
  8787. "float depth = dot( rgba_depth, bit_shift );",
  8788. "return depth;",
  8789. "}",
  8790. "#endif"
  8791. ].join("\n"),
  8792. shadowmap_fragment: [
  8793. "#ifdef USE_SHADOWMAP",
  8794. "#ifdef SHADOWMAP_DEBUG",
  8795. "vec3 frustumColors[3];",
  8796. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  8797. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  8798. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  8799. "#endif",
  8800. "#ifdef SHADOWMAP_CASCADE",
  8801. "int inFrustumCount = 0;",
  8802. "#endif",
  8803. "float fDepth;",
  8804. "vec3 shadowColor = vec3( 1.0 );",
  8805. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8806. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  8807. // "if ( something && something )" breaks ATI OpenGL shader compiler
  8808. // "if ( all( something, something ) )" using this instead
  8809. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  8810. "bool inFrustum = all( inFrustumVec );",
  8811. // don't shadow pixels outside of light frustum
  8812. // use just first frustum (for cascades)
  8813. // don't shadow pixels behind far plane of light frustum
  8814. "#ifdef SHADOWMAP_CASCADE",
  8815. "inFrustumCount += int( inFrustum );",
  8816. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  8817. "#else",
  8818. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  8819. "#endif",
  8820. "bool frustumTest = all( frustumTestVec );",
  8821. "if ( frustumTest ) {",
  8822. "shadowCoord.z += shadowBias[ i ];",
  8823. "#ifdef SHADOWMAP_SOFT",
  8824. // Percentage-close filtering
  8825. // (9 pixel kernel)
  8826. // http://fabiensanglard.net/shadowmappingPCF/
  8827. "float shadow = 0.0;",
  8828. /*
  8829. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  8830. // must enroll loop manually
  8831. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  8832. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  8833. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  8834. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  8835. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  8836. "float fDepth = unpackDepth( rgbaDepth );",
  8837. "if ( fDepth < shadowCoord.z )",
  8838. "shadow += 1.0;",
  8839. "}",
  8840. "shadow /= 9.0;",
  8841. */
  8842. "const float shadowDelta = 1.0 / 9.0;",
  8843. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  8844. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  8845. "float dx0 = -1.25 * xPixelOffset;",
  8846. "float dy0 = -1.25 * yPixelOffset;",
  8847. "float dx1 = 1.25 * xPixelOffset;",
  8848. "float dy1 = 1.25 * yPixelOffset;",
  8849. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  8850. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8851. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  8852. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8853. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  8854. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8855. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  8856. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8857. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  8858. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8859. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  8860. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8861. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  8862. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8863. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  8864. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8865. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  8866. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  8867. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  8868. "#else",
  8869. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  8870. "float fDepth = unpackDepth( rgbaDepth );",
  8871. "if ( fDepth < shadowCoord.z )",
  8872. // spot with multiple shadows is darker
  8873. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  8874. // spot with multiple shadows has the same color as single shadow spot
  8875. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  8876. "#endif",
  8877. "}",
  8878. "#ifdef SHADOWMAP_DEBUG",
  8879. "#ifdef SHADOWMAP_CASCADE",
  8880. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  8881. "#else",
  8882. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  8883. "#endif",
  8884. "#endif",
  8885. "}",
  8886. "#ifdef GAMMA_OUTPUT",
  8887. "shadowColor *= shadowColor;",
  8888. "#endif",
  8889. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  8890. "#endif"
  8891. ].join("\n"),
  8892. shadowmap_pars_vertex: [
  8893. "#ifdef USE_SHADOWMAP",
  8894. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  8895. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  8896. "#endif"
  8897. ].join("\n"),
  8898. shadowmap_vertex: [
  8899. "#ifdef USE_SHADOWMAP",
  8900. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  8901. "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
  8902. "}",
  8903. "#endif"
  8904. ].join("\n"),
  8905. // ALPHATEST
  8906. alphatest_fragment: [
  8907. "#ifdef ALPHATEST",
  8908. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  8909. "#endif"
  8910. ].join("\n"),
  8911. // LINEAR SPACE
  8912. linear_to_gamma_fragment: [
  8913. "#ifdef GAMMA_OUTPUT",
  8914. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  8915. "#endif"
  8916. ].join("\n"),
  8917. };
  8918. THREE.UniformsUtils = {
  8919. merge: function ( uniforms ) {
  8920. var u, p, tmp, merged = {};
  8921. for ( u = 0; u < uniforms.length; u ++ ) {
  8922. tmp = this.clone( uniforms[ u ] );
  8923. for ( p in tmp ) {
  8924. merged[ p ] = tmp[ p ];
  8925. }
  8926. }
  8927. return merged;
  8928. },
  8929. clone: function ( uniforms_src ) {
  8930. var u, p, parameter, parameter_src, uniforms_dst = {};
  8931. for ( u in uniforms_src ) {
  8932. uniforms_dst[ u ] = {};
  8933. for ( p in uniforms_src[ u ] ) {
  8934. parameter_src = uniforms_src[ u ][ p ];
  8935. if ( parameter_src instanceof THREE.Color ||
  8936. parameter_src instanceof THREE.Vector2 ||
  8937. parameter_src instanceof THREE.Vector3 ||
  8938. parameter_src instanceof THREE.Vector4 ||
  8939. parameter_src instanceof THREE.Matrix4 ||
  8940. parameter_src instanceof THREE.Texture ) {
  8941. uniforms_dst[ u ][ p ] = parameter_src.clone();
  8942. } else if ( parameter_src instanceof Array ) {
  8943. uniforms_dst[ u ][ p ] = parameter_src.slice();
  8944. } else {
  8945. uniforms_dst[ u ][ p ] = parameter_src;
  8946. }
  8947. }
  8948. }
  8949. return uniforms_dst;
  8950. }
  8951. };
  8952. THREE.UniformsLib = {
  8953. common: {
  8954. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  8955. "opacity" : { type: "f", value: 1.0 },
  8956. "map" : { type: "t", value: null },
  8957. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  8958. "lightMap" : { type: "t", value: null },
  8959. "specularMap" : { type: "t", value: null },
  8960. "envMap" : { type: "t", value: null },
  8961. "flipEnvMap" : { type: "f", value: -1 },
  8962. "useRefract" : { type: "i", value: 0 },
  8963. "reflectivity" : { type: "f", value: 1.0 },
  8964. "refractionRatio" : { type: "f", value: 0.98 },
  8965. "combine" : { type: "i", value: 0 },
  8966. "morphTargetInfluences" : { type: "f", value: 0 }
  8967. },
  8968. bump: {
  8969. "bumpMap" : { type: "t", value: null },
  8970. "bumpScale" : { type: "f", value: 1 }
  8971. },
  8972. normalmap: {
  8973. "normalMap" : { type: "t", value: null },
  8974. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  8975. },
  8976. fog : {
  8977. "fogDensity" : { type: "f", value: 0.00025 },
  8978. "fogNear" : { type: "f", value: 1 },
  8979. "fogFar" : { type: "f", value: 2000 },
  8980. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  8981. },
  8982. lights: {
  8983. "ambientLightColor" : { type: "fv", value: [] },
  8984. "directionalLightDirection" : { type: "fv", value: [] },
  8985. "directionalLightColor" : { type: "fv", value: [] },
  8986. "hemisphereLightPosition" : { type: "fv", value: [] },
  8987. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  8988. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  8989. "pointLightColor" : { type: "fv", value: [] },
  8990. "pointLightPosition" : { type: "fv", value: [] },
  8991. "pointLightDistance" : { type: "fv1", value: [] },
  8992. "spotLightColor" : { type: "fv", value: [] },
  8993. "spotLightPosition" : { type: "fv", value: [] },
  8994. "spotLightDirection" : { type: "fv", value: [] },
  8995. "spotLightDistance" : { type: "fv1", value: [] },
  8996. "spotLightAngle" : { type: "fv1", value: [] },
  8997. "spotLightExponent" : { type: "fv1", value: [] }
  8998. },
  8999. particle: {
  9000. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9001. "opacity" : { type: "f", value: 1.0 },
  9002. "size" : { type: "f", value: 1.0 },
  9003. "scale" : { type: "f", value: 1.0 },
  9004. "map" : { type: "t", value: null },
  9005. "fogDensity" : { type: "f", value: 0.00025 },
  9006. "fogNear" : { type: "f", value: 1 },
  9007. "fogFar" : { type: "f", value: 2000 },
  9008. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9009. },
  9010. shadowmap: {
  9011. "shadowMap": { type: "tv", value: [] },
  9012. "shadowMapSize": { type: "v2v", value: [] },
  9013. "shadowBias" : { type: "fv1", value: [] },
  9014. "shadowDarkness": { type: "fv1", value: [] },
  9015. "shadowMatrix" : { type: "m4v", value: [] },
  9016. }
  9017. };
  9018. THREE.ShaderLib = {
  9019. 'depth': {
  9020. uniforms: {
  9021. "mNear": { type: "f", value: 1.0 },
  9022. "mFar" : { type: "f", value: 2000.0 },
  9023. "opacity" : { type: "f", value: 1.0 }
  9024. },
  9025. vertexShader: [
  9026. "void main() {",
  9027. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9028. "}"
  9029. ].join("\n"),
  9030. fragmentShader: [
  9031. "uniform float mNear;",
  9032. "uniform float mFar;",
  9033. "uniform float opacity;",
  9034. "void main() {",
  9035. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9036. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9037. "gl_FragColor = vec4( vec3( color ), opacity );",
  9038. "}"
  9039. ].join("\n")
  9040. },
  9041. 'normal': {
  9042. uniforms: {
  9043. "opacity" : { type: "f", value: 1.0 }
  9044. },
  9045. vertexShader: [
  9046. "varying vec3 vNormal;",
  9047. "void main() {",
  9048. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9049. "vNormal = normalMatrix * normal;",
  9050. "gl_Position = projectionMatrix * mvPosition;",
  9051. "}"
  9052. ].join("\n"),
  9053. fragmentShader: [
  9054. "uniform float opacity;",
  9055. "varying vec3 vNormal;",
  9056. "void main() {",
  9057. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9058. "}"
  9059. ].join("\n")
  9060. },
  9061. 'basic': {
  9062. uniforms: THREE.UniformsUtils.merge( [
  9063. THREE.UniformsLib[ "common" ],
  9064. THREE.UniformsLib[ "fog" ],
  9065. THREE.UniformsLib[ "shadowmap" ]
  9066. ] ),
  9067. vertexShader: [
  9068. THREE.ShaderChunk[ "map_pars_vertex" ],
  9069. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9070. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9071. THREE.ShaderChunk[ "color_pars_vertex" ],
  9072. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9073. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9074. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9075. "void main() {",
  9076. THREE.ShaderChunk[ "map_vertex" ],
  9077. THREE.ShaderChunk[ "lightmap_vertex" ],
  9078. THREE.ShaderChunk[ "color_vertex" ],
  9079. "#ifdef USE_ENVMAP",
  9080. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9081. THREE.ShaderChunk[ "skinbase_vertex" ],
  9082. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9083. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9084. "#endif",
  9085. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9086. THREE.ShaderChunk[ "skinning_vertex" ],
  9087. THREE.ShaderChunk[ "default_vertex" ],
  9088. THREE.ShaderChunk[ "worldpos_vertex" ],
  9089. THREE.ShaderChunk[ "envmap_vertex" ],
  9090. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9091. "}"
  9092. ].join("\n"),
  9093. fragmentShader: [
  9094. "uniform vec3 diffuse;",
  9095. "uniform float opacity;",
  9096. THREE.ShaderChunk[ "color_pars_fragment" ],
  9097. THREE.ShaderChunk[ "map_pars_fragment" ],
  9098. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9099. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9100. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9101. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9102. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9103. "void main() {",
  9104. "gl_FragColor = vec4( diffuse, opacity );",
  9105. THREE.ShaderChunk[ "map_fragment" ],
  9106. THREE.ShaderChunk[ "alphatest_fragment" ],
  9107. THREE.ShaderChunk[ "specularmap_fragment" ],
  9108. THREE.ShaderChunk[ "lightmap_fragment" ],
  9109. THREE.ShaderChunk[ "color_fragment" ],
  9110. THREE.ShaderChunk[ "envmap_fragment" ],
  9111. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9112. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9113. THREE.ShaderChunk[ "fog_fragment" ],
  9114. "}"
  9115. ].join("\n")
  9116. },
  9117. 'lambert': {
  9118. uniforms: THREE.UniformsUtils.merge( [
  9119. THREE.UniformsLib[ "common" ],
  9120. THREE.UniformsLib[ "fog" ],
  9121. THREE.UniformsLib[ "lights" ],
  9122. THREE.UniformsLib[ "shadowmap" ],
  9123. {
  9124. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9125. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9126. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9127. }
  9128. ] ),
  9129. vertexShader: [
  9130. "#define LAMBERT",
  9131. "varying vec3 vLightFront;",
  9132. "#ifdef DOUBLE_SIDED",
  9133. "varying vec3 vLightBack;",
  9134. "#endif",
  9135. THREE.ShaderChunk[ "map_pars_vertex" ],
  9136. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9137. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9138. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9139. THREE.ShaderChunk[ "color_pars_vertex" ],
  9140. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9141. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9142. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9143. "void main() {",
  9144. THREE.ShaderChunk[ "map_vertex" ],
  9145. THREE.ShaderChunk[ "lightmap_vertex" ],
  9146. THREE.ShaderChunk[ "color_vertex" ],
  9147. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9148. THREE.ShaderChunk[ "skinbase_vertex" ],
  9149. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9150. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9151. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9152. THREE.ShaderChunk[ "skinning_vertex" ],
  9153. THREE.ShaderChunk[ "default_vertex" ],
  9154. THREE.ShaderChunk[ "worldpos_vertex" ],
  9155. THREE.ShaderChunk[ "envmap_vertex" ],
  9156. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9157. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9158. "}"
  9159. ].join("\n"),
  9160. fragmentShader: [
  9161. "uniform float opacity;",
  9162. "varying vec3 vLightFront;",
  9163. "#ifdef DOUBLE_SIDED",
  9164. "varying vec3 vLightBack;",
  9165. "#endif",
  9166. THREE.ShaderChunk[ "color_pars_fragment" ],
  9167. THREE.ShaderChunk[ "map_pars_fragment" ],
  9168. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9169. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9170. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9171. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9172. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9173. "void main() {",
  9174. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9175. THREE.ShaderChunk[ "map_fragment" ],
  9176. THREE.ShaderChunk[ "alphatest_fragment" ],
  9177. THREE.ShaderChunk[ "specularmap_fragment" ],
  9178. "#ifdef DOUBLE_SIDED",
  9179. //"float isFront = float( gl_FrontFacing );",
  9180. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9181. "if ( gl_FrontFacing )",
  9182. "gl_FragColor.xyz *= vLightFront;",
  9183. "else",
  9184. "gl_FragColor.xyz *= vLightBack;",
  9185. "#else",
  9186. "gl_FragColor.xyz *= vLightFront;",
  9187. "#endif",
  9188. THREE.ShaderChunk[ "lightmap_fragment" ],
  9189. THREE.ShaderChunk[ "color_fragment" ],
  9190. THREE.ShaderChunk[ "envmap_fragment" ],
  9191. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9192. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9193. THREE.ShaderChunk[ "fog_fragment" ],
  9194. "}"
  9195. ].join("\n")
  9196. },
  9197. 'phong': {
  9198. uniforms: THREE.UniformsUtils.merge( [
  9199. THREE.UniformsLib[ "common" ],
  9200. THREE.UniformsLib[ "bump" ],
  9201. THREE.UniformsLib[ "normalmap" ],
  9202. THREE.UniformsLib[ "fog" ],
  9203. THREE.UniformsLib[ "lights" ],
  9204. THREE.UniformsLib[ "shadowmap" ],
  9205. {
  9206. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9207. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9208. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9209. "shininess": { type: "f", value: 30 },
  9210. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9211. }
  9212. ] ),
  9213. vertexShader: [
  9214. "#define PHONG",
  9215. "varying vec3 vViewPosition;",
  9216. "varying vec3 vNormal;",
  9217. THREE.ShaderChunk[ "map_pars_vertex" ],
  9218. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9219. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9220. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9221. THREE.ShaderChunk[ "color_pars_vertex" ],
  9222. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9223. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9224. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9225. "void main() {",
  9226. THREE.ShaderChunk[ "map_vertex" ],
  9227. THREE.ShaderChunk[ "lightmap_vertex" ],
  9228. THREE.ShaderChunk[ "color_vertex" ],
  9229. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9230. THREE.ShaderChunk[ "skinbase_vertex" ],
  9231. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9232. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9233. "vNormal = transformedNormal;",
  9234. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9235. THREE.ShaderChunk[ "skinning_vertex" ],
  9236. THREE.ShaderChunk[ "default_vertex" ],
  9237. "vViewPosition = -mvPosition.xyz;",
  9238. THREE.ShaderChunk[ "worldpos_vertex" ],
  9239. THREE.ShaderChunk[ "envmap_vertex" ],
  9240. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9241. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9242. "}"
  9243. ].join("\n"),
  9244. fragmentShader: [
  9245. "uniform vec3 diffuse;",
  9246. "uniform float opacity;",
  9247. "uniform vec3 ambient;",
  9248. "uniform vec3 emissive;",
  9249. "uniform vec3 specular;",
  9250. "uniform float shininess;",
  9251. THREE.ShaderChunk[ "color_pars_fragment" ],
  9252. THREE.ShaderChunk[ "map_pars_fragment" ],
  9253. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9254. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9255. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9256. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9257. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9258. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9259. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9260. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9261. "void main() {",
  9262. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9263. THREE.ShaderChunk[ "map_fragment" ],
  9264. THREE.ShaderChunk[ "alphatest_fragment" ],
  9265. THREE.ShaderChunk[ "specularmap_fragment" ],
  9266. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9267. THREE.ShaderChunk[ "lightmap_fragment" ],
  9268. THREE.ShaderChunk[ "color_fragment" ],
  9269. THREE.ShaderChunk[ "envmap_fragment" ],
  9270. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9271. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9272. THREE.ShaderChunk[ "fog_fragment" ],
  9273. "}"
  9274. ].join("\n")
  9275. },
  9276. 'particle_basic': {
  9277. uniforms: THREE.UniformsUtils.merge( [
  9278. THREE.UniformsLib[ "particle" ],
  9279. THREE.UniformsLib[ "shadowmap" ]
  9280. ] ),
  9281. vertexShader: [
  9282. "uniform float size;",
  9283. "uniform float scale;",
  9284. THREE.ShaderChunk[ "color_pars_vertex" ],
  9285. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9286. "void main() {",
  9287. THREE.ShaderChunk[ "color_vertex" ],
  9288. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9289. "#ifdef USE_SIZEATTENUATION",
  9290. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9291. "#else",
  9292. "gl_PointSize = size;",
  9293. "#endif",
  9294. "gl_Position = projectionMatrix * mvPosition;",
  9295. THREE.ShaderChunk[ "worldpos_vertex" ],
  9296. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9297. "}"
  9298. ].join("\n"),
  9299. fragmentShader: [
  9300. "uniform vec3 psColor;",
  9301. "uniform float opacity;",
  9302. THREE.ShaderChunk[ "color_pars_fragment" ],
  9303. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9304. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9305. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9306. "void main() {",
  9307. "gl_FragColor = vec4( psColor, opacity );",
  9308. THREE.ShaderChunk[ "map_particle_fragment" ],
  9309. THREE.ShaderChunk[ "alphatest_fragment" ],
  9310. THREE.ShaderChunk[ "color_fragment" ],
  9311. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9312. THREE.ShaderChunk[ "fog_fragment" ],
  9313. "}"
  9314. ].join("\n")
  9315. },
  9316. // Depth encoding into RGBA texture
  9317. // based on SpiderGL shadow map example
  9318. // http://spidergl.org/example.php?id=6
  9319. // originally from
  9320. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  9321. // see also here:
  9322. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  9323. 'depthRGBA': {
  9324. uniforms: {},
  9325. vertexShader: [
  9326. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9327. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9328. "void main() {",
  9329. THREE.ShaderChunk[ "skinbase_vertex" ],
  9330. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9331. THREE.ShaderChunk[ "skinning_vertex" ],
  9332. THREE.ShaderChunk[ "default_vertex" ],
  9333. "}"
  9334. ].join("\n"),
  9335. fragmentShader: [
  9336. "vec4 pack_depth( const in float depth ) {",
  9337. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  9338. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  9339. "vec4 res = fract( depth * bit_shift );",
  9340. "res -= res.xxyz * bit_mask;",
  9341. "return res;",
  9342. "}",
  9343. "void main() {",
  9344. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  9345. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  9346. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  9347. //"gl_FragData[ 0 ] = pack_depth( z );",
  9348. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  9349. "}"
  9350. ].join("\n")
  9351. }
  9352. };
  9353. /**
  9354. * @author supereggbert / http://www.paulbrunt.co.uk/
  9355. * @author mrdoob / http://mrdoob.com/
  9356. * @author alteredq / http://alteredqualia.com/
  9357. * @author szimek / https://github.com/szimek/
  9358. */
  9359. THREE.WebGLRenderer = function ( parameters ) {
  9360. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  9361. parameters = parameters || {};
  9362. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  9363. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  9364. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  9365. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  9366. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  9367. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  9368. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  9369. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  9370. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  9371. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  9372. // public properties
  9373. this.domElement = _canvas;
  9374. this.context = null;
  9375. // clearing
  9376. this.autoClear = true;
  9377. this.autoClearColor = true;
  9378. this.autoClearDepth = true;
  9379. this.autoClearStencil = true;
  9380. // scene graph
  9381. this.sortObjects = true;
  9382. this.autoUpdateObjects = true;
  9383. this.autoUpdateScene = true;
  9384. // physically based shading
  9385. this.gammaInput = false;
  9386. this.gammaOutput = false;
  9387. this.physicallyBasedShading = false;
  9388. // shadow map
  9389. this.shadowMapEnabled = false;
  9390. this.shadowMapAutoUpdate = true;
  9391. this.shadowMapSoft = true;
  9392. this.shadowMapCullFrontFaces = true;
  9393. this.shadowMapDebug = false;
  9394. this.shadowMapCascade = false;
  9395. // morphs
  9396. this.maxMorphTargets = 8;
  9397. this.maxMorphNormals = 4;
  9398. // flags
  9399. this.autoScaleCubemaps = true;
  9400. // custom render plugins
  9401. this.renderPluginsPre = [];
  9402. this.renderPluginsPost = [];
  9403. // info
  9404. this.info = {
  9405. memory: {
  9406. programs: 0,
  9407. geometries: 0,
  9408. textures: 0
  9409. },
  9410. render: {
  9411. calls: 0,
  9412. vertices: 0,
  9413. faces: 0,
  9414. points: 0
  9415. }
  9416. };
  9417. // internal properties
  9418. var _this = this,
  9419. _programs = [],
  9420. _programs_counter = 0,
  9421. // internal state cache
  9422. _currentProgram = null,
  9423. _currentFramebuffer = null,
  9424. _currentMaterialId = -1,
  9425. _currentGeometryGroupHash = null,
  9426. _currentCamera = null,
  9427. _geometryGroupCounter = 0,
  9428. _usedTextureUnits = 0,
  9429. // GL state cache
  9430. _oldDoubleSided = -1,
  9431. _oldFlipSided = -1,
  9432. _oldBlending = -1,
  9433. _oldBlendEquation = -1,
  9434. _oldBlendSrc = -1,
  9435. _oldBlendDst = -1,
  9436. _oldDepthTest = -1,
  9437. _oldDepthWrite = -1,
  9438. _oldPolygonOffset = null,
  9439. _oldPolygonOffsetFactor = null,
  9440. _oldPolygonOffsetUnits = null,
  9441. _oldLineWidth = null,
  9442. _viewportX = 0,
  9443. _viewportY = 0,
  9444. _viewportWidth = 0,
  9445. _viewportHeight = 0,
  9446. _currentWidth = 0,
  9447. _currentHeight = 0,
  9448. // frustum
  9449. _frustum = new THREE.Frustum(),
  9450. // camera matrices cache
  9451. _projScreenMatrix = new THREE.Matrix4(),
  9452. _projScreenMatrixPS = new THREE.Matrix4(),
  9453. _vector3 = new THREE.Vector4(),
  9454. // light arrays cache
  9455. _direction = new THREE.Vector3(),
  9456. _lightsNeedUpdate = true,
  9457. _lights = {
  9458. ambient: [ 0, 0, 0 ],
  9459. directional: { length: 0, colors: new Array(), positions: new Array() },
  9460. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  9461. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), angles: new Array(), exponents: new Array() },
  9462. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  9463. };
  9464. // initialize
  9465. var _gl;
  9466. var _glExtensionTextureFloat;
  9467. var _glExtensionStandardDerivatives;
  9468. var _glExtensionTextureFilterAnisotropic;
  9469. var _glExtensionCompressedTextureS3TC;
  9470. initGL();
  9471. setDefaultGLState();
  9472. this.context = _gl;
  9473. // GPU capabilities
  9474. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  9475. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  9476. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  9477. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  9478. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  9479. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  9480. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  9481. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  9482. // API
  9483. this.getContext = function () {
  9484. return _gl;
  9485. };
  9486. this.supportsVertexTextures = function () {
  9487. return _supportsVertexTextures;
  9488. };
  9489. this.getMaxAnisotropy = function () {
  9490. return _maxAnisotropy;
  9491. };
  9492. this.setSize = function ( width, height ) {
  9493. _canvas.width = width;
  9494. _canvas.height = height;
  9495. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  9496. };
  9497. this.setViewport = function ( x, y, width, height ) {
  9498. _viewportX = x !== undefined ? x : 0;
  9499. _viewportY = y !== undefined ? y : 0;
  9500. _viewportWidth = width !== undefined ? width : _canvas.width;
  9501. _viewportHeight = height !== undefined ? height : _canvas.height;
  9502. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  9503. };
  9504. this.setScissor = function ( x, y, width, height ) {
  9505. _gl.scissor( x, y, width, height );
  9506. };
  9507. this.enableScissorTest = function ( enable ) {
  9508. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  9509. };
  9510. // Clearing
  9511. this.setClearColorHex = function ( hex, alpha ) {
  9512. _clearColor.setHex( hex );
  9513. _clearAlpha = alpha;
  9514. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9515. };
  9516. this.setClearColor = function ( color, alpha ) {
  9517. _clearColor.copy( color );
  9518. _clearAlpha = alpha;
  9519. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9520. };
  9521. this.getClearColor = function () {
  9522. return _clearColor;
  9523. };
  9524. this.getClearAlpha = function () {
  9525. return _clearAlpha;
  9526. };
  9527. this.clear = function ( color, depth, stencil ) {
  9528. var bits = 0;
  9529. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  9530. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  9531. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  9532. _gl.clear( bits );
  9533. };
  9534. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  9535. this.setRenderTarget( renderTarget );
  9536. this.clear( color, depth, stencil );
  9537. };
  9538. // Plugins
  9539. this.addPostPlugin = function ( plugin ) {
  9540. plugin.init( this );
  9541. this.renderPluginsPost.push( plugin );
  9542. };
  9543. this.addPrePlugin = function ( plugin ) {
  9544. plugin.init( this );
  9545. this.renderPluginsPre.push( plugin );
  9546. };
  9547. // Deallocation
  9548. this.deallocateObject = function ( object ) {
  9549. if ( ! object.__webglInit ) return;
  9550. object.__webglInit = false;
  9551. delete object._modelViewMatrix;
  9552. delete object._normalMatrix;
  9553. delete object._normalMatrixArray;
  9554. delete object._modelViewMatrixArray;
  9555. delete object._modelMatrixArray;
  9556. if ( object instanceof THREE.Mesh ) {
  9557. for ( var g in object.geometry.geometryGroups ) {
  9558. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  9559. }
  9560. } else if ( object instanceof THREE.Ribbon ) {
  9561. deleteRibbonBuffers( object.geometry );
  9562. } else if ( object instanceof THREE.Line ) {
  9563. deleteLineBuffers( object.geometry );
  9564. } else if ( object instanceof THREE.ParticleSystem ) {
  9565. deleteParticleBuffers( object.geometry );
  9566. }
  9567. };
  9568. this.deallocateTexture = function ( texture ) {
  9569. if ( ! texture.__webglInit ) return;
  9570. texture.__webglInit = false;
  9571. _gl.deleteTexture( texture.__webglTexture );
  9572. _this.info.memory.textures --;
  9573. };
  9574. this.deallocateRenderTarget = function ( renderTarget ) {
  9575. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  9576. _gl.deleteTexture( renderTarget.__webglTexture );
  9577. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9578. for ( var i = 0; i < 6; i ++ ) {
  9579. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  9580. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  9581. }
  9582. } else {
  9583. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  9584. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  9585. }
  9586. };
  9587. this.deallocateMaterial = function ( material ) {
  9588. var program = material.program;
  9589. if ( ! program ) return;
  9590. material.program = undefined;
  9591. // only deallocate GL program if this was the last use of shared program
  9592. // assumed there is only single copy of any program in the _programs list
  9593. // (that's how it's constructed)
  9594. var i, il, programInfo;
  9595. var deleteProgram = false;
  9596. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9597. programInfo = _programs[ i ];
  9598. if ( programInfo.program === program ) {
  9599. programInfo.usedTimes --;
  9600. if ( programInfo.usedTimes === 0 ) {
  9601. deleteProgram = true;
  9602. }
  9603. break;
  9604. }
  9605. }
  9606. if ( deleteProgram ) {
  9607. // avoid using array.splice, this is costlier than creating new array from scratch
  9608. var newPrograms = [];
  9609. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  9610. programInfo = _programs[ i ];
  9611. if ( programInfo.program !== program ) {
  9612. newPrograms.push( programInfo );
  9613. }
  9614. }
  9615. _programs = newPrograms;
  9616. _gl.deleteProgram( program );
  9617. _this.info.memory.programs --;
  9618. }
  9619. };
  9620. // Rendering
  9621. this.updateShadowMap = function ( scene, camera ) {
  9622. _currentProgram = null;
  9623. _oldBlending = -1;
  9624. _oldDepthTest = -1;
  9625. _oldDepthWrite = -1;
  9626. _currentGeometryGroupHash = -1;
  9627. _currentMaterialId = -1;
  9628. _lightsNeedUpdate = true;
  9629. _oldDoubleSided = -1;
  9630. _oldFlipSided = -1;
  9631. this.shadowMapPlugin.update( scene, camera );
  9632. };
  9633. // Internal functions
  9634. // Buffer allocation
  9635. function createParticleBuffers ( geometry ) {
  9636. geometry.__webglVertexBuffer = _gl.createBuffer();
  9637. geometry.__webglColorBuffer = _gl.createBuffer();
  9638. _this.info.memory.geometries ++;
  9639. };
  9640. function createLineBuffers ( geometry ) {
  9641. geometry.__webglVertexBuffer = _gl.createBuffer();
  9642. geometry.__webglColorBuffer = _gl.createBuffer();
  9643. _this.info.memory.geometries ++;
  9644. };
  9645. function createRibbonBuffers ( geometry ) {
  9646. geometry.__webglVertexBuffer = _gl.createBuffer();
  9647. geometry.__webglColorBuffer = _gl.createBuffer();
  9648. _this.info.memory.geometries ++;
  9649. };
  9650. function createMeshBuffers ( geometryGroup ) {
  9651. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  9652. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  9653. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  9654. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  9655. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  9656. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  9657. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  9658. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  9659. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  9660. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  9661. var m, ml;
  9662. if ( geometryGroup.numMorphTargets ) {
  9663. geometryGroup.__webglMorphTargetsBuffers = [];
  9664. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9665. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  9666. }
  9667. }
  9668. if ( geometryGroup.numMorphNormals ) {
  9669. geometryGroup.__webglMorphNormalsBuffers = [];
  9670. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9671. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  9672. }
  9673. }
  9674. _this.info.memory.geometries ++;
  9675. };
  9676. // Buffer deallocation
  9677. function deleteParticleBuffers ( geometry ) {
  9678. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9679. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9680. _this.info.memory.geometries --;
  9681. };
  9682. function deleteLineBuffers ( geometry ) {
  9683. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9684. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9685. _this.info.memory.geometries --;
  9686. };
  9687. function deleteRibbonBuffers ( geometry ) {
  9688. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  9689. _gl.deleteBuffer( geometry.__webglColorBuffer );
  9690. _this.info.memory.geometries --;
  9691. };
  9692. function deleteMeshBuffers ( geometryGroup ) {
  9693. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  9694. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  9695. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  9696. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  9697. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  9698. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  9699. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  9700. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  9701. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  9702. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  9703. var m, ml;
  9704. if ( geometryGroup.numMorphTargets ) {
  9705. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9706. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  9707. }
  9708. }
  9709. if ( geometryGroup.numMorphNormals ) {
  9710. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9711. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  9712. }
  9713. }
  9714. if ( geometryGroup.__webglCustomAttributesList ) {
  9715. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  9716. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  9717. }
  9718. }
  9719. _this.info.memory.geometries --;
  9720. };
  9721. // Buffer initialization
  9722. function initCustomAttributes ( geometry, object ) {
  9723. var nvertices = geometry.vertices.length;
  9724. var material = object.material;
  9725. if ( material.attributes ) {
  9726. if ( geometry.__webglCustomAttributesList === undefined ) {
  9727. geometry.__webglCustomAttributesList = [];
  9728. }
  9729. for ( var a in material.attributes ) {
  9730. var attribute = material.attributes[ a ];
  9731. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9732. attribute.__webglInitialized = true;
  9733. var size = 1; // "f" and "i"
  9734. if ( attribute.type === "v2" ) size = 2;
  9735. else if ( attribute.type === "v3" ) size = 3;
  9736. else if ( attribute.type === "v4" ) size = 4;
  9737. else if ( attribute.type === "c" ) size = 3;
  9738. attribute.size = size;
  9739. attribute.array = new Float32Array( nvertices * size );
  9740. attribute.buffer = _gl.createBuffer();
  9741. attribute.buffer.belongsToAttribute = a;
  9742. attribute.needsUpdate = true;
  9743. }
  9744. geometry.__webglCustomAttributesList.push( attribute );
  9745. }
  9746. }
  9747. };
  9748. function initParticleBuffers ( geometry, object ) {
  9749. var nvertices = geometry.vertices.length;
  9750. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9751. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9752. geometry.__sortArray = [];
  9753. geometry.__webglParticleCount = nvertices;
  9754. initCustomAttributes ( geometry, object );
  9755. };
  9756. function initLineBuffers ( geometry, object ) {
  9757. var nvertices = geometry.vertices.length;
  9758. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9759. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9760. geometry.__webglLineCount = nvertices;
  9761. initCustomAttributes ( geometry, object );
  9762. };
  9763. function initRibbonBuffers ( geometry ) {
  9764. var nvertices = geometry.vertices.length;
  9765. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  9766. geometry.__colorArray = new Float32Array( nvertices * 3 );
  9767. geometry.__webglVertexCount = nvertices;
  9768. };
  9769. function initMeshBuffers ( geometryGroup, object ) {
  9770. var geometry = object.geometry,
  9771. faces3 = geometryGroup.faces3,
  9772. faces4 = geometryGroup.faces4,
  9773. nvertices = faces3.length * 3 + faces4.length * 4,
  9774. ntris = faces3.length * 1 + faces4.length * 2,
  9775. nlines = faces3.length * 3 + faces4.length * 4,
  9776. material = getBufferMaterial( object, geometryGroup ),
  9777. uvType = bufferGuessUVType( material ),
  9778. normalType = bufferGuessNormalType( material ),
  9779. vertexColorType = bufferGuessVertexColorType( material );
  9780. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  9781. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  9782. if ( normalType ) {
  9783. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  9784. }
  9785. if ( geometry.hasTangents ) {
  9786. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  9787. }
  9788. if ( vertexColorType ) {
  9789. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  9790. }
  9791. if ( uvType ) {
  9792. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  9793. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  9794. }
  9795. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  9796. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  9797. }
  9798. }
  9799. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  9800. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  9801. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  9802. }
  9803. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  9804. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  9805. var m, ml;
  9806. if ( geometryGroup.numMorphTargets ) {
  9807. geometryGroup.__morphTargetsArrays = [];
  9808. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  9809. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  9810. }
  9811. }
  9812. if ( geometryGroup.numMorphNormals ) {
  9813. geometryGroup.__morphNormalsArrays = [];
  9814. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  9815. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  9816. }
  9817. }
  9818. geometryGroup.__webglFaceCount = ntris * 3;
  9819. geometryGroup.__webglLineCount = nlines * 2;
  9820. // custom attributes
  9821. if ( material.attributes ) {
  9822. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  9823. geometryGroup.__webglCustomAttributesList = [];
  9824. }
  9825. for ( var a in material.attributes ) {
  9826. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  9827. // attribute buffers which are correctly indexed in the setMeshBuffers function
  9828. var originalAttribute = material.attributes[ a ];
  9829. var attribute = {};
  9830. for ( var property in originalAttribute ) {
  9831. attribute[ property ] = originalAttribute[ property ];
  9832. }
  9833. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  9834. attribute.__webglInitialized = true;
  9835. var size = 1; // "f" and "i"
  9836. if( attribute.type === "v2" ) size = 2;
  9837. else if( attribute.type === "v3" ) size = 3;
  9838. else if( attribute.type === "v4" ) size = 4;
  9839. else if( attribute.type === "c" ) size = 3;
  9840. attribute.size = size;
  9841. attribute.array = new Float32Array( nvertices * size );
  9842. attribute.buffer = _gl.createBuffer();
  9843. attribute.buffer.belongsToAttribute = a;
  9844. originalAttribute.needsUpdate = true;
  9845. attribute.__original = originalAttribute;
  9846. }
  9847. geometryGroup.__webglCustomAttributesList.push( attribute );
  9848. }
  9849. }
  9850. geometryGroup.__inittedArrays = true;
  9851. };
  9852. function getBufferMaterial( object, geometryGroup ) {
  9853. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  9854. return object.material;
  9855. } else if ( geometryGroup.materialIndex >= 0 ) {
  9856. return object.geometry.materials[ geometryGroup.materialIndex ];
  9857. }
  9858. };
  9859. function materialNeedsSmoothNormals ( material ) {
  9860. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  9861. };
  9862. function bufferGuessNormalType ( material ) {
  9863. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  9864. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  9865. return false;
  9866. }
  9867. if ( materialNeedsSmoothNormals( material ) ) {
  9868. return THREE.SmoothShading;
  9869. } else {
  9870. return THREE.FlatShading;
  9871. }
  9872. };
  9873. function bufferGuessVertexColorType ( material ) {
  9874. if ( material.vertexColors ) {
  9875. return material.vertexColors;
  9876. }
  9877. return false;
  9878. };
  9879. function bufferGuessUVType ( material ) {
  9880. // material must use some texture to require uvs
  9881. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  9882. return true;
  9883. }
  9884. return false;
  9885. };
  9886. //
  9887. function initDirectBuffers( geometry ) {
  9888. var a, attribute, type;
  9889. for ( a in geometry.attributes ) {
  9890. if ( a === "index" ) {
  9891. type = _gl.ELEMENT_ARRAY_BUFFER;
  9892. } else {
  9893. type = _gl.ARRAY_BUFFER;
  9894. }
  9895. attribute = geometry.attributes[ a ];
  9896. attribute.buffer = _gl.createBuffer();
  9897. _gl.bindBuffer( type, attribute.buffer );
  9898. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  9899. }
  9900. };
  9901. // Buffer setting
  9902. function setParticleBuffers ( geometry, hint, object ) {
  9903. var v, c, vertex, offset, index, color,
  9904. vertices = geometry.vertices,
  9905. vl = vertices.length,
  9906. colors = geometry.colors,
  9907. cl = colors.length,
  9908. vertexArray = geometry.__vertexArray,
  9909. colorArray = geometry.__colorArray,
  9910. sortArray = geometry.__sortArray,
  9911. dirtyVertices = geometry.verticesNeedUpdate,
  9912. dirtyElements = geometry.elementsNeedUpdate,
  9913. dirtyColors = geometry.colorsNeedUpdate,
  9914. customAttributes = geometry.__webglCustomAttributesList,
  9915. i, il,
  9916. a, ca, cal, value,
  9917. customAttribute;
  9918. if ( object.sortParticles ) {
  9919. _projScreenMatrixPS.copy( _projScreenMatrix );
  9920. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  9921. for ( v = 0; v < vl; v ++ ) {
  9922. vertex = vertices[ v ];
  9923. _vector3.copy( vertex );
  9924. _projScreenMatrixPS.multiplyVector3( _vector3 );
  9925. sortArray[ v ] = [ _vector3.z, v ];
  9926. }
  9927. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  9928. for ( v = 0; v < vl; v ++ ) {
  9929. vertex = vertices[ sortArray[v][1] ];
  9930. offset = v * 3;
  9931. vertexArray[ offset ] = vertex.x;
  9932. vertexArray[ offset + 1 ] = vertex.y;
  9933. vertexArray[ offset + 2 ] = vertex.z;
  9934. }
  9935. for ( c = 0; c < cl; c ++ ) {
  9936. offset = c * 3;
  9937. color = colors[ sortArray[c][1] ];
  9938. colorArray[ offset ] = color.r;
  9939. colorArray[ offset + 1 ] = color.g;
  9940. colorArray[ offset + 2 ] = color.b;
  9941. }
  9942. if ( customAttributes ) {
  9943. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  9944. customAttribute = customAttributes[ i ];
  9945. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  9946. offset = 0;
  9947. cal = customAttribute.value.length;
  9948. if ( customAttribute.size === 1 ) {
  9949. for ( ca = 0; ca < cal; ca ++ ) {
  9950. index = sortArray[ ca ][ 1 ];
  9951. customAttribute.array[ ca ] = customAttribute.value[ index ];
  9952. }
  9953. } else if ( customAttribute.size === 2 ) {
  9954. for ( ca = 0; ca < cal; ca ++ ) {
  9955. index = sortArray[ ca ][ 1 ];
  9956. value = customAttribute.value[ index ];
  9957. customAttribute.array[ offset ] = value.x;
  9958. customAttribute.array[ offset + 1 ] = value.y;
  9959. offset += 2;
  9960. }
  9961. } else if ( customAttribute.size === 3 ) {
  9962. if ( customAttribute.type === "c" ) {
  9963. for ( ca = 0; ca < cal; ca ++ ) {
  9964. index = sortArray[ ca ][ 1 ];
  9965. value = customAttribute.value[ index ];
  9966. customAttribute.array[ offset ] = value.r;
  9967. customAttribute.array[ offset + 1 ] = value.g;
  9968. customAttribute.array[ offset + 2 ] = value.b;
  9969. offset += 3;
  9970. }
  9971. } else {
  9972. for ( ca = 0; ca < cal; ca ++ ) {
  9973. index = sortArray[ ca ][ 1 ];
  9974. value = customAttribute.value[ index ];
  9975. customAttribute.array[ offset ] = value.x;
  9976. customAttribute.array[ offset + 1 ] = value.y;
  9977. customAttribute.array[ offset + 2 ] = value.z;
  9978. offset += 3;
  9979. }
  9980. }
  9981. } else if ( customAttribute.size === 4 ) {
  9982. for ( ca = 0; ca < cal; ca ++ ) {
  9983. index = sortArray[ ca ][ 1 ];
  9984. value = customAttribute.value[ index ];
  9985. customAttribute.array[ offset ] = value.x;
  9986. customAttribute.array[ offset + 1 ] = value.y;
  9987. customAttribute.array[ offset + 2 ] = value.z;
  9988. customAttribute.array[ offset + 3 ] = value.w;
  9989. offset += 4;
  9990. }
  9991. }
  9992. }
  9993. }
  9994. } else {
  9995. if ( dirtyVertices ) {
  9996. for ( v = 0; v < vl; v ++ ) {
  9997. vertex = vertices[ v ];
  9998. offset = v * 3;
  9999. vertexArray[ offset ] = vertex.x;
  10000. vertexArray[ offset + 1 ] = vertex.y;
  10001. vertexArray[ offset + 2 ] = vertex.z;
  10002. }
  10003. }
  10004. if ( dirtyColors ) {
  10005. for ( c = 0; c < cl; c ++ ) {
  10006. color = colors[ c ];
  10007. offset = c * 3;
  10008. colorArray[ offset ] = color.r;
  10009. colorArray[ offset + 1 ] = color.g;
  10010. colorArray[ offset + 2 ] = color.b;
  10011. }
  10012. }
  10013. if ( customAttributes ) {
  10014. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10015. customAttribute = customAttributes[ i ];
  10016. if ( customAttribute.needsUpdate &&
  10017. ( customAttribute.boundTo === undefined ||
  10018. customAttribute.boundTo === "vertices") ) {
  10019. cal = customAttribute.value.length;
  10020. offset = 0;
  10021. if ( customAttribute.size === 1 ) {
  10022. for ( ca = 0; ca < cal; ca ++ ) {
  10023. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10024. }
  10025. } else if ( customAttribute.size === 2 ) {
  10026. for ( ca = 0; ca < cal; ca ++ ) {
  10027. value = customAttribute.value[ ca ];
  10028. customAttribute.array[ offset ] = value.x;
  10029. customAttribute.array[ offset + 1 ] = value.y;
  10030. offset += 2;
  10031. }
  10032. } else if ( customAttribute.size === 3 ) {
  10033. if ( customAttribute.type === "c" ) {
  10034. for ( ca = 0; ca < cal; ca ++ ) {
  10035. value = customAttribute.value[ ca ];
  10036. customAttribute.array[ offset ] = value.r;
  10037. customAttribute.array[ offset + 1 ] = value.g;
  10038. customAttribute.array[ offset + 2 ] = value.b;
  10039. offset += 3;
  10040. }
  10041. } else {
  10042. for ( ca = 0; ca < cal; ca ++ ) {
  10043. value = customAttribute.value[ ca ];
  10044. customAttribute.array[ offset ] = value.x;
  10045. customAttribute.array[ offset + 1 ] = value.y;
  10046. customAttribute.array[ offset + 2 ] = value.z;
  10047. offset += 3;
  10048. }
  10049. }
  10050. } else if ( customAttribute.size === 4 ) {
  10051. for ( ca = 0; ca < cal; ca ++ ) {
  10052. value = customAttribute.value[ ca ];
  10053. customAttribute.array[ offset ] = value.x;
  10054. customAttribute.array[ offset + 1 ] = value.y;
  10055. customAttribute.array[ offset + 2 ] = value.z;
  10056. customAttribute.array[ offset + 3 ] = value.w;
  10057. offset += 4;
  10058. }
  10059. }
  10060. }
  10061. }
  10062. }
  10063. }
  10064. if ( dirtyVertices || object.sortParticles ) {
  10065. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10066. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10067. }
  10068. if ( dirtyColors || object.sortParticles ) {
  10069. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10070. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10071. }
  10072. if ( customAttributes ) {
  10073. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10074. customAttribute = customAttributes[ i ];
  10075. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10076. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10077. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10078. }
  10079. }
  10080. }
  10081. };
  10082. function setLineBuffers ( geometry, hint ) {
  10083. var v, c, vertex, offset, color,
  10084. vertices = geometry.vertices,
  10085. colors = geometry.colors,
  10086. vl = vertices.length,
  10087. cl = colors.length,
  10088. vertexArray = geometry.__vertexArray,
  10089. colorArray = geometry.__colorArray,
  10090. dirtyVertices = geometry.verticesNeedUpdate,
  10091. dirtyColors = geometry.colorsNeedUpdate,
  10092. customAttributes = geometry.__webglCustomAttributesList,
  10093. i, il,
  10094. a, ca, cal, value,
  10095. customAttribute;
  10096. if ( dirtyVertices ) {
  10097. for ( v = 0; v < vl; v ++ ) {
  10098. vertex = vertices[ v ];
  10099. offset = v * 3;
  10100. vertexArray[ offset ] = vertex.x;
  10101. vertexArray[ offset + 1 ] = vertex.y;
  10102. vertexArray[ offset + 2 ] = vertex.z;
  10103. }
  10104. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10105. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10106. }
  10107. if ( dirtyColors ) {
  10108. for ( c = 0; c < cl; c ++ ) {
  10109. color = colors[ c ];
  10110. offset = c * 3;
  10111. colorArray[ offset ] = color.r;
  10112. colorArray[ offset + 1 ] = color.g;
  10113. colorArray[ offset + 2 ] = color.b;
  10114. }
  10115. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10116. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10117. }
  10118. if ( customAttributes ) {
  10119. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10120. customAttribute = customAttributes[ i ];
  10121. if ( customAttribute.needsUpdate &&
  10122. ( customAttribute.boundTo === undefined ||
  10123. customAttribute.boundTo === "vertices" ) ) {
  10124. offset = 0;
  10125. cal = customAttribute.value.length;
  10126. if ( customAttribute.size === 1 ) {
  10127. for ( ca = 0; ca < cal; ca ++ ) {
  10128. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10129. }
  10130. } else if ( customAttribute.size === 2 ) {
  10131. for ( ca = 0; ca < cal; ca ++ ) {
  10132. value = customAttribute.value[ ca ];
  10133. customAttribute.array[ offset ] = value.x;
  10134. customAttribute.array[ offset + 1 ] = value.y;
  10135. offset += 2;
  10136. }
  10137. } else if ( customAttribute.size === 3 ) {
  10138. if ( customAttribute.type === "c" ) {
  10139. for ( ca = 0; ca < cal; ca ++ ) {
  10140. value = customAttribute.value[ ca ];
  10141. customAttribute.array[ offset ] = value.r;
  10142. customAttribute.array[ offset + 1 ] = value.g;
  10143. customAttribute.array[ offset + 2 ] = value.b;
  10144. offset += 3;
  10145. }
  10146. } else {
  10147. for ( ca = 0; ca < cal; ca ++ ) {
  10148. value = customAttribute.value[ ca ];
  10149. customAttribute.array[ offset ] = value.x;
  10150. customAttribute.array[ offset + 1 ] = value.y;
  10151. customAttribute.array[ offset + 2 ] = value.z;
  10152. offset += 3;
  10153. }
  10154. }
  10155. } else if ( customAttribute.size === 4 ) {
  10156. for ( ca = 0; ca < cal; ca ++ ) {
  10157. value = customAttribute.value[ ca ];
  10158. customAttribute.array[ offset ] = value.x;
  10159. customAttribute.array[ offset + 1 ] = value.y;
  10160. customAttribute.array[ offset + 2 ] = value.z;
  10161. customAttribute.array[ offset + 3 ] = value.w;
  10162. offset += 4;
  10163. }
  10164. }
  10165. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10166. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10167. }
  10168. }
  10169. }
  10170. };
  10171. function setRibbonBuffers ( geometry, hint ) {
  10172. var v, c, vertex, offset, color,
  10173. vertices = geometry.vertices,
  10174. colors = geometry.colors,
  10175. vl = vertices.length,
  10176. cl = colors.length,
  10177. vertexArray = geometry.__vertexArray,
  10178. colorArray = geometry.__colorArray,
  10179. dirtyVertices = geometry.verticesNeedUpdate,
  10180. dirtyColors = geometry.colorsNeedUpdate;
  10181. if ( dirtyVertices ) {
  10182. for ( v = 0; v < vl; v ++ ) {
  10183. vertex = vertices[ v ];
  10184. offset = v * 3;
  10185. vertexArray[ offset ] = vertex.x;
  10186. vertexArray[ offset + 1 ] = vertex.y;
  10187. vertexArray[ offset + 2 ] = vertex.z;
  10188. }
  10189. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10190. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10191. }
  10192. if ( dirtyColors ) {
  10193. for ( c = 0; c < cl; c ++ ) {
  10194. color = colors[ c ];
  10195. offset = c * 3;
  10196. colorArray[ offset ] = color.r;
  10197. colorArray[ offset + 1 ] = color.g;
  10198. colorArray[ offset + 2 ] = color.b;
  10199. }
  10200. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10201. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10202. }
  10203. };
  10204. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  10205. if ( ! geometryGroup.__inittedArrays ) {
  10206. // console.log( object );
  10207. return;
  10208. }
  10209. var normalType = bufferGuessNormalType( material ),
  10210. vertexColorType = bufferGuessVertexColorType( material ),
  10211. uvType = bufferGuessUVType( material ),
  10212. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  10213. var f, fl, fi, face,
  10214. vertexNormals, faceNormal, normal,
  10215. vertexColors, faceColor,
  10216. vertexTangents,
  10217. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  10218. c1, c2, c3, c4,
  10219. sw1, sw2, sw3, sw4,
  10220. si1, si2, si3, si4,
  10221. sa1, sa2, sa3, sa4,
  10222. sb1, sb2, sb3, sb4,
  10223. m, ml, i, il,
  10224. vn, uvi, uv2i,
  10225. vk, vkl, vka,
  10226. nka, chf, faceVertexNormals,
  10227. a,
  10228. vertexIndex = 0,
  10229. offset = 0,
  10230. offset_uv = 0,
  10231. offset_uv2 = 0,
  10232. offset_face = 0,
  10233. offset_normal = 0,
  10234. offset_tangent = 0,
  10235. offset_line = 0,
  10236. offset_color = 0,
  10237. offset_skin = 0,
  10238. offset_morphTarget = 0,
  10239. offset_custom = 0,
  10240. offset_customSrc = 0,
  10241. value,
  10242. vertexArray = geometryGroup.__vertexArray,
  10243. uvArray = geometryGroup.__uvArray,
  10244. uv2Array = geometryGroup.__uv2Array,
  10245. normalArray = geometryGroup.__normalArray,
  10246. tangentArray = geometryGroup.__tangentArray,
  10247. colorArray = geometryGroup.__colorArray,
  10248. skinIndexArray = geometryGroup.__skinIndexArray,
  10249. skinWeightArray = geometryGroup.__skinWeightArray,
  10250. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  10251. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  10252. customAttributes = geometryGroup.__webglCustomAttributesList,
  10253. customAttribute,
  10254. faceArray = geometryGroup.__faceArray,
  10255. lineArray = geometryGroup.__lineArray,
  10256. geometry = object.geometry, // this is shared for all chunks
  10257. dirtyVertices = geometry.verticesNeedUpdate,
  10258. dirtyElements = geometry.elementsNeedUpdate,
  10259. dirtyUvs = geometry.uvsNeedUpdate,
  10260. dirtyNormals = geometry.normalsNeedUpdate,
  10261. dirtyTangents = geometry.tangentsNeedUpdate,
  10262. dirtyColors = geometry.colorsNeedUpdate,
  10263. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  10264. vertices = geometry.vertices,
  10265. chunk_faces3 = geometryGroup.faces3,
  10266. chunk_faces4 = geometryGroup.faces4,
  10267. obj_faces = geometry.faces,
  10268. obj_uvs = geometry.faceVertexUvs[ 0 ],
  10269. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  10270. obj_colors = geometry.colors,
  10271. obj_skinIndices = geometry.skinIndices,
  10272. obj_skinWeights = geometry.skinWeights,
  10273. morphTargets = geometry.morphTargets,
  10274. morphNormals = geometry.morphNormals;
  10275. if ( dirtyVertices ) {
  10276. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10277. face = obj_faces[ chunk_faces3[ f ] ];
  10278. v1 = vertices[ face.a ];
  10279. v2 = vertices[ face.b ];
  10280. v3 = vertices[ face.c ];
  10281. vertexArray[ offset ] = v1.x;
  10282. vertexArray[ offset + 1 ] = v1.y;
  10283. vertexArray[ offset + 2 ] = v1.z;
  10284. vertexArray[ offset + 3 ] = v2.x;
  10285. vertexArray[ offset + 4 ] = v2.y;
  10286. vertexArray[ offset + 5 ] = v2.z;
  10287. vertexArray[ offset + 6 ] = v3.x;
  10288. vertexArray[ offset + 7 ] = v3.y;
  10289. vertexArray[ offset + 8 ] = v3.z;
  10290. offset += 9;
  10291. }
  10292. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10293. face = obj_faces[ chunk_faces4[ f ] ];
  10294. v1 = vertices[ face.a ];
  10295. v2 = vertices[ face.b ];
  10296. v3 = vertices[ face.c ];
  10297. v4 = vertices[ face.d ];
  10298. vertexArray[ offset ] = v1.x;
  10299. vertexArray[ offset + 1 ] = v1.y;
  10300. vertexArray[ offset + 2 ] = v1.z;
  10301. vertexArray[ offset + 3 ] = v2.x;
  10302. vertexArray[ offset + 4 ] = v2.y;
  10303. vertexArray[ offset + 5 ] = v2.z;
  10304. vertexArray[ offset + 6 ] = v3.x;
  10305. vertexArray[ offset + 7 ] = v3.y;
  10306. vertexArray[ offset + 8 ] = v3.z;
  10307. vertexArray[ offset + 9 ] = v4.x;
  10308. vertexArray[ offset + 10 ] = v4.y;
  10309. vertexArray[ offset + 11 ] = v4.z;
  10310. offset += 12;
  10311. }
  10312. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  10313. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10314. }
  10315. if ( dirtyMorphTargets ) {
  10316. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  10317. offset_morphTarget = 0;
  10318. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10319. chf = chunk_faces3[ f ];
  10320. face = obj_faces[ chf ];
  10321. // morph positions
  10322. v1 = morphTargets[ vk ].vertices[ face.a ];
  10323. v2 = morphTargets[ vk ].vertices[ face.b ];
  10324. v3 = morphTargets[ vk ].vertices[ face.c ];
  10325. vka = morphTargetsArrays[ vk ];
  10326. vka[ offset_morphTarget ] = v1.x;
  10327. vka[ offset_morphTarget + 1 ] = v1.y;
  10328. vka[ offset_morphTarget + 2 ] = v1.z;
  10329. vka[ offset_morphTarget + 3 ] = v2.x;
  10330. vka[ offset_morphTarget + 4 ] = v2.y;
  10331. vka[ offset_morphTarget + 5 ] = v2.z;
  10332. vka[ offset_morphTarget + 6 ] = v3.x;
  10333. vka[ offset_morphTarget + 7 ] = v3.y;
  10334. vka[ offset_morphTarget + 8 ] = v3.z;
  10335. // morph normals
  10336. if ( material.morphNormals ) {
  10337. if ( needsSmoothNormals ) {
  10338. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10339. n1 = faceVertexNormals.a;
  10340. n2 = faceVertexNormals.b;
  10341. n3 = faceVertexNormals.c;
  10342. } else {
  10343. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10344. n2 = n1;
  10345. n3 = n1;
  10346. }
  10347. nka = morphNormalsArrays[ vk ];
  10348. nka[ offset_morphTarget ] = n1.x;
  10349. nka[ offset_morphTarget + 1 ] = n1.y;
  10350. nka[ offset_morphTarget + 2 ] = n1.z;
  10351. nka[ offset_morphTarget + 3 ] = n2.x;
  10352. nka[ offset_morphTarget + 4 ] = n2.y;
  10353. nka[ offset_morphTarget + 5 ] = n2.z;
  10354. nka[ offset_morphTarget + 6 ] = n3.x;
  10355. nka[ offset_morphTarget + 7 ] = n3.y;
  10356. nka[ offset_morphTarget + 8 ] = n3.z;
  10357. }
  10358. //
  10359. offset_morphTarget += 9;
  10360. }
  10361. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10362. chf = chunk_faces4[ f ];
  10363. face = obj_faces[ chf ];
  10364. // morph positions
  10365. v1 = morphTargets[ vk ].vertices[ face.a ];
  10366. v2 = morphTargets[ vk ].vertices[ face.b ];
  10367. v3 = morphTargets[ vk ].vertices[ face.c ];
  10368. v4 = morphTargets[ vk ].vertices[ face.d ];
  10369. vka = morphTargetsArrays[ vk ];
  10370. vka[ offset_morphTarget ] = v1.x;
  10371. vka[ offset_morphTarget + 1 ] = v1.y;
  10372. vka[ offset_morphTarget + 2 ] = v1.z;
  10373. vka[ offset_morphTarget + 3 ] = v2.x;
  10374. vka[ offset_morphTarget + 4 ] = v2.y;
  10375. vka[ offset_morphTarget + 5 ] = v2.z;
  10376. vka[ offset_morphTarget + 6 ] = v3.x;
  10377. vka[ offset_morphTarget + 7 ] = v3.y;
  10378. vka[ offset_morphTarget + 8 ] = v3.z;
  10379. vka[ offset_morphTarget + 9 ] = v4.x;
  10380. vka[ offset_morphTarget + 10 ] = v4.y;
  10381. vka[ offset_morphTarget + 11 ] = v4.z;
  10382. // morph normals
  10383. if ( material.morphNormals ) {
  10384. if ( needsSmoothNormals ) {
  10385. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  10386. n1 = faceVertexNormals.a;
  10387. n2 = faceVertexNormals.b;
  10388. n3 = faceVertexNormals.c;
  10389. n4 = faceVertexNormals.d;
  10390. } else {
  10391. n1 = morphNormals[ vk ].faceNormals[ chf ];
  10392. n2 = n1;
  10393. n3 = n1;
  10394. n4 = n1;
  10395. }
  10396. nka = morphNormalsArrays[ vk ];
  10397. nka[ offset_morphTarget ] = n1.x;
  10398. nka[ offset_morphTarget + 1 ] = n1.y;
  10399. nka[ offset_morphTarget + 2 ] = n1.z;
  10400. nka[ offset_morphTarget + 3 ] = n2.x;
  10401. nka[ offset_morphTarget + 4 ] = n2.y;
  10402. nka[ offset_morphTarget + 5 ] = n2.z;
  10403. nka[ offset_morphTarget + 6 ] = n3.x;
  10404. nka[ offset_morphTarget + 7 ] = n3.y;
  10405. nka[ offset_morphTarget + 8 ] = n3.z;
  10406. nka[ offset_morphTarget + 9 ] = n4.x;
  10407. nka[ offset_morphTarget + 10 ] = n4.y;
  10408. nka[ offset_morphTarget + 11 ] = n4.z;
  10409. }
  10410. //
  10411. offset_morphTarget += 12;
  10412. }
  10413. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  10414. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  10415. if ( material.morphNormals ) {
  10416. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  10417. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  10418. }
  10419. }
  10420. }
  10421. if ( obj_skinWeights.length ) {
  10422. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10423. face = obj_faces[ chunk_faces3[ f ] ];
  10424. // weights
  10425. sw1 = obj_skinWeights[ face.a ];
  10426. sw2 = obj_skinWeights[ face.b ];
  10427. sw3 = obj_skinWeights[ face.c ];
  10428. skinWeightArray[ offset_skin ] = sw1.x;
  10429. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10430. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10431. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10432. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10433. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10434. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10435. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10436. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10437. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10438. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10439. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10440. // indices
  10441. si1 = obj_skinIndices[ face.a ];
  10442. si2 = obj_skinIndices[ face.b ];
  10443. si3 = obj_skinIndices[ face.c ];
  10444. skinIndexArray[ offset_skin ] = si1.x;
  10445. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10446. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10447. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10448. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10449. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10450. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10451. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10452. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10453. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10454. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10455. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10456. offset_skin += 12;
  10457. }
  10458. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10459. face = obj_faces[ chunk_faces4[ f ] ];
  10460. // weights
  10461. sw1 = obj_skinWeights[ face.a ];
  10462. sw2 = obj_skinWeights[ face.b ];
  10463. sw3 = obj_skinWeights[ face.c ];
  10464. sw4 = obj_skinWeights[ face.d ];
  10465. skinWeightArray[ offset_skin ] = sw1.x;
  10466. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  10467. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  10468. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  10469. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  10470. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  10471. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  10472. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  10473. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  10474. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  10475. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  10476. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  10477. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  10478. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  10479. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  10480. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  10481. // indices
  10482. si1 = obj_skinIndices[ face.a ];
  10483. si2 = obj_skinIndices[ face.b ];
  10484. si3 = obj_skinIndices[ face.c ];
  10485. si4 = obj_skinIndices[ face.d ];
  10486. skinIndexArray[ offset_skin ] = si1.x;
  10487. skinIndexArray[ offset_skin + 1 ] = si1.y;
  10488. skinIndexArray[ offset_skin + 2 ] = si1.z;
  10489. skinIndexArray[ offset_skin + 3 ] = si1.w;
  10490. skinIndexArray[ offset_skin + 4 ] = si2.x;
  10491. skinIndexArray[ offset_skin + 5 ] = si2.y;
  10492. skinIndexArray[ offset_skin + 6 ] = si2.z;
  10493. skinIndexArray[ offset_skin + 7 ] = si2.w;
  10494. skinIndexArray[ offset_skin + 8 ] = si3.x;
  10495. skinIndexArray[ offset_skin + 9 ] = si3.y;
  10496. skinIndexArray[ offset_skin + 10 ] = si3.z;
  10497. skinIndexArray[ offset_skin + 11 ] = si3.w;
  10498. skinIndexArray[ offset_skin + 12 ] = si4.x;
  10499. skinIndexArray[ offset_skin + 13 ] = si4.y;
  10500. skinIndexArray[ offset_skin + 14 ] = si4.z;
  10501. skinIndexArray[ offset_skin + 15 ] = si4.w;
  10502. offset_skin += 16;
  10503. }
  10504. if ( offset_skin > 0 ) {
  10505. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  10506. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  10507. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  10508. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  10509. }
  10510. }
  10511. if ( dirtyColors && vertexColorType ) {
  10512. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10513. face = obj_faces[ chunk_faces3[ f ] ];
  10514. vertexColors = face.vertexColors;
  10515. faceColor = face.color;
  10516. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  10517. c1 = vertexColors[ 0 ];
  10518. c2 = vertexColors[ 1 ];
  10519. c3 = vertexColors[ 2 ];
  10520. } else {
  10521. c1 = faceColor;
  10522. c2 = faceColor;
  10523. c3 = faceColor;
  10524. }
  10525. colorArray[ offset_color ] = c1.r;
  10526. colorArray[ offset_color + 1 ] = c1.g;
  10527. colorArray[ offset_color + 2 ] = c1.b;
  10528. colorArray[ offset_color + 3 ] = c2.r;
  10529. colorArray[ offset_color + 4 ] = c2.g;
  10530. colorArray[ offset_color + 5 ] = c2.b;
  10531. colorArray[ offset_color + 6 ] = c3.r;
  10532. colorArray[ offset_color + 7 ] = c3.g;
  10533. colorArray[ offset_color + 8 ] = c3.b;
  10534. offset_color += 9;
  10535. }
  10536. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10537. face = obj_faces[ chunk_faces4[ f ] ];
  10538. vertexColors = face.vertexColors;
  10539. faceColor = face.color;
  10540. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  10541. c1 = vertexColors[ 0 ];
  10542. c2 = vertexColors[ 1 ];
  10543. c3 = vertexColors[ 2 ];
  10544. c4 = vertexColors[ 3 ];
  10545. } else {
  10546. c1 = faceColor;
  10547. c2 = faceColor;
  10548. c3 = faceColor;
  10549. c4 = faceColor;
  10550. }
  10551. colorArray[ offset_color ] = c1.r;
  10552. colorArray[ offset_color + 1 ] = c1.g;
  10553. colorArray[ offset_color + 2 ] = c1.b;
  10554. colorArray[ offset_color + 3 ] = c2.r;
  10555. colorArray[ offset_color + 4 ] = c2.g;
  10556. colorArray[ offset_color + 5 ] = c2.b;
  10557. colorArray[ offset_color + 6 ] = c3.r;
  10558. colorArray[ offset_color + 7 ] = c3.g;
  10559. colorArray[ offset_color + 8 ] = c3.b;
  10560. colorArray[ offset_color + 9 ] = c4.r;
  10561. colorArray[ offset_color + 10 ] = c4.g;
  10562. colorArray[ offset_color + 11 ] = c4.b;
  10563. offset_color += 12;
  10564. }
  10565. if ( offset_color > 0 ) {
  10566. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  10567. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10568. }
  10569. }
  10570. if ( dirtyTangents && geometry.hasTangents ) {
  10571. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10572. face = obj_faces[ chunk_faces3[ f ] ];
  10573. vertexTangents = face.vertexTangents;
  10574. t1 = vertexTangents[ 0 ];
  10575. t2 = vertexTangents[ 1 ];
  10576. t3 = vertexTangents[ 2 ];
  10577. tangentArray[ offset_tangent ] = t1.x;
  10578. tangentArray[ offset_tangent + 1 ] = t1.y;
  10579. tangentArray[ offset_tangent + 2 ] = t1.z;
  10580. tangentArray[ offset_tangent + 3 ] = t1.w;
  10581. tangentArray[ offset_tangent + 4 ] = t2.x;
  10582. tangentArray[ offset_tangent + 5 ] = t2.y;
  10583. tangentArray[ offset_tangent + 6 ] = t2.z;
  10584. tangentArray[ offset_tangent + 7 ] = t2.w;
  10585. tangentArray[ offset_tangent + 8 ] = t3.x;
  10586. tangentArray[ offset_tangent + 9 ] = t3.y;
  10587. tangentArray[ offset_tangent + 10 ] = t3.z;
  10588. tangentArray[ offset_tangent + 11 ] = t3.w;
  10589. offset_tangent += 12;
  10590. }
  10591. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10592. face = obj_faces[ chunk_faces4[ f ] ];
  10593. vertexTangents = face.vertexTangents;
  10594. t1 = vertexTangents[ 0 ];
  10595. t2 = vertexTangents[ 1 ];
  10596. t3 = vertexTangents[ 2 ];
  10597. t4 = vertexTangents[ 3 ];
  10598. tangentArray[ offset_tangent ] = t1.x;
  10599. tangentArray[ offset_tangent + 1 ] = t1.y;
  10600. tangentArray[ offset_tangent + 2 ] = t1.z;
  10601. tangentArray[ offset_tangent + 3 ] = t1.w;
  10602. tangentArray[ offset_tangent + 4 ] = t2.x;
  10603. tangentArray[ offset_tangent + 5 ] = t2.y;
  10604. tangentArray[ offset_tangent + 6 ] = t2.z;
  10605. tangentArray[ offset_tangent + 7 ] = t2.w;
  10606. tangentArray[ offset_tangent + 8 ] = t3.x;
  10607. tangentArray[ offset_tangent + 9 ] = t3.y;
  10608. tangentArray[ offset_tangent + 10 ] = t3.z;
  10609. tangentArray[ offset_tangent + 11 ] = t3.w;
  10610. tangentArray[ offset_tangent + 12 ] = t4.x;
  10611. tangentArray[ offset_tangent + 13 ] = t4.y;
  10612. tangentArray[ offset_tangent + 14 ] = t4.z;
  10613. tangentArray[ offset_tangent + 15 ] = t4.w;
  10614. offset_tangent += 16;
  10615. }
  10616. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  10617. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  10618. }
  10619. if ( dirtyNormals && normalType ) {
  10620. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10621. face = obj_faces[ chunk_faces3[ f ] ];
  10622. vertexNormals = face.vertexNormals;
  10623. faceNormal = face.normal;
  10624. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  10625. for ( i = 0; i < 3; i ++ ) {
  10626. vn = vertexNormals[ i ];
  10627. normalArray[ offset_normal ] = vn.x;
  10628. normalArray[ offset_normal + 1 ] = vn.y;
  10629. normalArray[ offset_normal + 2 ] = vn.z;
  10630. offset_normal += 3;
  10631. }
  10632. } else {
  10633. for ( i = 0; i < 3; i ++ ) {
  10634. normalArray[ offset_normal ] = faceNormal.x;
  10635. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10636. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10637. offset_normal += 3;
  10638. }
  10639. }
  10640. }
  10641. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10642. face = obj_faces[ chunk_faces4[ f ] ];
  10643. vertexNormals = face.vertexNormals;
  10644. faceNormal = face.normal;
  10645. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  10646. for ( i = 0; i < 4; i ++ ) {
  10647. vn = vertexNormals[ i ];
  10648. normalArray[ offset_normal ] = vn.x;
  10649. normalArray[ offset_normal + 1 ] = vn.y;
  10650. normalArray[ offset_normal + 2 ] = vn.z;
  10651. offset_normal += 3;
  10652. }
  10653. } else {
  10654. for ( i = 0; i < 4; i ++ ) {
  10655. normalArray[ offset_normal ] = faceNormal.x;
  10656. normalArray[ offset_normal + 1 ] = faceNormal.y;
  10657. normalArray[ offset_normal + 2 ] = faceNormal.z;
  10658. offset_normal += 3;
  10659. }
  10660. }
  10661. }
  10662. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  10663. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10664. }
  10665. if ( dirtyUvs && obj_uvs && uvType ) {
  10666. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10667. fi = chunk_faces3[ f ];
  10668. uv = obj_uvs[ fi ];
  10669. if ( uv === undefined ) continue;
  10670. for ( i = 0; i < 3; i ++ ) {
  10671. uvi = uv[ i ];
  10672. uvArray[ offset_uv ] = uvi.u;
  10673. uvArray[ offset_uv + 1 ] = uvi.v;
  10674. offset_uv += 2;
  10675. }
  10676. }
  10677. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10678. fi = chunk_faces4[ f ];
  10679. uv = obj_uvs[ fi ];
  10680. if ( uv === undefined ) continue;
  10681. for ( i = 0; i < 4; i ++ ) {
  10682. uvi = uv[ i ];
  10683. uvArray[ offset_uv ] = uvi.u;
  10684. uvArray[ offset_uv + 1 ] = uvi.v;
  10685. offset_uv += 2;
  10686. }
  10687. }
  10688. if ( offset_uv > 0 ) {
  10689. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  10690. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  10691. }
  10692. }
  10693. if ( dirtyUvs && obj_uvs2 && uvType ) {
  10694. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10695. fi = chunk_faces3[ f ];
  10696. uv2 = obj_uvs2[ fi ];
  10697. if ( uv2 === undefined ) continue;
  10698. for ( i = 0; i < 3; i ++ ) {
  10699. uv2i = uv2[ i ];
  10700. uv2Array[ offset_uv2 ] = uv2i.u;
  10701. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10702. offset_uv2 += 2;
  10703. }
  10704. }
  10705. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10706. fi = chunk_faces4[ f ];
  10707. uv2 = obj_uvs2[ fi ];
  10708. if ( uv2 === undefined ) continue;
  10709. for ( i = 0; i < 4; i ++ ) {
  10710. uv2i = uv2[ i ];
  10711. uv2Array[ offset_uv2 ] = uv2i.u;
  10712. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  10713. offset_uv2 += 2;
  10714. }
  10715. }
  10716. if ( offset_uv2 > 0 ) {
  10717. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  10718. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  10719. }
  10720. }
  10721. if ( dirtyElements ) {
  10722. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10723. faceArray[ offset_face ] = vertexIndex;
  10724. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10725. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  10726. offset_face += 3;
  10727. lineArray[ offset_line ] = vertexIndex;
  10728. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10729. lineArray[ offset_line + 2 ] = vertexIndex;
  10730. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  10731. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10732. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10733. offset_line += 6;
  10734. vertexIndex += 3;
  10735. }
  10736. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10737. faceArray[ offset_face ] = vertexIndex;
  10738. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  10739. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  10740. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  10741. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  10742. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  10743. offset_face += 6;
  10744. lineArray[ offset_line ] = vertexIndex;
  10745. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  10746. lineArray[ offset_line + 2 ] = vertexIndex;
  10747. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  10748. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  10749. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  10750. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  10751. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  10752. offset_line += 8;
  10753. vertexIndex += 4;
  10754. }
  10755. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  10756. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  10757. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  10758. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  10759. }
  10760. if ( customAttributes ) {
  10761. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10762. customAttribute = customAttributes[ i ];
  10763. if ( ! customAttribute.__original.needsUpdate ) continue;
  10764. offset_custom = 0;
  10765. offset_customSrc = 0;
  10766. if ( customAttribute.size === 1 ) {
  10767. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10768. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10769. face = obj_faces[ chunk_faces3[ f ] ];
  10770. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10771. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10772. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10773. offset_custom += 3;
  10774. }
  10775. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10776. face = obj_faces[ chunk_faces4[ f ] ];
  10777. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  10778. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  10779. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  10780. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  10781. offset_custom += 4;
  10782. }
  10783. } else if ( customAttribute.boundTo === "faces" ) {
  10784. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10785. value = customAttribute.value[ chunk_faces3[ f ] ];
  10786. customAttribute.array[ offset_custom ] = value;
  10787. customAttribute.array[ offset_custom + 1 ] = value;
  10788. customAttribute.array[ offset_custom + 2 ] = value;
  10789. offset_custom += 3;
  10790. }
  10791. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10792. value = customAttribute.value[ chunk_faces4[ f ] ];
  10793. customAttribute.array[ offset_custom ] = value;
  10794. customAttribute.array[ offset_custom + 1 ] = value;
  10795. customAttribute.array[ offset_custom + 2 ] = value;
  10796. customAttribute.array[ offset_custom + 3 ] = value;
  10797. offset_custom += 4;
  10798. }
  10799. }
  10800. } else if ( customAttribute.size === 2 ) {
  10801. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10802. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10803. face = obj_faces[ chunk_faces3[ f ] ];
  10804. v1 = customAttribute.value[ face.a ];
  10805. v2 = customAttribute.value[ face.b ];
  10806. v3 = customAttribute.value[ face.c ];
  10807. customAttribute.array[ offset_custom ] = v1.x;
  10808. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10809. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10810. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10811. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10812. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10813. offset_custom += 6;
  10814. }
  10815. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10816. face = obj_faces[ chunk_faces4[ f ] ];
  10817. v1 = customAttribute.value[ face.a ];
  10818. v2 = customAttribute.value[ face.b ];
  10819. v3 = customAttribute.value[ face.c ];
  10820. v4 = customAttribute.value[ face.d ];
  10821. customAttribute.array[ offset_custom ] = v1.x;
  10822. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10823. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10824. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10825. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10826. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10827. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10828. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10829. offset_custom += 8;
  10830. }
  10831. } else if ( customAttribute.boundTo === "faces" ) {
  10832. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10833. value = customAttribute.value[ chunk_faces3[ f ] ];
  10834. v1 = value;
  10835. v2 = value;
  10836. v3 = value;
  10837. customAttribute.array[ offset_custom ] = v1.x;
  10838. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10839. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10840. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10841. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10842. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10843. offset_custom += 6;
  10844. }
  10845. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10846. value = customAttribute.value[ chunk_faces4[ f ] ];
  10847. v1 = value;
  10848. v2 = value;
  10849. v3 = value;
  10850. v4 = value;
  10851. customAttribute.array[ offset_custom ] = v1.x;
  10852. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10853. customAttribute.array[ offset_custom + 2 ] = v2.x;
  10854. customAttribute.array[ offset_custom + 3 ] = v2.y;
  10855. customAttribute.array[ offset_custom + 4 ] = v3.x;
  10856. customAttribute.array[ offset_custom + 5 ] = v3.y;
  10857. customAttribute.array[ offset_custom + 6 ] = v4.x;
  10858. customAttribute.array[ offset_custom + 7 ] = v4.y;
  10859. offset_custom += 8;
  10860. }
  10861. }
  10862. } else if ( customAttribute.size === 3 ) {
  10863. var pp;
  10864. if ( customAttribute.type === "c" ) {
  10865. pp = [ "r", "g", "b" ];
  10866. } else {
  10867. pp = [ "x", "y", "z" ];
  10868. }
  10869. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10870. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10871. face = obj_faces[ chunk_faces3[ f ] ];
  10872. v1 = customAttribute.value[ face.a ];
  10873. v2 = customAttribute.value[ face.b ];
  10874. v3 = customAttribute.value[ face.c ];
  10875. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10876. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10877. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10878. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10879. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10880. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10881. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10882. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10883. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10884. offset_custom += 9;
  10885. }
  10886. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10887. face = obj_faces[ chunk_faces4[ f ] ];
  10888. v1 = customAttribute.value[ face.a ];
  10889. v2 = customAttribute.value[ face.b ];
  10890. v3 = customAttribute.value[ face.c ];
  10891. v4 = customAttribute.value[ face.d ];
  10892. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10893. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10894. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10895. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10896. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10897. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10898. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10899. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10900. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10901. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10902. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10903. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10904. offset_custom += 12;
  10905. }
  10906. } else if ( customAttribute.boundTo === "faces" ) {
  10907. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10908. value = customAttribute.value[ chunk_faces3[ f ] ];
  10909. v1 = value;
  10910. v2 = value;
  10911. v3 = value;
  10912. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10913. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10914. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10915. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10916. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10917. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10918. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10919. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10920. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10921. offset_custom += 9;
  10922. }
  10923. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10924. value = customAttribute.value[ chunk_faces4[ f ] ];
  10925. v1 = value;
  10926. v2 = value;
  10927. v3 = value;
  10928. v4 = value;
  10929. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10930. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10931. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10932. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10933. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10934. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10935. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10936. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10937. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10938. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10939. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10940. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10941. offset_custom += 12;
  10942. }
  10943. } else if ( customAttribute.boundTo === "faceVertices" ) {
  10944. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10945. value = customAttribute.value[ chunk_faces3[ f ] ];
  10946. v1 = value[ 0 ];
  10947. v2 = value[ 1 ];
  10948. v3 = value[ 2 ];
  10949. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10950. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10951. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10952. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10953. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10954. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10955. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10956. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10957. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10958. offset_custom += 9;
  10959. }
  10960. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  10961. value = customAttribute.value[ chunk_faces4[ f ] ];
  10962. v1 = value[ 0 ];
  10963. v2 = value[ 1 ];
  10964. v3 = value[ 2 ];
  10965. v4 = value[ 3 ];
  10966. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  10967. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  10968. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  10969. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  10970. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  10971. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  10972. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  10973. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  10974. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  10975. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  10976. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  10977. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  10978. offset_custom += 12;
  10979. }
  10980. }
  10981. } else if ( customAttribute.size === 4 ) {
  10982. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  10983. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  10984. face = obj_faces[ chunk_faces3[ f ] ];
  10985. v1 = customAttribute.value[ face.a ];
  10986. v2 = customAttribute.value[ face.b ];
  10987. v3 = customAttribute.value[ face.c ];
  10988. customAttribute.array[ offset_custom ] = v1.x;
  10989. customAttribute.array[ offset_custom + 1 ] = v1.y;
  10990. customAttribute.array[ offset_custom + 2 ] = v1.z;
  10991. customAttribute.array[ offset_custom + 3 ] = v1.w;
  10992. customAttribute.array[ offset_custom + 4 ] = v2.x;
  10993. customAttribute.array[ offset_custom + 5 ] = v2.y;
  10994. customAttribute.array[ offset_custom + 6 ] = v2.z;
  10995. customAttribute.array[ offset_custom + 7 ] = v2.w;
  10996. customAttribute.array[ offset_custom + 8 ] = v3.x;
  10997. customAttribute.array[ offset_custom + 9 ] = v3.y;
  10998. customAttribute.array[ offset_custom + 10 ] = v3.z;
  10999. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11000. offset_custom += 12;
  11001. }
  11002. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11003. face = obj_faces[ chunk_faces4[ f ] ];
  11004. v1 = customAttribute.value[ face.a ];
  11005. v2 = customAttribute.value[ face.b ];
  11006. v3 = customAttribute.value[ face.c ];
  11007. v4 = customAttribute.value[ face.d ];
  11008. customAttribute.array[ offset_custom ] = v1.x;
  11009. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11010. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11011. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11012. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11013. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11014. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11015. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11016. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11017. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11018. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11019. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11020. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11021. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11022. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11023. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11024. offset_custom += 16;
  11025. }
  11026. } else if ( customAttribute.boundTo === "faces" ) {
  11027. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11028. value = customAttribute.value[ chunk_faces3[ f ] ];
  11029. v1 = value;
  11030. v2 = value;
  11031. v3 = value;
  11032. customAttribute.array[ offset_custom ] = v1.x;
  11033. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11034. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11035. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11036. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11037. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11038. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11039. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11040. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11041. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11042. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11043. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11044. offset_custom += 12;
  11045. }
  11046. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11047. value = customAttribute.value[ chunk_faces4[ f ] ];
  11048. v1 = value;
  11049. v2 = value;
  11050. v3 = value;
  11051. v4 = value;
  11052. customAttribute.array[ offset_custom ] = v1.x;
  11053. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11054. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11055. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11056. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11057. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11058. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11059. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11060. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11061. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11062. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11063. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11064. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11065. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11066. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11067. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11068. offset_custom += 16;
  11069. }
  11070. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11071. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11072. value = customAttribute.value[ chunk_faces3[ f ] ];
  11073. v1 = value[ 0 ];
  11074. v2 = value[ 1 ];
  11075. v3 = value[ 2 ];
  11076. customAttribute.array[ offset_custom ] = v1.x;
  11077. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11078. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11079. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11080. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11081. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11082. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11083. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11084. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11085. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11086. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11087. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11088. offset_custom += 12;
  11089. }
  11090. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11091. value = customAttribute.value[ chunk_faces4[ f ] ];
  11092. v1 = value[ 0 ];
  11093. v2 = value[ 1 ];
  11094. v3 = value[ 2 ];
  11095. v4 = value[ 3 ];
  11096. customAttribute.array[ offset_custom ] = v1.x;
  11097. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11098. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11099. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11100. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11101. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11102. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11103. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11104. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11105. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11106. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11107. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11108. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11109. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11110. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11111. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11112. offset_custom += 16;
  11113. }
  11114. }
  11115. }
  11116. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11117. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11118. }
  11119. }
  11120. if ( dispose ) {
  11121. delete geometryGroup.__inittedArrays;
  11122. delete geometryGroup.__colorArray;
  11123. delete geometryGroup.__normalArray;
  11124. delete geometryGroup.__tangentArray;
  11125. delete geometryGroup.__uvArray;
  11126. delete geometryGroup.__uv2Array;
  11127. delete geometryGroup.__faceArray;
  11128. delete geometryGroup.__vertexArray;
  11129. delete geometryGroup.__lineArray;
  11130. delete geometryGroup.__skinIndexArray;
  11131. delete geometryGroup.__skinWeightArray;
  11132. }
  11133. };
  11134. function setDirectBuffers ( geometry, hint, dispose ) {
  11135. var attributes = geometry.attributes;
  11136. var index = attributes[ "index" ];
  11137. var position = attributes[ "position" ];
  11138. var normal = attributes[ "normal" ];
  11139. var uv = attributes[ "uv" ];
  11140. var color = attributes[ "color" ];
  11141. var tangent = attributes[ "tangent" ];
  11142. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11143. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11144. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11145. }
  11146. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11147. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11148. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11149. }
  11150. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11151. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11152. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11153. }
  11154. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11155. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11156. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11157. }
  11158. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11159. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11160. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11161. }
  11162. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11163. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11164. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11165. }
  11166. if ( dispose ) {
  11167. for ( var i in geometry.attributes ) {
  11168. delete geometry.attributes[ i ].array;
  11169. }
  11170. }
  11171. };
  11172. // Buffer rendering
  11173. this.renderBufferImmediate = function ( object, program, material ) {
  11174. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11175. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11176. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11177. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11178. if ( object.hasPositions ) {
  11179. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11180. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11181. _gl.enableVertexAttribArray( program.attributes.position );
  11182. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11183. }
  11184. if ( object.hasNormals ) {
  11185. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  11186. if ( material.shading === THREE.FlatShading ) {
  11187. var nx, ny, nz,
  11188. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  11189. normalArray,
  11190. i, il = object.count * 3;
  11191. for( i = 0; i < il; i += 9 ) {
  11192. normalArray = object.normalArray;
  11193. nax = normalArray[ i ];
  11194. nay = normalArray[ i + 1 ];
  11195. naz = normalArray[ i + 2 ];
  11196. nbx = normalArray[ i + 3 ];
  11197. nby = normalArray[ i + 4 ];
  11198. nbz = normalArray[ i + 5 ];
  11199. ncx = normalArray[ i + 6 ];
  11200. ncy = normalArray[ i + 7 ];
  11201. ncz = normalArray[ i + 8 ];
  11202. nx = ( nax + nbx + ncx ) / 3;
  11203. ny = ( nay + nby + ncy ) / 3;
  11204. nz = ( naz + nbz + ncz ) / 3;
  11205. normalArray[ i ] = nx;
  11206. normalArray[ i + 1 ] = ny;
  11207. normalArray[ i + 2 ] = nz;
  11208. normalArray[ i + 3 ] = nx;
  11209. normalArray[ i + 4 ] = ny;
  11210. normalArray[ i + 5 ] = nz;
  11211. normalArray[ i + 6 ] = nx;
  11212. normalArray[ i + 7 ] = ny;
  11213. normalArray[ i + 8 ] = nz;
  11214. }
  11215. }
  11216. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  11217. _gl.enableVertexAttribArray( program.attributes.normal );
  11218. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11219. }
  11220. if ( object.hasUvs && material.map ) {
  11221. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  11222. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  11223. _gl.enableVertexAttribArray( program.attributes.uv );
  11224. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11225. }
  11226. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  11227. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  11228. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  11229. _gl.enableVertexAttribArray( program.attributes.color );
  11230. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11231. }
  11232. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  11233. object.count = 0;
  11234. };
  11235. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  11236. if ( material.visible === false ) return;
  11237. var program, attributes, linewidth, primitives, a, attribute;
  11238. program = setProgram( camera, lights, fog, material, object );
  11239. attributes = program.attributes;
  11240. var updateBuffers = false,
  11241. wireframeBit = material.wireframe ? 1 : 0,
  11242. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11243. if ( geometryHash !== _currentGeometryGroupHash ) {
  11244. _currentGeometryGroupHash = geometryHash;
  11245. updateBuffers = true;
  11246. }
  11247. // render mesh
  11248. if ( object instanceof THREE.Mesh ) {
  11249. var offsets = geometry.offsets;
  11250. // if there is more than 1 chunk
  11251. // must set attribute pointers to use new offsets for each chunk
  11252. // even if geometry and materials didn't change
  11253. if ( offsets.length > 1 ) updateBuffers = true;
  11254. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  11255. var startIndex = offsets[ i ].index;
  11256. if ( updateBuffers ) {
  11257. // vertices
  11258. var position = geometry.attributes[ "position" ];
  11259. var positionSize = position.itemSize;
  11260. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11261. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  11262. // normals
  11263. var normal = geometry.attributes[ "normal" ];
  11264. if ( attributes.normal >= 0 && normal ) {
  11265. var normalSize = normal.itemSize;
  11266. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11267. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  11268. }
  11269. // uvs
  11270. var uv = geometry.attributes[ "uv" ];
  11271. if ( attributes.uv >= 0 && uv ) {
  11272. if ( uv.buffer ) {
  11273. var uvSize = uv.itemSize;
  11274. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11275. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  11276. _gl.enableVertexAttribArray( attributes.uv );
  11277. } else {
  11278. _gl.disableVertexAttribArray( attributes.uv );
  11279. }
  11280. }
  11281. // colors
  11282. var color = geometry.attributes[ "color" ];
  11283. if ( attributes.color >= 0 && color ) {
  11284. var colorSize = color.itemSize;
  11285. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11286. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  11287. }
  11288. // tangents
  11289. var tangent = geometry.attributes[ "tangent" ];
  11290. if ( attributes.tangent >= 0 && tangent ) {
  11291. var tangentSize = tangent.itemSize;
  11292. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11293. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  11294. }
  11295. // indices
  11296. var index = geometry.attributes[ "index" ];
  11297. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11298. }
  11299. // render indexed triangles
  11300. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  11301. _this.info.render.calls ++;
  11302. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  11303. _this.info.render.faces += offsets[ i ].count / 3;
  11304. }
  11305. // render particles
  11306. } else if ( object instanceof THREE.ParticleSystem ) {
  11307. if ( updateBuffers ) {
  11308. // vertices
  11309. var position = geometry.attributes[ "position" ];
  11310. var positionSize = position.itemSize;
  11311. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11312. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  11313. // colors
  11314. var color = geometry.attributes[ "color" ];
  11315. if ( attributes.color >= 0 && color ) {
  11316. var colorSize = color.itemSize;
  11317. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11318. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  11319. }
  11320. // render particles
  11321. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  11322. _this.info.render.calls ++;
  11323. _this.info.render.points += position.numItems / 3;
  11324. }
  11325. }
  11326. };
  11327. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  11328. if ( material.visible === false ) return;
  11329. var program, attributes, linewidth, primitives, a, attribute, i, il;
  11330. program = setProgram( camera, lights, fog, material, object );
  11331. attributes = program.attributes;
  11332. var updateBuffers = false,
  11333. wireframeBit = material.wireframe ? 1 : 0,
  11334. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  11335. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  11336. _currentGeometryGroupHash = geometryGroupHash;
  11337. updateBuffers = true;
  11338. }
  11339. // vertices
  11340. if ( !material.morphTargets && attributes.position >= 0 ) {
  11341. if ( updateBuffers ) {
  11342. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11343. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11344. }
  11345. } else {
  11346. if ( object.morphTargetBase ) {
  11347. setupMorphTargets( material, geometryGroup, object );
  11348. }
  11349. }
  11350. if ( updateBuffers ) {
  11351. // custom attributes
  11352. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  11353. if ( geometryGroup.__webglCustomAttributesList ) {
  11354. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  11355. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  11356. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  11357. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  11358. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  11359. }
  11360. }
  11361. }
  11362. // colors
  11363. if ( attributes.color >= 0 ) {
  11364. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11365. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  11366. }
  11367. // normals
  11368. if ( attributes.normal >= 0 ) {
  11369. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11370. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  11371. }
  11372. // tangents
  11373. if ( attributes.tangent >= 0 ) {
  11374. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11375. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  11376. }
  11377. // uvs
  11378. if ( attributes.uv >= 0 ) {
  11379. if ( geometryGroup.__webglUVBuffer ) {
  11380. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11381. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  11382. _gl.enableVertexAttribArray( attributes.uv );
  11383. } else {
  11384. _gl.disableVertexAttribArray( attributes.uv );
  11385. }
  11386. }
  11387. if ( attributes.uv2 >= 0 ) {
  11388. if ( geometryGroup.__webglUV2Buffer ) {
  11389. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11390. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  11391. _gl.enableVertexAttribArray( attributes.uv2 );
  11392. } else {
  11393. _gl.disableVertexAttribArray( attributes.uv2 );
  11394. }
  11395. }
  11396. if ( material.skinning &&
  11397. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  11398. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11399. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  11400. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11401. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  11402. }
  11403. }
  11404. // render mesh
  11405. if ( object instanceof THREE.Mesh ) {
  11406. // wireframe
  11407. if ( material.wireframe ) {
  11408. setLineWidth( material.wireframeLinewidth );
  11409. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11410. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  11411. // triangles
  11412. } else {
  11413. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11414. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  11415. }
  11416. _this.info.render.calls ++;
  11417. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  11418. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  11419. // render lines
  11420. } else if ( object instanceof THREE.Line ) {
  11421. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  11422. setLineWidth( material.linewidth );
  11423. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  11424. _this.info.render.calls ++;
  11425. // render particles
  11426. } else if ( object instanceof THREE.ParticleSystem ) {
  11427. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  11428. _this.info.render.calls ++;
  11429. _this.info.render.points += geometryGroup.__webglParticleCount;
  11430. // render ribbon
  11431. } else if ( object instanceof THREE.Ribbon ) {
  11432. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  11433. _this.info.render.calls ++;
  11434. }
  11435. };
  11436. function setupMorphTargets ( material, geometryGroup, object ) {
  11437. // set base
  11438. var attributes = material.program.attributes;
  11439. if ( object.morphTargetBase !== -1 ) {
  11440. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  11441. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11442. } else if ( attributes.position >= 0 ) {
  11443. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11444. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  11445. }
  11446. if ( object.morphTargetForcedOrder.length ) {
  11447. // set forced order
  11448. var m = 0;
  11449. var order = object.morphTargetForcedOrder;
  11450. var influences = object.morphTargetInfluences;
  11451. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  11452. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  11453. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11454. if ( material.morphNormals ) {
  11455. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  11456. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11457. }
  11458. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  11459. m ++;
  11460. }
  11461. } else {
  11462. // find the most influencing
  11463. var influence, activeInfluenceIndices = [];
  11464. var influences = object.morphTargetInfluences;
  11465. var i, il = influences.length;
  11466. for ( i = 0; i < il; i ++ ) {
  11467. influence = influences[ i ];
  11468. if ( influence > 0 ) {
  11469. activeInfluenceIndices.push( [ i, influence ] );
  11470. }
  11471. }
  11472. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  11473. activeInfluenceIndices.sort( numericalSort );
  11474. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  11475. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  11476. activeInfluenceIndices.sort( numericalSort );
  11477. } else if ( activeInfluenceIndices.length === 0 ) {
  11478. activeInfluenceIndices.push( [ 0, 0 ] );
  11479. };
  11480. var influenceIndex, m = 0;
  11481. while ( m < material.numSupportedMorphTargets ) {
  11482. if ( activeInfluenceIndices[ m ] ) {
  11483. influenceIndex = activeInfluenceIndices[ m ][ 0 ];
  11484. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  11485. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11486. if ( material.morphNormals ) {
  11487. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  11488. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11489. }
  11490. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  11491. } else {
  11492. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11493. if ( material.morphNormals ) {
  11494. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  11495. }
  11496. object.__webglMorphTargetInfluences[ m ] = 0;
  11497. }
  11498. m ++;
  11499. }
  11500. }
  11501. // load updated influences uniform
  11502. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  11503. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  11504. }
  11505. };
  11506. // Sorting
  11507. function painterSort ( a, b ) {
  11508. return b.z - a.z;
  11509. };
  11510. function numericalSort ( a, b ) {
  11511. return b[ 1 ] - a[ 1 ];
  11512. };
  11513. // Rendering
  11514. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11515. if ( camera instanceof THREE.Camera === false ) {
  11516. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  11517. return;
  11518. }
  11519. var i, il,
  11520. webglObject, object,
  11521. renderList,
  11522. lights = scene.__lights,
  11523. fog = scene.fog;
  11524. // reset caching for this frame
  11525. _currentMaterialId = -1;
  11526. _lightsNeedUpdate = true;
  11527. // update scene graph
  11528. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  11529. // update camera matrices and frustum
  11530. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  11531. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11532. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11533. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11534. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11535. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11536. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11537. _frustum.setFromMatrix( _projScreenMatrix );
  11538. // update WebGL objects
  11539. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  11540. // custom render plugins (pre pass)
  11541. renderPlugins( this.renderPluginsPre, scene, camera );
  11542. //
  11543. _this.info.render.calls = 0;
  11544. _this.info.render.vertices = 0;
  11545. _this.info.render.faces = 0;
  11546. _this.info.render.points = 0;
  11547. this.setRenderTarget( renderTarget );
  11548. if ( this.autoClear || forceClear ) {
  11549. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  11550. }
  11551. // set matrices for regular objects (frustum culled)
  11552. renderList = scene.__webglObjects;
  11553. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11554. webglObject = renderList[ i ];
  11555. object = webglObject.object;
  11556. webglObject.render = false;
  11557. if ( object.visible ) {
  11558. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11559. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11560. setupMatrices( object, camera );
  11561. unrollBufferMaterial( webglObject );
  11562. webglObject.render = true;
  11563. if ( this.sortObjects === true ) {
  11564. if ( object.renderDepth !== null ) {
  11565. webglObject.z = object.renderDepth;
  11566. } else {
  11567. _vector3.copy( object.matrixWorld.getPosition() );
  11568. _projScreenMatrix.multiplyVector3( _vector3 );
  11569. webglObject.z = _vector3.z;
  11570. }
  11571. }
  11572. }
  11573. }
  11574. }
  11575. if ( this.sortObjects ) {
  11576. renderList.sort( painterSort );
  11577. }
  11578. // set matrices for immediate objects
  11579. renderList = scene.__webglObjectsImmediate;
  11580. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  11581. webglObject = renderList[ i ];
  11582. object = webglObject.object;
  11583. if ( object.visible ) {
  11584. /*
  11585. if ( object.matrixAutoUpdate ) {
  11586. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  11587. }
  11588. */
  11589. setupMatrices( object, camera );
  11590. unrollImmediateBufferMaterial( webglObject );
  11591. }
  11592. }
  11593. if ( scene.overrideMaterial ) {
  11594. var material = scene.overrideMaterial;
  11595. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11596. this.setDepthTest( material.depthTest );
  11597. this.setDepthWrite( material.depthWrite );
  11598. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11599. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  11600. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  11601. } else {
  11602. // opaque pass (front-to-back order)
  11603. this.setBlending( THREE.NormalBlending );
  11604. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  11605. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  11606. // transparent pass (back-to-front order)
  11607. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  11608. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  11609. }
  11610. // custom render plugins (post pass)
  11611. renderPlugins( this.renderPluginsPost, scene, camera );
  11612. // Generate mipmap if we're using any kind of mipmap filtering
  11613. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  11614. updateRenderTargetMipmap( renderTarget );
  11615. }
  11616. // Ensure depth buffer writing is enabled so it can be cleared on next render
  11617. this.setDepthTest( true );
  11618. this.setDepthWrite( true );
  11619. // _gl.finish();
  11620. };
  11621. function renderPlugins( plugins, scene, camera ) {
  11622. if ( ! plugins.length ) return;
  11623. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  11624. // reset state for plugin (to start from clean slate)
  11625. _currentProgram = null;
  11626. _currentCamera = null;
  11627. _oldBlending = -1;
  11628. _oldDepthTest = -1;
  11629. _oldDepthWrite = -1;
  11630. _oldDoubleSided = -1;
  11631. _oldFlipSided = -1;
  11632. _currentGeometryGroupHash = -1;
  11633. _currentMaterialId = -1;
  11634. _lightsNeedUpdate = true;
  11635. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  11636. // reset state after plugin (anything could have changed)
  11637. _currentProgram = null;
  11638. _currentCamera = null;
  11639. _oldBlending = -1;
  11640. _oldDepthTest = -1;
  11641. _oldDepthWrite = -1;
  11642. _oldDoubleSided = -1;
  11643. _oldFlipSided = -1;
  11644. _currentGeometryGroupHash = -1;
  11645. _currentMaterialId = -1;
  11646. _lightsNeedUpdate = true;
  11647. }
  11648. };
  11649. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11650. var webglObject, object, buffer, material, start, end, delta;
  11651. if ( reverse ) {
  11652. start = renderList.length - 1;
  11653. end = -1;
  11654. delta = -1;
  11655. } else {
  11656. start = 0;
  11657. end = renderList.length;
  11658. delta = 1;
  11659. }
  11660. for ( var i = start; i !== end; i += delta ) {
  11661. webglObject = renderList[ i ];
  11662. if ( webglObject.render ) {
  11663. object = webglObject.object;
  11664. buffer = webglObject.buffer;
  11665. if ( overrideMaterial ) {
  11666. material = overrideMaterial;
  11667. } else {
  11668. material = webglObject[ materialType ];
  11669. if ( ! material ) continue;
  11670. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11671. _this.setDepthTest( material.depthTest );
  11672. _this.setDepthWrite( material.depthWrite );
  11673. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11674. }
  11675. _this.setMaterialFaces( material );
  11676. if ( buffer instanceof THREE.BufferGeometry ) {
  11677. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  11678. } else {
  11679. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  11680. }
  11681. }
  11682. }
  11683. };
  11684. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  11685. var webglObject, object, material, program;
  11686. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  11687. webglObject = renderList[ i ];
  11688. object = webglObject.object;
  11689. if ( object.visible ) {
  11690. if ( overrideMaterial ) {
  11691. material = overrideMaterial;
  11692. } else {
  11693. material = webglObject[ materialType ];
  11694. if ( ! material ) continue;
  11695. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  11696. _this.setDepthTest( material.depthTest );
  11697. _this.setDepthWrite( material.depthWrite );
  11698. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  11699. }
  11700. _this.renderImmediateObject( camera, lights, fog, material, object );
  11701. }
  11702. }
  11703. };
  11704. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  11705. var program = setProgram( camera, lights, fog, material, object );
  11706. _currentGeometryGroupHash = -1;
  11707. _this.setMaterialFaces( material );
  11708. if ( object.immediateRenderCallback ) {
  11709. object.immediateRenderCallback( program, _gl, _frustum );
  11710. } else {
  11711. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  11712. }
  11713. };
  11714. function unrollImmediateBufferMaterial ( globject ) {
  11715. var object = globject.object,
  11716. material = object.material;
  11717. if ( material.transparent ) {
  11718. globject.transparent = material;
  11719. globject.opaque = null;
  11720. } else {
  11721. globject.opaque = material;
  11722. globject.transparent = null;
  11723. }
  11724. };
  11725. function unrollBufferMaterial ( globject ) {
  11726. var object = globject.object,
  11727. buffer = globject.buffer,
  11728. material, materialIndex, meshMaterial;
  11729. meshMaterial = object.material;
  11730. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  11731. materialIndex = buffer.materialIndex;
  11732. if ( materialIndex >= 0 ) {
  11733. material = object.geometry.materials[ materialIndex ];
  11734. if ( material.transparent ) {
  11735. globject.transparent = material;
  11736. globject.opaque = null;
  11737. } else {
  11738. globject.opaque = material;
  11739. globject.transparent = null;
  11740. }
  11741. }
  11742. } else {
  11743. material = meshMaterial;
  11744. if ( material ) {
  11745. if ( material.transparent ) {
  11746. globject.transparent = material;
  11747. globject.opaque = null;
  11748. } else {
  11749. globject.opaque = material;
  11750. globject.transparent = null;
  11751. }
  11752. }
  11753. }
  11754. };
  11755. // Geometry splitting
  11756. function sortFacesByMaterial ( geometry ) {
  11757. var f, fl, face, materialIndex, vertices,
  11758. materialHash, groupHash,
  11759. hash_map = {};
  11760. var numMorphTargets = geometry.morphTargets.length;
  11761. var numMorphNormals = geometry.morphNormals.length;
  11762. geometry.geometryGroups = {};
  11763. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  11764. face = geometry.faces[ f ];
  11765. materialIndex = face.materialIndex;
  11766. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  11767. if ( hash_map[ materialHash ] === undefined ) {
  11768. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  11769. }
  11770. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11771. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11772. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11773. }
  11774. vertices = face instanceof THREE.Face3 ? 3 : 4;
  11775. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  11776. hash_map[ materialHash ].counter += 1;
  11777. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  11778. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  11779. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  11780. }
  11781. }
  11782. if ( face instanceof THREE.Face3 ) {
  11783. geometry.geometryGroups[ groupHash ].faces3.push( f );
  11784. } else {
  11785. geometry.geometryGroups[ groupHash ].faces4.push( f );
  11786. }
  11787. geometry.geometryGroups[ groupHash ].vertices += vertices;
  11788. }
  11789. geometry.geometryGroupsList = [];
  11790. for ( var g in geometry.geometryGroups ) {
  11791. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  11792. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  11793. }
  11794. };
  11795. // Objects refresh
  11796. this.initWebGLObjects = function ( scene ) {
  11797. if ( !scene.__webglObjects ) {
  11798. scene.__webglObjects = [];
  11799. scene.__webglObjectsImmediate = [];
  11800. scene.__webglSprites = [];
  11801. scene.__webglFlares = [];
  11802. }
  11803. while ( scene.__objectsAdded.length ) {
  11804. addObject( scene.__objectsAdded[ 0 ], scene );
  11805. scene.__objectsAdded.splice( 0, 1 );
  11806. }
  11807. while ( scene.__objectsRemoved.length ) {
  11808. removeObject( scene.__objectsRemoved[ 0 ], scene );
  11809. scene.__objectsRemoved.splice( 0, 1 );
  11810. }
  11811. // update must be called after objects adding / removal
  11812. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  11813. updateObject( scene.__webglObjects[ o ].object );
  11814. }
  11815. };
  11816. // Objects adding
  11817. function addObject ( object, scene ) {
  11818. var g, geometry, geometryGroup;
  11819. if ( ! object.__webglInit ) {
  11820. object.__webglInit = true;
  11821. object._modelViewMatrix = new THREE.Matrix4();
  11822. object._normalMatrix = new THREE.Matrix3();
  11823. if ( object instanceof THREE.Mesh ) {
  11824. geometry = object.geometry;
  11825. if ( geometry instanceof THREE.Geometry ) {
  11826. if ( geometry.geometryGroups === undefined ) {
  11827. sortFacesByMaterial( geometry );
  11828. }
  11829. // create separate VBOs per geometry chunk
  11830. for ( g in geometry.geometryGroups ) {
  11831. geometryGroup = geometry.geometryGroups[ g ];
  11832. // initialise VBO on the first access
  11833. if ( ! geometryGroup.__webglVertexBuffer ) {
  11834. createMeshBuffers( geometryGroup );
  11835. initMeshBuffers( geometryGroup, object );
  11836. geometry.verticesNeedUpdate = true;
  11837. geometry.morphTargetsNeedUpdate = true;
  11838. geometry.elementsNeedUpdate = true;
  11839. geometry.uvsNeedUpdate = true;
  11840. geometry.normalsNeedUpdate = true;
  11841. geometry.tangentsNeedUpdate = true;
  11842. geometry.colorsNeedUpdate = true;
  11843. }
  11844. }
  11845. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11846. initDirectBuffers( geometry );
  11847. }
  11848. } else if ( object instanceof THREE.Ribbon ) {
  11849. geometry = object.geometry;
  11850. if( ! geometry.__webglVertexBuffer ) {
  11851. createRibbonBuffers( geometry );
  11852. initRibbonBuffers( geometry );
  11853. geometry.verticesNeedUpdate = true;
  11854. geometry.colorsNeedUpdate = true;
  11855. }
  11856. } else if ( object instanceof THREE.Line ) {
  11857. geometry = object.geometry;
  11858. if( ! geometry.__webglVertexBuffer ) {
  11859. createLineBuffers( geometry );
  11860. initLineBuffers( geometry, object );
  11861. geometry.verticesNeedUpdate = true;
  11862. geometry.colorsNeedUpdate = true;
  11863. }
  11864. } else if ( object instanceof THREE.ParticleSystem ) {
  11865. geometry = object.geometry;
  11866. if ( ! geometry.__webglVertexBuffer ) {
  11867. if ( geometry instanceof THREE.Geometry ) {
  11868. createParticleBuffers( geometry );
  11869. initParticleBuffers( geometry, object );
  11870. geometry.verticesNeedUpdate = true;
  11871. geometry.colorsNeedUpdate = true;
  11872. } else if ( geometry instanceof THREE.BufferGeometry ) {
  11873. initDirectBuffers( geometry );
  11874. }
  11875. }
  11876. }
  11877. }
  11878. if ( ! object.__webglActive ) {
  11879. if ( object instanceof THREE.Mesh ) {
  11880. geometry = object.geometry;
  11881. if ( geometry instanceof THREE.BufferGeometry ) {
  11882. addBuffer( scene.__webglObjects, geometry, object );
  11883. } else {
  11884. for ( g in geometry.geometryGroups ) {
  11885. geometryGroup = geometry.geometryGroups[ g ];
  11886. addBuffer( scene.__webglObjects, geometryGroup, object );
  11887. }
  11888. }
  11889. } else if ( object instanceof THREE.Ribbon ||
  11890. object instanceof THREE.Line ||
  11891. object instanceof THREE.ParticleSystem ) {
  11892. geometry = object.geometry;
  11893. addBuffer( scene.__webglObjects, geometry, object );
  11894. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  11895. addBufferImmediate( scene.__webglObjectsImmediate, object );
  11896. } else if ( object instanceof THREE.Sprite ) {
  11897. scene.__webglSprites.push( object );
  11898. } else if ( object instanceof THREE.LensFlare ) {
  11899. scene.__webglFlares.push( object );
  11900. }
  11901. object.__webglActive = true;
  11902. }
  11903. };
  11904. function addBuffer ( objlist, buffer, object ) {
  11905. objlist.push(
  11906. {
  11907. buffer: buffer,
  11908. object: object,
  11909. opaque: null,
  11910. transparent: null
  11911. }
  11912. );
  11913. };
  11914. function addBufferImmediate ( objlist, object ) {
  11915. objlist.push(
  11916. {
  11917. object: object,
  11918. opaque: null,
  11919. transparent: null
  11920. }
  11921. );
  11922. };
  11923. // Objects updates
  11924. function updateObject ( object ) {
  11925. var geometry = object.geometry,
  11926. geometryGroup, customAttributesDirty, material;
  11927. if ( object instanceof THREE.Mesh ) {
  11928. if ( geometry instanceof THREE.BufferGeometry ) {
  11929. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  11930. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11931. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  11932. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  11933. }
  11934. geometry.verticesNeedUpdate = false;
  11935. geometry.elementsNeedUpdate = false;
  11936. geometry.uvsNeedUpdate = false;
  11937. geometry.normalsNeedUpdate = false;
  11938. geometry.colorsNeedUpdate = false;
  11939. geometry.tangentsNeedUpdate = false;
  11940. } else {
  11941. // check all geometry groups
  11942. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  11943. geometryGroup = geometry.geometryGroupsList[ i ];
  11944. material = getBufferMaterial( object, geometryGroup );
  11945. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11946. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  11947. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  11948. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  11949. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  11950. }
  11951. }
  11952. geometry.verticesNeedUpdate = false;
  11953. geometry.morphTargetsNeedUpdate = false;
  11954. geometry.elementsNeedUpdate = false;
  11955. geometry.uvsNeedUpdate = false;
  11956. geometry.normalsNeedUpdate = false;
  11957. geometry.colorsNeedUpdate = false;
  11958. geometry.tangentsNeedUpdate = false;
  11959. material.attributes && clearCustomAttributes( material );
  11960. }
  11961. } else if ( object instanceof THREE.Ribbon ) {
  11962. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11963. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  11964. }
  11965. geometry.verticesNeedUpdate = false;
  11966. geometry.colorsNeedUpdate = false;
  11967. } else if ( object instanceof THREE.Line ) {
  11968. material = getBufferMaterial( object, geometryGroup );
  11969. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11970. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || customAttributesDirty ) {
  11971. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  11972. }
  11973. geometry.verticesNeedUpdate = false;
  11974. geometry.colorsNeedUpdate = false;
  11975. material.attributes && clearCustomAttributes( material );
  11976. } else if ( object instanceof THREE.ParticleSystem ) {
  11977. if ( geometry instanceof THREE.BufferGeometry ) {
  11978. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  11979. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  11980. }
  11981. geometry.verticesNeedUpdate = false;
  11982. geometry.colorsNeedUpdate = false;
  11983. } else {
  11984. material = getBufferMaterial( object, geometryGroup );
  11985. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  11986. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  11987. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  11988. }
  11989. geometry.verticesNeedUpdate = false;
  11990. geometry.colorsNeedUpdate = false;
  11991. material.attributes && clearCustomAttributes( material );
  11992. }
  11993. }
  11994. };
  11995. // Objects updates - custom attributes check
  11996. function areCustomAttributesDirty ( material ) {
  11997. for ( var a in material.attributes ) {
  11998. if ( material.attributes[ a ].needsUpdate ) return true;
  11999. }
  12000. return false;
  12001. };
  12002. function clearCustomAttributes ( material ) {
  12003. for ( var a in material.attributes ) {
  12004. material.attributes[ a ].needsUpdate = false;
  12005. }
  12006. };
  12007. // Objects removal
  12008. function removeObject ( object, scene ) {
  12009. if ( object instanceof THREE.Mesh ||
  12010. object instanceof THREE.ParticleSystem ||
  12011. object instanceof THREE.Ribbon ||
  12012. object instanceof THREE.Line ) {
  12013. removeInstances( scene.__webglObjects, object );
  12014. } else if ( object instanceof THREE.Sprite ) {
  12015. removeInstancesDirect( scene.__webglSprites, object );
  12016. } else if ( object instanceof THREE.LensFlare ) {
  12017. removeInstancesDirect( scene.__webglFlares, object );
  12018. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12019. removeInstances( scene.__webglObjectsImmediate, object );
  12020. }
  12021. object.__webglActive = false;
  12022. };
  12023. function removeInstances ( objlist, object ) {
  12024. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12025. if ( objlist[ o ].object === object ) {
  12026. objlist.splice( o, 1 );
  12027. }
  12028. }
  12029. };
  12030. function removeInstancesDirect ( objlist, object ) {
  12031. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12032. if ( objlist[ o ] === object ) {
  12033. objlist.splice( o, 1 );
  12034. }
  12035. }
  12036. };
  12037. // Materials
  12038. this.initMaterial = function ( material, lights, fog, object ) {
  12039. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12040. if ( material instanceof THREE.MeshDepthMaterial ) {
  12041. shaderID = 'depth';
  12042. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12043. shaderID = 'normal';
  12044. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12045. shaderID = 'basic';
  12046. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12047. shaderID = 'lambert';
  12048. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12049. shaderID = 'phong';
  12050. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12051. shaderID = 'basic';
  12052. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12053. shaderID = 'particle_basic';
  12054. }
  12055. if ( shaderID ) {
  12056. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12057. }
  12058. // heuristics to create shader parameters according to lights in the scene
  12059. // (not to blow over maxLights budget)
  12060. maxLightCount = allocateLights( lights );
  12061. maxShadows = allocateShadows( lights );
  12062. maxBones = allocateBones( object );
  12063. parameters = {
  12064. map: !!material.map,
  12065. envMap: !!material.envMap,
  12066. lightMap: !!material.lightMap,
  12067. bumpMap: !!material.bumpMap,
  12068. normalMap: !!material.normalMap,
  12069. specularMap: !!material.specularMap,
  12070. vertexColors: material.vertexColors,
  12071. fog: fog,
  12072. useFog: material.fog,
  12073. sizeAttenuation: material.sizeAttenuation,
  12074. skinning: material.skinning,
  12075. maxBones: maxBones,
  12076. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12077. boneTextureWidth: object && object.boneTextureWidth,
  12078. boneTextureHeight: object && object.boneTextureHeight,
  12079. morphTargets: material.morphTargets,
  12080. morphNormals: material.morphNormals,
  12081. maxMorphTargets: this.maxMorphTargets,
  12082. maxMorphNormals: this.maxMorphNormals,
  12083. maxDirLights: maxLightCount.directional,
  12084. maxPointLights: maxLightCount.point,
  12085. maxSpotLights: maxLightCount.spot,
  12086. maxHemiLights: maxLightCount.hemi,
  12087. maxShadows: maxShadows,
  12088. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  12089. shadowMapSoft: this.shadowMapSoft,
  12090. shadowMapDebug: this.shadowMapDebug,
  12091. shadowMapCascade: this.shadowMapCascade,
  12092. alphaTest: material.alphaTest,
  12093. metal: material.metal,
  12094. perPixel: material.perPixel,
  12095. wrapAround: material.wrapAround,
  12096. doubleSided: material.side === THREE.DoubleSide,
  12097. flipSided: material.side === THREE.BackSide
  12098. };
  12099. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  12100. var attributes = material.program.attributes;
  12101. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  12102. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  12103. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  12104. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  12105. if ( material.skinning &&
  12106. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12107. _gl.enableVertexAttribArray( attributes.skinIndex );
  12108. _gl.enableVertexAttribArray( attributes.skinWeight );
  12109. }
  12110. if ( material.attributes ) {
  12111. for ( a in material.attributes ) {
  12112. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  12113. }
  12114. }
  12115. if ( material.morphTargets ) {
  12116. material.numSupportedMorphTargets = 0;
  12117. var id, base = "morphTarget";
  12118. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  12119. id = base + i;
  12120. if ( attributes[ id ] >= 0 ) {
  12121. _gl.enableVertexAttribArray( attributes[ id ] );
  12122. material.numSupportedMorphTargets ++;
  12123. }
  12124. }
  12125. }
  12126. if ( material.morphNormals ) {
  12127. material.numSupportedMorphNormals = 0;
  12128. var id, base = "morphNormal";
  12129. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  12130. id = base + i;
  12131. if ( attributes[ id ] >= 0 ) {
  12132. _gl.enableVertexAttribArray( attributes[ id ] );
  12133. material.numSupportedMorphNormals ++;
  12134. }
  12135. }
  12136. }
  12137. material.uniformsList = [];
  12138. for ( u in material.uniforms ) {
  12139. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  12140. }
  12141. };
  12142. function setMaterialShaders( material, shaders ) {
  12143. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  12144. material.vertexShader = shaders.vertexShader;
  12145. material.fragmentShader = shaders.fragmentShader;
  12146. };
  12147. function setProgram( camera, lights, fog, material, object ) {
  12148. _usedTextureUnits = 0;
  12149. if ( material.needsUpdate ) {
  12150. if ( material.program ) _this.deallocateMaterial( material );
  12151. _this.initMaterial( material, lights, fog, object );
  12152. material.needsUpdate = false;
  12153. }
  12154. if ( material.morphTargets ) {
  12155. if ( ! object.__webglMorphTargetInfluences ) {
  12156. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  12157. }
  12158. }
  12159. var refreshMaterial = false;
  12160. var program = material.program,
  12161. p_uniforms = program.uniforms,
  12162. m_uniforms = material.uniforms;
  12163. if ( program !== _currentProgram ) {
  12164. _gl.useProgram( program );
  12165. _currentProgram = program;
  12166. refreshMaterial = true;
  12167. }
  12168. if ( material.id !== _currentMaterialId ) {
  12169. _currentMaterialId = material.id;
  12170. refreshMaterial = true;
  12171. }
  12172. if ( refreshMaterial || camera !== _currentCamera ) {
  12173. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  12174. if ( camera !== _currentCamera ) _currentCamera = camera;
  12175. }
  12176. // skinning uniforms must be set even if material didn't change
  12177. // auto-setting of texture unit for bone texture must go before other textures
  12178. // not sure why, but otherwise weird things happen
  12179. if ( material.skinning ) {
  12180. if ( _supportsBoneTextures && object.useVertexTexture ) {
  12181. if ( p_uniforms.boneTexture !== null ) {
  12182. var textureUnit = getTextureUnit();
  12183. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  12184. _this.setTexture( object.boneTexture, textureUnit );
  12185. }
  12186. } else {
  12187. if ( p_uniforms.boneGlobalMatrices !== null ) {
  12188. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  12189. }
  12190. }
  12191. }
  12192. if ( refreshMaterial ) {
  12193. // refresh uniforms common to several materials
  12194. if ( fog && material.fog ) {
  12195. refreshUniformsFog( m_uniforms, fog );
  12196. }
  12197. if ( material instanceof THREE.MeshPhongMaterial ||
  12198. material instanceof THREE.MeshLambertMaterial ||
  12199. material.lights ) {
  12200. if ( _lightsNeedUpdate ) {
  12201. setupLights( program, lights );
  12202. _lightsNeedUpdate = false;
  12203. }
  12204. refreshUniformsLights( m_uniforms, _lights );
  12205. }
  12206. if ( material instanceof THREE.MeshBasicMaterial ||
  12207. material instanceof THREE.MeshLambertMaterial ||
  12208. material instanceof THREE.MeshPhongMaterial ) {
  12209. refreshUniformsCommon( m_uniforms, material );
  12210. }
  12211. // refresh single material specific uniforms
  12212. if ( material instanceof THREE.LineBasicMaterial ) {
  12213. refreshUniformsLine( m_uniforms, material );
  12214. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12215. refreshUniformsParticle( m_uniforms, material );
  12216. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12217. refreshUniformsPhong( m_uniforms, material );
  12218. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12219. refreshUniformsLambert( m_uniforms, material );
  12220. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  12221. m_uniforms.mNear.value = camera.near;
  12222. m_uniforms.mFar.value = camera.far;
  12223. m_uniforms.opacity.value = material.opacity;
  12224. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12225. m_uniforms.opacity.value = material.opacity;
  12226. }
  12227. if ( object.receiveShadow && ! material._shadowPass ) {
  12228. refreshUniformsShadow( m_uniforms, lights );
  12229. }
  12230. // load common uniforms
  12231. loadUniformsGeneric( program, material.uniformsList );
  12232. // load material specific uniforms
  12233. // (shader material also gets them for the sake of genericity)
  12234. if ( material instanceof THREE.ShaderMaterial ||
  12235. material instanceof THREE.MeshPhongMaterial ||
  12236. material.envMap ) {
  12237. if ( p_uniforms.cameraPosition !== null ) {
  12238. var position = camera.matrixWorld.getPosition();
  12239. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  12240. }
  12241. }
  12242. if ( material instanceof THREE.MeshPhongMaterial ||
  12243. material instanceof THREE.MeshLambertMaterial ||
  12244. material instanceof THREE.ShaderMaterial ||
  12245. material.skinning ) {
  12246. if ( p_uniforms.viewMatrix !== null ) {
  12247. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  12248. }
  12249. }
  12250. }
  12251. loadUniformsMatrices( p_uniforms, object );
  12252. if ( p_uniforms.modelMatrix !== null ) {
  12253. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  12254. }
  12255. return program;
  12256. };
  12257. // Uniforms (refresh uniforms objects)
  12258. function refreshUniformsCommon ( uniforms, material ) {
  12259. uniforms.opacity.value = material.opacity;
  12260. if ( _this.gammaInput ) {
  12261. uniforms.diffuse.value.copyGammaToLinear( material.color );
  12262. } else {
  12263. uniforms.diffuse.value = material.color;
  12264. }
  12265. uniforms.map.value = material.map;
  12266. uniforms.lightMap.value = material.lightMap;
  12267. uniforms.specularMap.value = material.specularMap;
  12268. if ( material.bumpMap ) {
  12269. uniforms.bumpMap.value = material.bumpMap;
  12270. uniforms.bumpScale.value = material.bumpScale;
  12271. }
  12272. if ( material.normalMap ) {
  12273. uniforms.normalMap.value = material.normalMap;
  12274. uniforms.normalScale.value.copy( material.normalScale );
  12275. }
  12276. // uv repeat and offset setting priorities
  12277. // 1. color map
  12278. // 2. specular map
  12279. // 3. normal map
  12280. // 4. bump map
  12281. var uvScaleMap;
  12282. if ( material.map ) {
  12283. uvScaleMap = material.map;
  12284. } else if ( material.specularMap ) {
  12285. uvScaleMap = material.specularMap;
  12286. } else if ( material.normalMap ) {
  12287. uvScaleMap = material.normalMap;
  12288. } else if ( material.bumpMap ) {
  12289. uvScaleMap = material.bumpMap;
  12290. }
  12291. if ( uvScaleMap !== undefined ) {
  12292. var offset = uvScaleMap.offset;
  12293. var repeat = uvScaleMap.repeat;
  12294. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  12295. }
  12296. uniforms.envMap.value = material.envMap;
  12297. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  12298. if ( _this.gammaInput ) {
  12299. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  12300. uniforms.reflectivity.value = material.reflectivity;
  12301. } else {
  12302. uniforms.reflectivity.value = material.reflectivity;
  12303. }
  12304. uniforms.refractionRatio.value = material.refractionRatio;
  12305. uniforms.combine.value = material.combine;
  12306. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  12307. };
  12308. function refreshUniformsLine ( uniforms, material ) {
  12309. uniforms.diffuse.value = material.color;
  12310. uniforms.opacity.value = material.opacity;
  12311. };
  12312. function refreshUniformsParticle ( uniforms, material ) {
  12313. uniforms.psColor.value = material.color;
  12314. uniforms.opacity.value = material.opacity;
  12315. uniforms.size.value = material.size;
  12316. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  12317. uniforms.map.value = material.map;
  12318. };
  12319. function refreshUniformsFog ( uniforms, fog ) {
  12320. uniforms.fogColor.value = fog.color;
  12321. if ( fog instanceof THREE.Fog ) {
  12322. uniforms.fogNear.value = fog.near;
  12323. uniforms.fogFar.value = fog.far;
  12324. } else if ( fog instanceof THREE.FogExp2 ) {
  12325. uniforms.fogDensity.value = fog.density;
  12326. }
  12327. };
  12328. function refreshUniformsPhong ( uniforms, material ) {
  12329. uniforms.shininess.value = material.shininess;
  12330. if ( _this.gammaInput ) {
  12331. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12332. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12333. uniforms.specular.value.copyGammaToLinear( material.specular );
  12334. } else {
  12335. uniforms.ambient.value = material.ambient;
  12336. uniforms.emissive.value = material.emissive;
  12337. uniforms.specular.value = material.specular;
  12338. }
  12339. if ( material.wrapAround ) {
  12340. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12341. }
  12342. };
  12343. function refreshUniformsLambert ( uniforms, material ) {
  12344. if ( _this.gammaInput ) {
  12345. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  12346. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  12347. } else {
  12348. uniforms.ambient.value = material.ambient;
  12349. uniforms.emissive.value = material.emissive;
  12350. }
  12351. if ( material.wrapAround ) {
  12352. uniforms.wrapRGB.value.copy( material.wrapRGB );
  12353. }
  12354. };
  12355. function refreshUniformsLights ( uniforms, lights ) {
  12356. uniforms.ambientLightColor.value = lights.ambient;
  12357. uniforms.directionalLightColor.value = lights.directional.colors;
  12358. uniforms.directionalLightDirection.value = lights.directional.positions;
  12359. uniforms.pointLightColor.value = lights.point.colors;
  12360. uniforms.pointLightPosition.value = lights.point.positions;
  12361. uniforms.pointLightDistance.value = lights.point.distances;
  12362. uniforms.spotLightColor.value = lights.spot.colors;
  12363. uniforms.spotLightPosition.value = lights.spot.positions;
  12364. uniforms.spotLightDistance.value = lights.spot.distances;
  12365. uniforms.spotLightDirection.value = lights.spot.directions;
  12366. uniforms.spotLightAngle.value = lights.spot.angles;
  12367. uniforms.spotLightExponent.value = lights.spot.exponents;
  12368. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  12369. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  12370. uniforms.hemisphereLightPosition.value = lights.hemi.positions;
  12371. };
  12372. function refreshUniformsShadow ( uniforms, lights ) {
  12373. if ( uniforms.shadowMatrix ) {
  12374. var j = 0;
  12375. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  12376. var light = lights[ i ];
  12377. if ( ! light.castShadow ) continue;
  12378. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  12379. uniforms.shadowMap.value[ j ] = light.shadowMap;
  12380. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  12381. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  12382. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  12383. uniforms.shadowBias.value[ j ] = light.shadowBias;
  12384. j ++;
  12385. }
  12386. }
  12387. }
  12388. };
  12389. // Uniforms (load to GPU)
  12390. function loadUniformsMatrices ( uniforms, object ) {
  12391. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  12392. if ( uniforms.normalMatrix ) {
  12393. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  12394. }
  12395. };
  12396. function getTextureUnit() {
  12397. var textureUnit = _usedTextureUnits;
  12398. if ( textureUnit >= _maxTextures ) {
  12399. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  12400. }
  12401. _usedTextureUnits += 1;
  12402. return textureUnit;
  12403. };
  12404. function loadUniformsGeneric ( program, uniforms ) {
  12405. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  12406. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  12407. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  12408. if ( !location ) continue;
  12409. uniform = uniforms[ j ][ 0 ];
  12410. type = uniform.type;
  12411. value = uniform.value;
  12412. if ( type === "i" ) { // single integer
  12413. _gl.uniform1i( location, value );
  12414. } else if ( type === "f" ) { // single float
  12415. _gl.uniform1f( location, value );
  12416. } else if ( type === "v2" ) { // single THREE.Vector2
  12417. _gl.uniform2f( location, value.x, value.y );
  12418. } else if ( type === "v3" ) { // single THREE.Vector3
  12419. _gl.uniform3f( location, value.x, value.y, value.z );
  12420. } else if ( type === "v4" ) { // single THREE.Vector4
  12421. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  12422. } else if ( type === "c" ) { // single THREE.Color
  12423. _gl.uniform3f( location, value.r, value.g, value.b );
  12424. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  12425. _gl.uniform1iv( location, value );
  12426. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  12427. _gl.uniform3iv( location, value );
  12428. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  12429. _gl.uniform1fv( location, value );
  12430. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  12431. _gl.uniform3fv( location, value );
  12432. } else if ( type === "v2v" ) { // array of THREE.Vector2
  12433. if ( uniform._array === undefined ) {
  12434. uniform._array = new Float32Array( 2 * value.length );
  12435. }
  12436. for ( i = 0, il = value.length; i < il; i ++ ) {
  12437. offset = i * 2;
  12438. uniform._array[ offset ] = value[ i ].x;
  12439. uniform._array[ offset + 1 ] = value[ i ].y;
  12440. }
  12441. _gl.uniform2fv( location, uniform._array );
  12442. } else if ( type === "v3v" ) { // array of THREE.Vector3
  12443. if ( uniform._array === undefined ) {
  12444. uniform._array = new Float32Array( 3 * value.length );
  12445. }
  12446. for ( i = 0, il = value.length; i < il; i ++ ) {
  12447. offset = i * 3;
  12448. uniform._array[ offset ] = value[ i ].x;
  12449. uniform._array[ offset + 1 ] = value[ i ].y;
  12450. uniform._array[ offset + 2 ] = value[ i ].z;
  12451. }
  12452. _gl.uniform3fv( location, uniform._array );
  12453. } else if ( type === "v4v" ) { // array of THREE.Vector4
  12454. if ( uniform._array === undefined ) {
  12455. uniform._array = new Float32Array( 4 * value.length );
  12456. }
  12457. for ( i = 0, il = value.length; i < il; i ++ ) {
  12458. offset = i * 4;
  12459. uniform._array[ offset ] = value[ i ].x;
  12460. uniform._array[ offset + 1 ] = value[ i ].y;
  12461. uniform._array[ offset + 2 ] = value[ i ].z;
  12462. uniform._array[ offset + 3 ] = value[ i ].w;
  12463. }
  12464. _gl.uniform4fv( location, uniform._array );
  12465. } else if ( type === "m4") { // single THREE.Matrix4
  12466. if ( uniform._array === undefined ) {
  12467. uniform._array = new Float32Array( 16 );
  12468. }
  12469. value.flattenToArray( uniform._array );
  12470. _gl.uniformMatrix4fv( location, false, uniform._array );
  12471. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  12472. if ( uniform._array === undefined ) {
  12473. uniform._array = new Float32Array( 16 * value.length );
  12474. }
  12475. for ( i = 0, il = value.length; i < il; i ++ ) {
  12476. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  12477. }
  12478. _gl.uniformMatrix4fv( location, false, uniform._array );
  12479. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  12480. texture = value;
  12481. textureUnit = getTextureUnit();
  12482. _gl.uniform1i( location, textureUnit );
  12483. if ( !texture ) continue;
  12484. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  12485. setCubeTexture( texture, textureUnit );
  12486. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  12487. setCubeTextureDynamic( texture, textureUnit );
  12488. } else {
  12489. _this.setTexture( texture, textureUnit );
  12490. }
  12491. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  12492. if ( uniform._array === undefined ) {
  12493. uniform._array = [];
  12494. }
  12495. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12496. uniform._array[ i ] = getTextureUnit();
  12497. }
  12498. _gl.uniform1iv( location, uniform._array );
  12499. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  12500. texture = uniform.value[ i ];
  12501. textureUnit = uniform._array[ i ];
  12502. if ( !texture ) continue;
  12503. _this.setTexture( texture, textureUnit );
  12504. }
  12505. }
  12506. }
  12507. };
  12508. function setupMatrices ( object, camera ) {
  12509. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  12510. object._normalMatrix.getInverse( object._modelViewMatrix );
  12511. object._normalMatrix.transpose();
  12512. };
  12513. //
  12514. function setColorGamma( array, offset, color, intensitySq ) {
  12515. array[ offset ] = color.r * color.r * intensitySq;
  12516. array[ offset + 1 ] = color.g * color.g * intensitySq;
  12517. array[ offset + 2 ] = color.b * color.b * intensitySq;
  12518. };
  12519. function setColorLinear( array, offset, color, intensity ) {
  12520. array[ offset ] = color.r * intensity;
  12521. array[ offset + 1 ] = color.g * intensity;
  12522. array[ offset + 2 ] = color.b * intensity;
  12523. };
  12524. function setupLights ( program, lights ) {
  12525. var l, ll, light, n,
  12526. r = 0, g = 0, b = 0,
  12527. color, skyColor, groundColor,
  12528. intensity, intensitySq,
  12529. position,
  12530. distance,
  12531. zlights = _lights,
  12532. dirColors = zlights.directional.colors,
  12533. dirPositions = zlights.directional.positions,
  12534. pointColors = zlights.point.colors,
  12535. pointPositions = zlights.point.positions,
  12536. pointDistances = zlights.point.distances,
  12537. spotColors = zlights.spot.colors,
  12538. spotPositions = zlights.spot.positions,
  12539. spotDistances = zlights.spot.distances,
  12540. spotDirections = zlights.spot.directions,
  12541. spotAngles = zlights.spot.angles,
  12542. spotExponents = zlights.spot.exponents,
  12543. hemiSkyColors = zlights.hemi.skyColors,
  12544. hemiGroundColors = zlights.hemi.groundColors,
  12545. hemiPositions = zlights.hemi.positions,
  12546. dirLength = 0,
  12547. pointLength = 0,
  12548. spotLength = 0,
  12549. hemiLength = 0,
  12550. dirOffset = 0,
  12551. pointOffset = 0,
  12552. spotOffset = 0,
  12553. hemiOffset = 0;
  12554. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  12555. light = lights[ l ];
  12556. if ( light.onlyShadow || ! light.visible ) continue;
  12557. color = light.color;
  12558. intensity = light.intensity;
  12559. distance = light.distance;
  12560. if ( light instanceof THREE.AmbientLight ) {
  12561. if ( _this.gammaInput ) {
  12562. r += color.r * color.r;
  12563. g += color.g * color.g;
  12564. b += color.b * color.b;
  12565. } else {
  12566. r += color.r;
  12567. g += color.g;
  12568. b += color.b;
  12569. }
  12570. } else if ( light instanceof THREE.DirectionalLight ) {
  12571. dirOffset = dirLength * 3;
  12572. if ( _this.gammaInput ) {
  12573. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  12574. } else {
  12575. setColorLinear( dirColors, dirOffset, color, intensity );
  12576. }
  12577. _direction.copy( light.matrixWorld.getPosition() );
  12578. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12579. _direction.normalize();
  12580. dirPositions[ dirOffset ] = _direction.x;
  12581. dirPositions[ dirOffset + 1 ] = _direction.y;
  12582. dirPositions[ dirOffset + 2 ] = _direction.z;
  12583. dirLength += 1;
  12584. } else if( light instanceof THREE.PointLight ) {
  12585. pointOffset = pointLength * 3;
  12586. if ( _this.gammaInput ) {
  12587. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  12588. } else {
  12589. setColorLinear( pointColors, pointOffset, color, intensity );
  12590. }
  12591. position = light.matrixWorld.getPosition();
  12592. pointPositions[ pointOffset ] = position.x;
  12593. pointPositions[ pointOffset + 1 ] = position.y;
  12594. pointPositions[ pointOffset + 2 ] = position.z;
  12595. pointDistances[ pointLength ] = distance;
  12596. pointLength += 1;
  12597. } else if( light instanceof THREE.SpotLight ) {
  12598. spotOffset = spotLength * 3;
  12599. if ( _this.gammaInput ) {
  12600. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  12601. } else {
  12602. setColorLinear( spotColors, spotOffset, color, intensity );
  12603. }
  12604. position = light.matrixWorld.getPosition();
  12605. spotPositions[ spotOffset ] = position.x;
  12606. spotPositions[ spotOffset + 1 ] = position.y;
  12607. spotPositions[ spotOffset + 2 ] = position.z;
  12608. spotDistances[ spotLength ] = distance;
  12609. _direction.copy( position );
  12610. _direction.subSelf( light.target.matrixWorld.getPosition() );
  12611. _direction.normalize();
  12612. spotDirections[ spotOffset ] = _direction.x;
  12613. spotDirections[ spotOffset + 1 ] = _direction.y;
  12614. spotDirections[ spotOffset + 2 ] = _direction.z;
  12615. spotAngles[ spotLength ] = Math.cos( light.angle );
  12616. spotExponents[ spotLength ] = light.exponent;
  12617. spotLength += 1;
  12618. } else if ( light instanceof THREE.HemisphereLight ) {
  12619. skyColor = light.color;
  12620. groundColor = light.groundColor;
  12621. hemiOffset = hemiLength * 3;
  12622. if ( _this.gammaInput ) {
  12623. intensitySq = intensity * intensity;
  12624. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  12625. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  12626. } else {
  12627. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  12628. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  12629. }
  12630. position = light.matrixWorld.getPosition();
  12631. hemiPositions[ hemiOffset ] = position.x;
  12632. hemiPositions[ hemiOffset + 1 ] = position.y;
  12633. hemiPositions[ hemiOffset + 2 ] = position.z;
  12634. hemiLength += 1;
  12635. }
  12636. }
  12637. // null eventual remains from removed lights
  12638. // (this is to avoid if in shader)
  12639. for ( l = dirLength * 3, ll = dirColors.length; l < ll; l ++ ) dirColors[ l ] = 0.0;
  12640. for ( l = pointLength * 3, ll = pointColors.length; l < ll; l ++ ) pointColors[ l ] = 0.0;
  12641. for ( l = spotLength * 3, ll = spotColors.length; l < ll; l ++ ) spotColors[ l ] = 0.0;
  12642. for ( l = hemiLength * 3, ll = hemiSkyColors.length; l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  12643. for ( l = hemiLength * 3, ll = hemiGroundColors.length; l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  12644. zlights.directional.length = dirLength;
  12645. zlights.point.length = pointLength;
  12646. zlights.spot.length = spotLength;
  12647. zlights.hemi.length = hemiLength;
  12648. zlights.ambient[ 0 ] = r;
  12649. zlights.ambient[ 1 ] = g;
  12650. zlights.ambient[ 2 ] = b;
  12651. };
  12652. // GL state setting
  12653. this.setFaceCulling = function ( cullFace, frontFace ) {
  12654. if ( cullFace ) {
  12655. if ( !frontFace || frontFace === "ccw" ) {
  12656. _gl.frontFace( _gl.CCW );
  12657. } else {
  12658. _gl.frontFace( _gl.CW );
  12659. }
  12660. if( cullFace === "back" ) {
  12661. _gl.cullFace( _gl.BACK );
  12662. } else if( cullFace === "front" ) {
  12663. _gl.cullFace( _gl.FRONT );
  12664. } else {
  12665. _gl.cullFace( _gl.FRONT_AND_BACK );
  12666. }
  12667. _gl.enable( _gl.CULL_FACE );
  12668. } else {
  12669. _gl.disable( _gl.CULL_FACE );
  12670. }
  12671. };
  12672. this.setMaterialFaces = function ( material ) {
  12673. var doubleSided = material.side === THREE.DoubleSide;
  12674. var flipSided = material.side === THREE.BackSide;
  12675. if ( _oldDoubleSided !== doubleSided ) {
  12676. if ( doubleSided ) {
  12677. _gl.disable( _gl.CULL_FACE );
  12678. } else {
  12679. _gl.enable( _gl.CULL_FACE );
  12680. }
  12681. _oldDoubleSided = doubleSided;
  12682. }
  12683. if ( _oldFlipSided !== flipSided ) {
  12684. if ( flipSided ) {
  12685. _gl.frontFace( _gl.CW );
  12686. } else {
  12687. _gl.frontFace( _gl.CCW );
  12688. }
  12689. _oldFlipSided = flipSided;
  12690. }
  12691. };
  12692. this.setDepthTest = function ( depthTest ) {
  12693. if ( _oldDepthTest !== depthTest ) {
  12694. if ( depthTest ) {
  12695. _gl.enable( _gl.DEPTH_TEST );
  12696. } else {
  12697. _gl.disable( _gl.DEPTH_TEST );
  12698. }
  12699. _oldDepthTest = depthTest;
  12700. }
  12701. };
  12702. this.setDepthWrite = function ( depthWrite ) {
  12703. if ( _oldDepthWrite !== depthWrite ) {
  12704. _gl.depthMask( depthWrite );
  12705. _oldDepthWrite = depthWrite;
  12706. }
  12707. };
  12708. function setLineWidth ( width ) {
  12709. if ( width !== _oldLineWidth ) {
  12710. _gl.lineWidth( width );
  12711. _oldLineWidth = width;
  12712. }
  12713. };
  12714. function setPolygonOffset ( polygonoffset, factor, units ) {
  12715. if ( _oldPolygonOffset !== polygonoffset ) {
  12716. if ( polygonoffset ) {
  12717. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  12718. } else {
  12719. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  12720. }
  12721. _oldPolygonOffset = polygonoffset;
  12722. }
  12723. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  12724. _gl.polygonOffset( factor, units );
  12725. _oldPolygonOffsetFactor = factor;
  12726. _oldPolygonOffsetUnits = units;
  12727. }
  12728. };
  12729. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  12730. if ( blending !== _oldBlending ) {
  12731. if ( blending === THREE.NoBlending ) {
  12732. _gl.disable( _gl.BLEND );
  12733. } else if ( blending === THREE.AdditiveBlending ) {
  12734. _gl.enable( _gl.BLEND );
  12735. _gl.blendEquation( _gl.FUNC_ADD );
  12736. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  12737. } else if ( blending === THREE.SubtractiveBlending ) {
  12738. // TODO: Find blendFuncSeparate() combination
  12739. _gl.enable( _gl.BLEND );
  12740. _gl.blendEquation( _gl.FUNC_ADD );
  12741. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  12742. } else if ( blending === THREE.MultiplyBlending ) {
  12743. // TODO: Find blendFuncSeparate() combination
  12744. _gl.enable( _gl.BLEND );
  12745. _gl.blendEquation( _gl.FUNC_ADD );
  12746. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  12747. } else if ( blending === THREE.CustomBlending ) {
  12748. _gl.enable( _gl.BLEND );
  12749. } else {
  12750. _gl.enable( _gl.BLEND );
  12751. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  12752. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  12753. }
  12754. _oldBlending = blending;
  12755. }
  12756. if ( blending === THREE.CustomBlending ) {
  12757. if ( blendEquation !== _oldBlendEquation ) {
  12758. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  12759. _oldBlendEquation = blendEquation;
  12760. }
  12761. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  12762. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  12763. _oldBlendSrc = blendSrc;
  12764. _oldBlendDst = blendDst;
  12765. }
  12766. } else {
  12767. _oldBlendEquation = null;
  12768. _oldBlendSrc = null;
  12769. _oldBlendDst = null;
  12770. }
  12771. };
  12772. // Defines
  12773. function generateDefines ( defines ) {
  12774. var value, chunk, chunks = [];
  12775. for ( var d in defines ) {
  12776. value = defines[ d ];
  12777. if ( value === false ) continue;
  12778. chunk = "#define " + d + " " + value;
  12779. chunks.push( chunk );
  12780. }
  12781. return chunks.join( "\n" );
  12782. };
  12783. // Shaders
  12784. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  12785. var p, pl, d, program, code;
  12786. var chunks = [];
  12787. // Generate code
  12788. if ( shaderID ) {
  12789. chunks.push( shaderID );
  12790. } else {
  12791. chunks.push( fragmentShader );
  12792. chunks.push( vertexShader );
  12793. }
  12794. for ( d in defines ) {
  12795. chunks.push( d );
  12796. chunks.push( defines[ d ] );
  12797. }
  12798. for ( p in parameters ) {
  12799. chunks.push( p );
  12800. chunks.push( parameters[ p ] );
  12801. }
  12802. code = chunks.join();
  12803. // Check if code has been already compiled
  12804. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  12805. var programInfo = _programs[ p ];
  12806. if ( programInfo.code === code ) {
  12807. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  12808. programInfo.usedTimes ++;
  12809. return programInfo.program;
  12810. }
  12811. }
  12812. //console.log( "building new program " );
  12813. //
  12814. var customDefines = generateDefines( defines );
  12815. //
  12816. program = _gl.createProgram();
  12817. var prefix_vertex = [
  12818. "precision " + _precision + " float;",
  12819. customDefines,
  12820. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  12821. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12822. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12823. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12824. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12825. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12826. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12827. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  12828. "#define MAX_SHADOWS " + parameters.maxShadows,
  12829. "#define MAX_BONES " + parameters.maxBones,
  12830. parameters.map ? "#define USE_MAP" : "",
  12831. parameters.envMap ? "#define USE_ENVMAP" : "",
  12832. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12833. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12834. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  12835. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12836. parameters.vertexColors ? "#define USE_COLOR" : "",
  12837. parameters.skinning ? "#define USE_SKINNING" : "",
  12838. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  12839. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  12840. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  12841. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  12842. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  12843. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12844. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12845. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12846. parameters.flipSided ? "#define FLIP_SIDED" : "",
  12847. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12848. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12849. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12850. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12851. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  12852. "uniform mat4 modelMatrix;",
  12853. "uniform mat4 modelViewMatrix;",
  12854. "uniform mat4 projectionMatrix;",
  12855. "uniform mat4 viewMatrix;",
  12856. "uniform mat3 normalMatrix;",
  12857. "uniform vec3 cameraPosition;",
  12858. "attribute vec3 position;",
  12859. "attribute vec3 normal;",
  12860. "attribute vec2 uv;",
  12861. "attribute vec2 uv2;",
  12862. "#ifdef USE_COLOR",
  12863. "attribute vec3 color;",
  12864. "#endif",
  12865. "#ifdef USE_MORPHTARGETS",
  12866. "attribute vec3 morphTarget0;",
  12867. "attribute vec3 morphTarget1;",
  12868. "attribute vec3 morphTarget2;",
  12869. "attribute vec3 morphTarget3;",
  12870. "#ifdef USE_MORPHNORMALS",
  12871. "attribute vec3 morphNormal0;",
  12872. "attribute vec3 morphNormal1;",
  12873. "attribute vec3 morphNormal2;",
  12874. "attribute vec3 morphNormal3;",
  12875. "#else",
  12876. "attribute vec3 morphTarget4;",
  12877. "attribute vec3 morphTarget5;",
  12878. "attribute vec3 morphTarget6;",
  12879. "attribute vec3 morphTarget7;",
  12880. "#endif",
  12881. "#endif",
  12882. "#ifdef USE_SKINNING",
  12883. "attribute vec4 skinIndex;",
  12884. "attribute vec4 skinWeight;",
  12885. "#endif",
  12886. ""
  12887. ].join("\n");
  12888. var prefix_fragment = [
  12889. "precision " + _precision + " float;",
  12890. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  12891. customDefines,
  12892. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  12893. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  12894. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  12895. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  12896. "#define MAX_SHADOWS " + parameters.maxShadows,
  12897. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  12898. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  12899. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  12900. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  12901. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  12902. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  12903. parameters.map ? "#define USE_MAP" : "",
  12904. parameters.envMap ? "#define USE_ENVMAP" : "",
  12905. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  12906. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  12907. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  12908. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  12909. parameters.vertexColors ? "#define USE_COLOR" : "",
  12910. parameters.metal ? "#define METAL" : "",
  12911. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  12912. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  12913. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  12914. parameters.flipSided ? "#define FLIP_SIDED" : "",
  12915. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  12916. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  12917. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  12918. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  12919. "uniform mat4 viewMatrix;",
  12920. "uniform vec3 cameraPosition;",
  12921. ""
  12922. ].join("\n");
  12923. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  12924. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  12925. _gl.attachShader( program, glVertexShader );
  12926. _gl.attachShader( program, glFragmentShader );
  12927. _gl.linkProgram( program );
  12928. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  12929. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  12930. }
  12931. // clean up
  12932. _gl.deleteShader( glFragmentShader );
  12933. _gl.deleteShader( glVertexShader );
  12934. //console.log( prefix_fragment + fragmentShader );
  12935. //console.log( prefix_vertex + vertexShader );
  12936. program.uniforms = {};
  12937. program.attributes = {};
  12938. var identifiers, u, a, i;
  12939. // cache uniform locations
  12940. identifiers = [
  12941. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  12942. 'morphTargetInfluences'
  12943. ];
  12944. if ( parameters.useVertexTexture ) {
  12945. identifiers.push( 'boneTexture' );
  12946. } else {
  12947. identifiers.push( 'boneGlobalMatrices' );
  12948. }
  12949. for ( u in uniforms ) {
  12950. identifiers.push( u );
  12951. }
  12952. cacheUniformLocations( program, identifiers );
  12953. // cache attributes locations
  12954. identifiers = [
  12955. "position", "normal", "uv", "uv2", "tangent", "color",
  12956. "skinIndex", "skinWeight"
  12957. ];
  12958. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  12959. identifiers.push( "morphTarget" + i );
  12960. }
  12961. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  12962. identifiers.push( "morphNormal" + i );
  12963. }
  12964. for ( a in attributes ) {
  12965. identifiers.push( a );
  12966. }
  12967. cacheAttributeLocations( program, identifiers );
  12968. program.id = _programs_counter ++;
  12969. _programs.push( { program: program, code: code, usedTimes: 1 } );
  12970. _this.info.memory.programs = _programs.length;
  12971. return program;
  12972. };
  12973. // Shader parameters cache
  12974. function cacheUniformLocations ( program, identifiers ) {
  12975. var i, l, id;
  12976. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12977. id = identifiers[ i ];
  12978. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  12979. }
  12980. };
  12981. function cacheAttributeLocations ( program, identifiers ) {
  12982. var i, l, id;
  12983. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  12984. id = identifiers[ i ];
  12985. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  12986. }
  12987. };
  12988. function addLineNumbers ( string ) {
  12989. var chunks = string.split( "\n" );
  12990. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  12991. // Chrome reports shader errors on lines
  12992. // starting counting from 1
  12993. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  12994. }
  12995. return chunks.join( "\n" );
  12996. };
  12997. function getShader ( type, string ) {
  12998. var shader;
  12999. if ( type === "fragment" ) {
  13000. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13001. } else if ( type === "vertex" ) {
  13002. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13003. }
  13004. _gl.shaderSource( shader, string );
  13005. _gl.compileShader( shader );
  13006. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13007. console.error( _gl.getShaderInfoLog( shader ) );
  13008. console.error( addLineNumbers( string ) );
  13009. return null;
  13010. }
  13011. return shader;
  13012. };
  13013. // Textures
  13014. function isPowerOfTwo ( value ) {
  13015. return ( value & ( value - 1 ) ) === 0;
  13016. };
  13017. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13018. if ( isImagePowerOfTwo ) {
  13019. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13020. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13021. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13022. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13023. } else {
  13024. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13025. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13026. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13027. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13028. }
  13029. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13030. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13031. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13032. texture.__oldAnisotropy = texture.anisotropy;
  13033. }
  13034. }
  13035. };
  13036. this.setTexture = function ( texture, slot ) {
  13037. if ( texture.needsUpdate ) {
  13038. if ( ! texture.__webglInit ) {
  13039. texture.__webglInit = true;
  13040. texture.__webglTexture = _gl.createTexture();
  13041. _this.info.memory.textures ++;
  13042. }
  13043. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13044. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13045. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13046. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13047. var image = texture.image,
  13048. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13049. glFormat = paramThreeToGL( texture.format ),
  13050. glType = paramThreeToGL( texture.type );
  13051. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13052. if ( texture instanceof THREE.CompressedTexture ) {
  13053. var mipmap, mipmaps = texture.mipmaps;
  13054. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13055. mipmap = mipmaps[ i ];
  13056. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13057. }
  13058. } else if ( texture instanceof THREE.DataTexture ) {
  13059. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13060. } else {
  13061. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  13062. }
  13063. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13064. texture.needsUpdate = false;
  13065. if ( texture.onUpdate ) texture.onUpdate();
  13066. } else {
  13067. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13068. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13069. }
  13070. };
  13071. function clampToMaxSize ( image, maxSize ) {
  13072. if ( image.width <= maxSize && image.height <= maxSize ) {
  13073. return image;
  13074. }
  13075. // Warning: Scaling through the canvas will only work with images that use
  13076. // premultiplied alpha.
  13077. var maxDimension = Math.max( image.width, image.height );
  13078. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  13079. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  13080. var canvas = document.createElement( 'canvas' );
  13081. canvas.width = newWidth;
  13082. canvas.height = newHeight;
  13083. var ctx = canvas.getContext( "2d" );
  13084. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  13085. return canvas;
  13086. }
  13087. function setCubeTexture ( texture, slot ) {
  13088. if ( texture.image.length === 6 ) {
  13089. if ( texture.needsUpdate ) {
  13090. if ( ! texture.image.__webglTextureCube ) {
  13091. texture.image.__webglTextureCube = _gl.createTexture();
  13092. }
  13093. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13094. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13095. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13096. var isCompressed = texture instanceof THREE.CompressedTexture;
  13097. var cubeImage = [];
  13098. for ( var i = 0; i < 6; i ++ ) {
  13099. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  13100. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  13101. } else {
  13102. cubeImage[ i ] = texture.image[ i ];
  13103. }
  13104. }
  13105. var image = cubeImage[ 0 ],
  13106. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13107. glFormat = paramThreeToGL( texture.format ),
  13108. glType = paramThreeToGL( texture.type );
  13109. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  13110. for ( var i = 0; i < 6; i ++ ) {
  13111. if ( isCompressed ) {
  13112. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  13113. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  13114. mipmap = mipmaps[ j ];
  13115. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  13116. }
  13117. } else {
  13118. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  13119. }
  13120. }
  13121. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  13122. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13123. }
  13124. texture.needsUpdate = false;
  13125. if ( texture.onUpdate ) texture.onUpdate();
  13126. } else {
  13127. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13128. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  13129. }
  13130. }
  13131. };
  13132. function setCubeTextureDynamic ( texture, slot ) {
  13133. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13134. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  13135. };
  13136. // Render targets
  13137. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  13138. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13139. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  13140. };
  13141. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  13142. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  13143. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  13144. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  13145. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13146. /* For some reason this is not working. Defaulting to RGBA4.
  13147. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13148. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  13149. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13150. */
  13151. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  13152. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  13153. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  13154. } else {
  13155. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  13156. }
  13157. };
  13158. this.setRenderTarget = function ( renderTarget ) {
  13159. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  13160. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  13161. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  13162. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  13163. renderTarget.__webglTexture = _gl.createTexture();
  13164. // Setup texture, create render and frame buffers
  13165. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  13166. glFormat = paramThreeToGL( renderTarget.format ),
  13167. glType = paramThreeToGL( renderTarget.type );
  13168. if ( isCube ) {
  13169. renderTarget.__webglFramebuffer = [];
  13170. renderTarget.__webglRenderbuffer = [];
  13171. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13172. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  13173. for ( var i = 0; i < 6; i ++ ) {
  13174. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  13175. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  13176. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13177. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  13178. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  13179. }
  13180. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13181. } else {
  13182. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  13183. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  13184. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13185. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  13186. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  13187. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  13188. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  13189. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  13190. }
  13191. // Release everything
  13192. if ( isCube ) {
  13193. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13194. } else {
  13195. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13196. }
  13197. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  13198. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  13199. }
  13200. var framebuffer, width, height, vx, vy;
  13201. if ( renderTarget ) {
  13202. if ( isCube ) {
  13203. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  13204. } else {
  13205. framebuffer = renderTarget.__webglFramebuffer;
  13206. }
  13207. width = renderTarget.width;
  13208. height = renderTarget.height;
  13209. vx = 0;
  13210. vy = 0;
  13211. } else {
  13212. framebuffer = null;
  13213. width = _viewportWidth;
  13214. height = _viewportHeight;
  13215. vx = _viewportX;
  13216. vy = _viewportY;
  13217. }
  13218. if ( framebuffer !== _currentFramebuffer ) {
  13219. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  13220. _gl.viewport( vx, vy, width, height );
  13221. _currentFramebuffer = framebuffer;
  13222. }
  13223. _currentWidth = width;
  13224. _currentHeight = height;
  13225. };
  13226. function updateRenderTargetMipmap ( renderTarget ) {
  13227. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  13228. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  13229. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  13230. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  13231. } else {
  13232. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  13233. _gl.generateMipmap( _gl.TEXTURE_2D );
  13234. _gl.bindTexture( _gl.TEXTURE_2D, null );
  13235. }
  13236. };
  13237. // Fallback filters for non-power-of-2 textures
  13238. function filterFallback ( f ) {
  13239. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  13240. return _gl.NEAREST;
  13241. }
  13242. return _gl.LINEAR;
  13243. };
  13244. // Map three.js constants to WebGL constants
  13245. function paramThreeToGL ( p ) {
  13246. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  13247. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  13248. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  13249. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  13250. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  13251. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  13252. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  13253. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  13254. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  13255. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  13256. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  13257. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  13258. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  13259. if ( p === THREE.ByteType ) return _gl.BYTE;
  13260. if ( p === THREE.ShortType ) return _gl.SHORT;
  13261. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  13262. if ( p === THREE.IntType ) return _gl.INT;
  13263. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  13264. if ( p === THREE.FloatType ) return _gl.FLOAT;
  13265. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  13266. if ( p === THREE.RGBFormat ) return _gl.RGB;
  13267. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  13268. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  13269. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  13270. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  13271. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  13272. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  13273. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  13274. if ( p === THREE.OneFactor ) return _gl.ONE;
  13275. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  13276. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  13277. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  13278. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  13279. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  13280. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  13281. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  13282. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  13283. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  13284. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  13285. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  13286. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  13287. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  13288. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  13289. }
  13290. return 0;
  13291. };
  13292. // Allocations
  13293. function allocateBones ( object ) {
  13294. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  13295. return 1024;
  13296. } else {
  13297. // default for when object is not specified
  13298. // ( for example when prebuilding shader
  13299. // to be used with multiple objects )
  13300. //
  13301. // - leave some extra space for other uniforms
  13302. // - limit here is ANGLE's 254 max uniform vectors
  13303. // (up to 54 should be safe)
  13304. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  13305. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  13306. var maxBones = nVertexMatrices;
  13307. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  13308. maxBones = Math.min( object.bones.length, maxBones );
  13309. if ( maxBones < object.bones.length ) {
  13310. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  13311. }
  13312. }
  13313. return maxBones;
  13314. }
  13315. };
  13316. function allocateLights ( lights ) {
  13317. var l, ll, light, dirLights, pointLights, spotLights, hemiLights, maxDirLights, maxPointLights, maxSpotLights, maxHemiLights;
  13318. dirLights = pointLights = spotLights = hemiLights = maxDirLights = maxPointLights = maxSpotLights = maxHemiLights = 0;
  13319. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13320. light = lights[ l ];
  13321. if ( light.onlyShadow ) continue;
  13322. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  13323. if ( light instanceof THREE.PointLight ) pointLights ++;
  13324. if ( light instanceof THREE.SpotLight ) spotLights ++;
  13325. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  13326. }
  13327. if ( ( pointLights + spotLights + dirLights + hemiLights) <= _maxLights ) {
  13328. maxDirLights = dirLights;
  13329. maxPointLights = pointLights;
  13330. maxSpotLights = spotLights;
  13331. maxHemiLights = hemiLights;
  13332. } else {
  13333. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  13334. maxPointLights = _maxLights - maxDirLights;
  13335. // these are not really correct
  13336. maxSpotLights = maxPointLights;
  13337. maxHemiLights = maxDirLights;
  13338. }
  13339. return { 'directional' : maxDirLights, 'point' : maxPointLights, 'spot': maxSpotLights, 'hemi': maxHemiLights };
  13340. };
  13341. function allocateShadows ( lights ) {
  13342. var l, ll, light, maxShadows = 0;
  13343. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  13344. light = lights[ l ];
  13345. if ( ! light.castShadow ) continue;
  13346. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  13347. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  13348. }
  13349. return maxShadows;
  13350. };
  13351. // Initialization
  13352. function initGL () {
  13353. try {
  13354. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  13355. throw 'Error creating WebGL context.';
  13356. }
  13357. } catch ( error ) {
  13358. console.error( error );
  13359. }
  13360. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  13361. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  13362. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  13363. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  13364. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  13365. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  13366. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  13367. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  13368. if ( ! _glExtensionTextureFloat ) {
  13369. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  13370. }
  13371. if ( ! _glExtensionStandardDerivatives ) {
  13372. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  13373. }
  13374. if ( ! _glExtensionTextureFilterAnisotropic ) {
  13375. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  13376. }
  13377. if ( ! _glExtensionCompressedTextureS3TC ) {
  13378. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  13379. }
  13380. };
  13381. function setDefaultGLState () {
  13382. _gl.clearColor( 0, 0, 0, 1 );
  13383. _gl.clearDepth( 1 );
  13384. _gl.clearStencil( 0 );
  13385. _gl.enable( _gl.DEPTH_TEST );
  13386. _gl.depthFunc( _gl.LEQUAL );
  13387. _gl.frontFace( _gl.CCW );
  13388. _gl.cullFace( _gl.BACK );
  13389. _gl.enable( _gl.CULL_FACE );
  13390. _gl.enable( _gl.BLEND );
  13391. _gl.blendEquation( _gl.FUNC_ADD );
  13392. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  13393. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  13394. };
  13395. // default plugins (order is important)
  13396. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  13397. this.addPrePlugin( this.shadowMapPlugin );
  13398. this.addPostPlugin( new THREE.SpritePlugin() );
  13399. this.addPostPlugin( new THREE.LensFlarePlugin() );
  13400. };
  13401. /**
  13402. * @author szimek / https://github.com/szimek/
  13403. * @author alteredq / http://alteredqualia.com/
  13404. */
  13405. THREE.WebGLRenderTarget = function ( width, height, options ) {
  13406. this.width = width;
  13407. this.height = height;
  13408. options = options || {};
  13409. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  13410. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  13411. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  13412. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  13413. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  13414. this.offset = new THREE.Vector2( 0, 0 );
  13415. this.repeat = new THREE.Vector2( 1, 1 );
  13416. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  13417. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  13418. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  13419. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  13420. this.generateMipmaps = true;
  13421. };
  13422. THREE.WebGLRenderTarget.prototype.clone = function() {
  13423. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  13424. tmp.wrapS = this.wrapS;
  13425. tmp.wrapT = this.wrapT;
  13426. tmp.magFilter = this.magFilter;
  13427. tmp.anisotropy = this.anisotropy;
  13428. tmp.minFilter = this.minFilter;
  13429. tmp.offset.copy( this.offset );
  13430. tmp.repeat.copy( this.repeat );
  13431. tmp.format = this.format;
  13432. tmp.type = this.type;
  13433. tmp.depthBuffer = this.depthBuffer;
  13434. tmp.stencilBuffer = this.stencilBuffer;
  13435. tmp.generateMipmaps = this.generateMipmaps;
  13436. return tmp;
  13437. };
  13438. /**
  13439. * @author alteredq / http://alteredqualia.com
  13440. */
  13441. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  13442. THREE.WebGLRenderTarget.call( this, width, height, options );
  13443. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  13444. };
  13445. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  13446. /**
  13447. * @author mrdoob / http://mrdoob.com/
  13448. */
  13449. THREE.RenderableVertex = function () {
  13450. this.positionWorld = new THREE.Vector3();
  13451. this.positionScreen = new THREE.Vector4();
  13452. this.visible = true;
  13453. };
  13454. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  13455. this.positionWorld.copy( vertex.positionWorld );
  13456. this.positionScreen.copy( vertex.positionScreen );
  13457. }
  13458. /**
  13459. * @author mrdoob / http://mrdoob.com/
  13460. */
  13461. THREE.RenderableFace3 = function () {
  13462. this.v1 = new THREE.RenderableVertex();
  13463. this.v2 = new THREE.RenderableVertex();
  13464. this.v3 = new THREE.RenderableVertex();
  13465. this.centroidWorld = new THREE.Vector3();
  13466. this.centroidScreen = new THREE.Vector3();
  13467. this.normalWorld = new THREE.Vector3();
  13468. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13469. this.vertexNormalsLength = 0;
  13470. this.color = null;
  13471. this.material = null;
  13472. this.uvs = [[]];
  13473. this.z = null;
  13474. };
  13475. /**
  13476. * @author mrdoob / http://mrdoob.com/
  13477. */
  13478. THREE.RenderableFace4 = function () {
  13479. this.v1 = new THREE.RenderableVertex();
  13480. this.v2 = new THREE.RenderableVertex();
  13481. this.v3 = new THREE.RenderableVertex();
  13482. this.v4 = new THREE.RenderableVertex();
  13483. this.centroidWorld = new THREE.Vector3();
  13484. this.centroidScreen = new THREE.Vector3();
  13485. this.normalWorld = new THREE.Vector3();
  13486. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  13487. this.vertexNormalsLength = 0;
  13488. this.color = null;
  13489. this.material = null;
  13490. this.uvs = [[]];
  13491. this.z = null;
  13492. };
  13493. /**
  13494. * @author mrdoob / http://mrdoob.com/
  13495. */
  13496. THREE.RenderableObject = function () {
  13497. this.object = null;
  13498. this.z = null;
  13499. };
  13500. /**
  13501. * @author mrdoob / http://mrdoob.com/
  13502. */
  13503. THREE.RenderableParticle = function () {
  13504. this.object = null;
  13505. this.x = null;
  13506. this.y = null;
  13507. this.z = null;
  13508. this.rotation = null;
  13509. this.scale = new THREE.Vector2();
  13510. this.material = null;
  13511. };
  13512. /**
  13513. * @author mrdoob / http://mrdoob.com/
  13514. */
  13515. THREE.RenderableLine = function () {
  13516. this.z = null;
  13517. this.v1 = new THREE.RenderableVertex();
  13518. this.v2 = new THREE.RenderableVertex();
  13519. this.material = null;
  13520. };
  13521. /**
  13522. * @author alteredq / http://alteredqualia.com/
  13523. */
  13524. THREE.ColorUtils = {
  13525. adjustHSV : function ( color, h, s, v ) {
  13526. var hsv = THREE.ColorUtils.__hsv;
  13527. THREE.ColorUtils.rgbToHsv( color, hsv );
  13528. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  13529. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  13530. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  13531. color.setHSV( hsv.h, hsv.s, hsv.v );
  13532. },
  13533. // based on MochiKit implementation by Bob Ippolito
  13534. rgbToHsv : function ( color, hsv ) {
  13535. var r = color.r;
  13536. var g = color.g;
  13537. var b = color.b;
  13538. var max = Math.max( Math.max( r, g ), b );
  13539. var min = Math.min( Math.min( r, g ), b );
  13540. var hue;
  13541. var saturation;
  13542. var value = max;
  13543. if ( min === max ) {
  13544. hue = 0;
  13545. saturation = 0;
  13546. } else {
  13547. var delta = ( max - min );
  13548. saturation = delta / max;
  13549. if ( r === max ) {
  13550. hue = ( g - b ) / delta;
  13551. } else if ( g === max ) {
  13552. hue = 2 + ( ( b - r ) / delta );
  13553. } else {
  13554. hue = 4 + ( ( r - g ) / delta );
  13555. }
  13556. hue /= 6;
  13557. if ( hue < 0 ) {
  13558. hue += 1;
  13559. }
  13560. if ( hue > 1 ) {
  13561. hue -= 1;
  13562. }
  13563. }
  13564. if ( hsv === undefined ) {
  13565. hsv = { h: 0, s: 0, v: 0 };
  13566. }
  13567. hsv.h = hue;
  13568. hsv.s = saturation;
  13569. hsv.v = value;
  13570. return hsv;
  13571. }
  13572. };
  13573. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  13574. * @author mrdoob / http://mrdoob.com/
  13575. * @author alteredq / http://alteredqualia.com/
  13576. */
  13577. THREE.GeometryUtils = {
  13578. // Merge two geometries or geometry and geometry from object (using object's transform)
  13579. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  13580. var matrix, matrixRotation,
  13581. vertexOffset = geometry1.vertices.length,
  13582. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  13583. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  13584. vertices1 = geometry1.vertices,
  13585. vertices2 = geometry2.vertices,
  13586. faces1 = geometry1.faces,
  13587. faces2 = geometry2.faces,
  13588. uvs1 = geometry1.faceVertexUvs[ 0 ],
  13589. uvs2 = geometry2.faceVertexUvs[ 0 ];
  13590. var geo1MaterialsMap = {};
  13591. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  13592. var id = geometry1.materials[ i ].id;
  13593. geo1MaterialsMap[ id ] = i;
  13594. }
  13595. if ( object2 instanceof THREE.Mesh ) {
  13596. object2.matrixAutoUpdate && object2.updateMatrix();
  13597. matrix = object2.matrix;
  13598. matrixRotation = new THREE.Matrix4();
  13599. matrixRotation.extractRotation( matrix, object2.scale );
  13600. }
  13601. // vertices
  13602. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  13603. var vertex = vertices2[ i ];
  13604. var vertexCopy = vertex.clone();
  13605. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  13606. vertices1.push( vertexCopy );
  13607. }
  13608. // faces
  13609. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  13610. var face = faces2[ i ], faceCopy, normal, color,
  13611. faceVertexNormals = face.vertexNormals,
  13612. faceVertexColors = face.vertexColors;
  13613. if ( face instanceof THREE.Face3 ) {
  13614. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  13615. } else if ( face instanceof THREE.Face4 ) {
  13616. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  13617. }
  13618. faceCopy.normal.copy( face.normal );
  13619. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  13620. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  13621. normal = faceVertexNormals[ j ].clone();
  13622. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  13623. faceCopy.vertexNormals.push( normal );
  13624. }
  13625. faceCopy.color.copy( face.color );
  13626. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  13627. color = faceVertexColors[ j ];
  13628. faceCopy.vertexColors.push( color.clone() );
  13629. }
  13630. if ( face.materialIndex !== undefined ) {
  13631. var material2 = geometry2.materials[ face.materialIndex ];
  13632. var materialId2 = material2.id;
  13633. var materialIndex = geo1MaterialsMap[ materialId2 ];
  13634. if ( materialIndex === undefined ) {
  13635. materialIndex = geometry1.materials.length;
  13636. geo1MaterialsMap[ materialId2 ] = materialIndex;
  13637. geometry1.materials.push( material2 );
  13638. }
  13639. faceCopy.materialIndex = materialIndex;
  13640. }
  13641. faceCopy.centroid.copy( face.centroid );
  13642. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  13643. faces1.push( faceCopy );
  13644. }
  13645. // uvs
  13646. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  13647. var uv = uvs2[ i ], uvCopy = [];
  13648. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13649. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13650. }
  13651. uvs1.push( uvCopy );
  13652. }
  13653. },
  13654. clone: function ( geometry ) {
  13655. var cloneGeo = new THREE.Geometry();
  13656. var i, il;
  13657. var vertices = geometry.vertices,
  13658. faces = geometry.faces,
  13659. uvs = geometry.faceVertexUvs[ 0 ];
  13660. // materials
  13661. if ( geometry.materials ) {
  13662. cloneGeo.materials = geometry.materials.slice();
  13663. }
  13664. // vertices
  13665. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  13666. var vertex = vertices[ i ];
  13667. cloneGeo.vertices.push( vertex.clone() );
  13668. }
  13669. // faces
  13670. for ( i = 0, il = faces.length; i < il; i ++ ) {
  13671. var face = faces[ i ];
  13672. cloneGeo.faces.push( face.clone() );
  13673. }
  13674. // uvs
  13675. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  13676. var uv = uvs[ i ], uvCopy = [];
  13677. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  13678. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  13679. }
  13680. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  13681. }
  13682. return cloneGeo;
  13683. },
  13684. // Get random point in triangle (via barycentric coordinates)
  13685. // (uniform distribution)
  13686. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  13687. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  13688. var a, b, c,
  13689. point = new THREE.Vector3(),
  13690. tmp = THREE.GeometryUtils.__v1;
  13691. a = THREE.GeometryUtils.random();
  13692. b = THREE.GeometryUtils.random();
  13693. if ( ( a + b ) > 1 ) {
  13694. a = 1 - a;
  13695. b = 1 - b;
  13696. }
  13697. c = 1 - a - b;
  13698. point.copy( vectorA );
  13699. point.multiplyScalar( a );
  13700. tmp.copy( vectorB );
  13701. tmp.multiplyScalar( b );
  13702. point.addSelf( tmp );
  13703. tmp.copy( vectorC );
  13704. tmp.multiplyScalar( c );
  13705. point.addSelf( tmp );
  13706. return point;
  13707. },
  13708. // Get random point in face (triangle / quad)
  13709. // (uniform distribution)
  13710. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  13711. var vA, vB, vC, vD;
  13712. if ( face instanceof THREE.Face3 ) {
  13713. vA = geometry.vertices[ face.a ];
  13714. vB = geometry.vertices[ face.b ];
  13715. vC = geometry.vertices[ face.c ];
  13716. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  13717. } else if ( face instanceof THREE.Face4 ) {
  13718. vA = geometry.vertices[ face.a ];
  13719. vB = geometry.vertices[ face.b ];
  13720. vC = geometry.vertices[ face.c ];
  13721. vD = geometry.vertices[ face.d ];
  13722. var area1, area2;
  13723. if ( useCachedAreas ) {
  13724. if ( face._area1 && face._area2 ) {
  13725. area1 = face._area1;
  13726. area2 = face._area2;
  13727. } else {
  13728. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13729. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13730. face._area1 = area1;
  13731. face._area2 = area2;
  13732. }
  13733. } else {
  13734. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  13735. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13736. }
  13737. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  13738. if ( r < area1 ) {
  13739. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  13740. } else {
  13741. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  13742. }
  13743. }
  13744. },
  13745. // Get uniformly distributed random points in mesh
  13746. // - create array with cumulative sums of face areas
  13747. // - pick random number from 0 to total area
  13748. // - find corresponding place in area array by binary search
  13749. // - get random point in face
  13750. randomPointsInGeometry: function ( geometry, n ) {
  13751. var face, i,
  13752. faces = geometry.faces,
  13753. vertices = geometry.vertices,
  13754. il = faces.length,
  13755. totalArea = 0,
  13756. cumulativeAreas = [],
  13757. vA, vB, vC, vD;
  13758. // precompute face areas
  13759. for ( i = 0; i < il; i ++ ) {
  13760. face = faces[ i ];
  13761. if ( face instanceof THREE.Face3 ) {
  13762. vA = vertices[ face.a ];
  13763. vB = vertices[ face.b ];
  13764. vC = vertices[ face.c ];
  13765. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  13766. } else if ( face instanceof THREE.Face4 ) {
  13767. vA = vertices[ face.a ];
  13768. vB = vertices[ face.b ];
  13769. vC = vertices[ face.c ];
  13770. vD = vertices[ face.d ];
  13771. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  13772. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  13773. face._area = face._area1 + face._area2;
  13774. }
  13775. totalArea += face._area;
  13776. cumulativeAreas[ i ] = totalArea;
  13777. }
  13778. // binary search cumulative areas array
  13779. function binarySearchIndices( value ) {
  13780. function binarySearch( start, end ) {
  13781. // return closest larger index
  13782. // if exact number is not found
  13783. if ( end < start )
  13784. return start;
  13785. var mid = start + Math.floor( ( end - start ) / 2 );
  13786. if ( cumulativeAreas[ mid ] > value ) {
  13787. return binarySearch( start, mid - 1 );
  13788. } else if ( cumulativeAreas[ mid ] < value ) {
  13789. return binarySearch( mid + 1, end );
  13790. } else {
  13791. return mid;
  13792. }
  13793. }
  13794. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  13795. return result;
  13796. }
  13797. // pick random face weighted by face area
  13798. var r, index,
  13799. result = [];
  13800. var stats = {};
  13801. for ( i = 0; i < n; i ++ ) {
  13802. r = THREE.GeometryUtils.random() * totalArea;
  13803. index = binarySearchIndices( r );
  13804. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  13805. if ( ! stats[ index ] ) {
  13806. stats[ index ] = 1;
  13807. } else {
  13808. stats[ index ] += 1;
  13809. }
  13810. }
  13811. return result;
  13812. },
  13813. // Get triangle area (by Heron's formula)
  13814. // http://en.wikipedia.org/wiki/Heron%27s_formula
  13815. triangleArea: function ( vectorA, vectorB, vectorC ) {
  13816. var s, a, b, c,
  13817. tmp = THREE.GeometryUtils.__v1;
  13818. tmp.sub( vectorA, vectorB );
  13819. a = tmp.length();
  13820. tmp.sub( vectorA, vectorC );
  13821. b = tmp.length();
  13822. tmp.sub( vectorB, vectorC );
  13823. c = tmp.length();
  13824. s = 0.5 * ( a + b + c );
  13825. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  13826. },
  13827. // Center geometry so that 0,0,0 is in center of bounding box
  13828. center: function ( geometry ) {
  13829. geometry.computeBoundingBox();
  13830. var bb = geometry.boundingBox;
  13831. var offset = new THREE.Vector3();
  13832. offset.add( bb.min, bb.max );
  13833. offset.multiplyScalar( -0.5 );
  13834. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  13835. geometry.computeBoundingBox();
  13836. return offset;
  13837. },
  13838. // Normalize UVs to be from <0,1>
  13839. // (for now just the first set of UVs)
  13840. normalizeUVs: function ( geometry ) {
  13841. var uvSet = geometry.faceVertexUvs[ 0 ];
  13842. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  13843. var uvs = uvSet[ i ];
  13844. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  13845. // texture repeat
  13846. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  13847. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  13848. }
  13849. }
  13850. },
  13851. triangulateQuads: function ( geometry ) {
  13852. var i, il, j, jl;
  13853. var faces = [];
  13854. var faceUvs = [];
  13855. var faceVertexUvs = [];
  13856. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  13857. faceUvs[ i ] = [];
  13858. }
  13859. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13860. faceVertexUvs[ i ] = [];
  13861. }
  13862. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13863. var face = geometry.faces[ i ];
  13864. if ( face instanceof THREE.Face4 ) {
  13865. var a = face.a;
  13866. var b = face.b;
  13867. var c = face.c;
  13868. var d = face.d;
  13869. var triA = new THREE.Face3();
  13870. var triB = new THREE.Face3();
  13871. triA.color.copy( face.color );
  13872. triB.color.copy( face.color );
  13873. triA.materialIndex = face.materialIndex;
  13874. triB.materialIndex = face.materialIndex;
  13875. triA.a = a;
  13876. triA.b = b;
  13877. triA.c = d;
  13878. triB.a = b;
  13879. triB.b = c;
  13880. triB.c = d;
  13881. if ( face.vertexColors.length === 4 ) {
  13882. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  13883. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  13884. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13885. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  13886. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  13887. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  13888. }
  13889. faces.push( triA, triB );
  13890. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13891. if ( geometry.faceVertexUvs[ j ].length ) {
  13892. var uvs = geometry.faceVertexUvs[ j ][ i ];
  13893. var uvA = uvs[ 0 ];
  13894. var uvB = uvs[ 1 ];
  13895. var uvC = uvs[ 2 ];
  13896. var uvD = uvs[ 3 ];
  13897. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  13898. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  13899. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  13900. }
  13901. }
  13902. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13903. if ( geometry.faceUvs[ j ].length ) {
  13904. var faceUv = geometry.faceUvs[ j ][ i ];
  13905. faceUvs[ j ].push( faceUv, faceUv );
  13906. }
  13907. }
  13908. } else {
  13909. faces.push( face );
  13910. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  13911. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  13912. }
  13913. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  13914. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  13915. }
  13916. }
  13917. }
  13918. geometry.faces = faces;
  13919. geometry.faceUvs = faceUvs;
  13920. geometry.faceVertexUvs = faceVertexUvs;
  13921. geometry.computeCentroids();
  13922. geometry.computeFaceNormals();
  13923. geometry.computeVertexNormals();
  13924. if ( geometry.hasTangents ) geometry.computeTangents();
  13925. },
  13926. // Make all faces use unique vertices
  13927. // so that each face can be separated from others
  13928. explode: function( geometry ) {
  13929. var vertices = [];
  13930. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13931. var n = vertices.length;
  13932. var face = geometry.faces[ i ];
  13933. if ( face instanceof THREE.Face4 ) {
  13934. var a = face.a;
  13935. var b = face.b;
  13936. var c = face.c;
  13937. var d = face.d;
  13938. var va = geometry.vertices[ a ];
  13939. var vb = geometry.vertices[ b ];
  13940. var vc = geometry.vertices[ c ];
  13941. var vd = geometry.vertices[ d ];
  13942. vertices.push( va.clone() );
  13943. vertices.push( vb.clone() );
  13944. vertices.push( vc.clone() );
  13945. vertices.push( vd.clone() );
  13946. face.a = n;
  13947. face.b = n + 1;
  13948. face.c = n + 2;
  13949. face.d = n + 3;
  13950. } else {
  13951. var a = face.a;
  13952. var b = face.b;
  13953. var c = face.c;
  13954. var va = geometry.vertices[ a ];
  13955. var vb = geometry.vertices[ b ];
  13956. var vc = geometry.vertices[ c ];
  13957. vertices.push( va.clone() );
  13958. vertices.push( vb.clone() );
  13959. vertices.push( vc.clone() );
  13960. face.a = n;
  13961. face.b = n + 1;
  13962. face.c = n + 2;
  13963. }
  13964. }
  13965. geometry.vertices = vertices;
  13966. delete geometry.__tmpVertices;
  13967. },
  13968. // Break faces with edges longer than maxEdgeLength
  13969. // - not recursive
  13970. tessellate: function ( geometry, maxEdgeLength ) {
  13971. var i, il, face,
  13972. a, b, c, d,
  13973. va, vb, vc, vd,
  13974. dab, dbc, dac, dcd, dad,
  13975. m, m1, m2,
  13976. vm, vm1, vm2,
  13977. vnm, vnm1, vnm2,
  13978. vcm, vcm1, vcm2,
  13979. triA, triB,
  13980. quadA, quadB,
  13981. edge;
  13982. var faces = [];
  13983. var faceVertexUvs = [];
  13984. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  13985. faceVertexUvs[ i ] = [];
  13986. }
  13987. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  13988. face = geometry.faces[ i ];
  13989. if ( face instanceof THREE.Face3 ) {
  13990. a = face.a;
  13991. b = face.b;
  13992. c = face.c;
  13993. va = geometry.vertices[ a ];
  13994. vb = geometry.vertices[ b ];
  13995. vc = geometry.vertices[ c ];
  13996. dab = va.distanceTo( vb );
  13997. dbc = vb.distanceTo( vc );
  13998. dac = va.distanceTo( vc );
  13999. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14000. m = geometry.vertices.length;
  14001. triA = face.clone();
  14002. triB = face.clone();
  14003. if ( dab >= dbc && dab >= dac ) {
  14004. vm = va.clone();
  14005. vm.lerpSelf( vb, 0.5 );
  14006. triA.a = a;
  14007. triA.b = m;
  14008. triA.c = c;
  14009. triB.a = m;
  14010. triB.b = b;
  14011. triB.c = c;
  14012. if ( face.vertexNormals.length === 3 ) {
  14013. vnm = face.vertexNormals[ 0 ].clone();
  14014. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14015. triA.vertexNormals[ 1 ].copy( vnm );
  14016. triB.vertexNormals[ 0 ].copy( vnm );
  14017. }
  14018. if ( face.vertexColors.length === 3 ) {
  14019. vcm = face.vertexColors[ 0 ].clone();
  14020. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14021. triA.vertexColors[ 1 ].copy( vcm );
  14022. triB.vertexColors[ 0 ].copy( vcm );
  14023. }
  14024. edge = 0;
  14025. } else if ( dbc >= dab && dbc >= dac ) {
  14026. vm = vb.clone();
  14027. vm.lerpSelf( vc, 0.5 );
  14028. triA.a = a;
  14029. triA.b = b;
  14030. triA.c = m;
  14031. triB.a = m;
  14032. triB.b = c;
  14033. triB.c = a;
  14034. if ( face.vertexNormals.length === 3 ) {
  14035. vnm = face.vertexNormals[ 1 ].clone();
  14036. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14037. triA.vertexNormals[ 2 ].copy( vnm );
  14038. triB.vertexNormals[ 0 ].copy( vnm );
  14039. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14040. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14041. }
  14042. if ( face.vertexColors.length === 3 ) {
  14043. vcm = face.vertexColors[ 1 ].clone();
  14044. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14045. triA.vertexColors[ 2 ].copy( vcm );
  14046. triB.vertexColors[ 0 ].copy( vcm );
  14047. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14048. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14049. }
  14050. edge = 1;
  14051. } else {
  14052. vm = va.clone();
  14053. vm.lerpSelf( vc, 0.5 );
  14054. triA.a = a;
  14055. triA.b = b;
  14056. triA.c = m;
  14057. triB.a = m;
  14058. triB.b = b;
  14059. triB.c = c;
  14060. if ( face.vertexNormals.length === 3 ) {
  14061. vnm = face.vertexNormals[ 0 ].clone();
  14062. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14063. triA.vertexNormals[ 2 ].copy( vnm );
  14064. triB.vertexNormals[ 0 ].copy( vnm );
  14065. }
  14066. if ( face.vertexColors.length === 3 ) {
  14067. vcm = face.vertexColors[ 0 ].clone();
  14068. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14069. triA.vertexColors[ 2 ].copy( vcm );
  14070. triB.vertexColors[ 0 ].copy( vcm );
  14071. }
  14072. edge = 2;
  14073. }
  14074. faces.push( triA, triB );
  14075. geometry.vertices.push( vm );
  14076. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14077. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14078. if ( geometry.faceVertexUvs[ j ].length ) {
  14079. uvs = geometry.faceVertexUvs[ j ][ i ];
  14080. uvA = uvs[ 0 ];
  14081. uvB = uvs[ 1 ];
  14082. uvC = uvs[ 2 ];
  14083. // AB
  14084. if ( edge === 0 ) {
  14085. uvM = uvA.clone();
  14086. uvM.lerpSelf( uvB, 0.5 );
  14087. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14088. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14089. // BC
  14090. } else if ( edge === 1 ) {
  14091. uvM = uvB.clone();
  14092. uvM.lerpSelf( uvC, 0.5 );
  14093. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14094. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14095. // AC
  14096. } else {
  14097. uvM = uvA.clone();
  14098. uvM.lerpSelf( uvC, 0.5 );
  14099. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14100. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14101. }
  14102. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14103. }
  14104. }
  14105. } else {
  14106. faces.push( face );
  14107. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14108. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14109. }
  14110. }
  14111. } else {
  14112. a = face.a;
  14113. b = face.b;
  14114. c = face.c;
  14115. d = face.d;
  14116. va = geometry.vertices[ a ];
  14117. vb = geometry.vertices[ b ];
  14118. vc = geometry.vertices[ c ];
  14119. vd = geometry.vertices[ d ];
  14120. dab = va.distanceTo( vb );
  14121. dbc = vb.distanceTo( vc );
  14122. dcd = vc.distanceTo( vd );
  14123. dad = va.distanceTo( vd );
  14124. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14125. m1 = geometry.vertices.length;
  14126. m2 = geometry.vertices.length + 1;
  14127. quadA = face.clone();
  14128. quadB = face.clone();
  14129. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14130. vm1 = va.clone();
  14131. vm1.lerpSelf( vb, 0.5 );
  14132. vm2 = vc.clone();
  14133. vm2.lerpSelf( vd, 0.5 );
  14134. quadA.a = a;
  14135. quadA.b = m1;
  14136. quadA.c = m2;
  14137. quadA.d = d;
  14138. quadB.a = m1;
  14139. quadB.b = b;
  14140. quadB.c = c;
  14141. quadB.d = m2;
  14142. if ( face.vertexNormals.length === 4 ) {
  14143. vnm1 = face.vertexNormals[ 0 ].clone();
  14144. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14145. vnm2 = face.vertexNormals[ 2 ].clone();
  14146. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  14147. quadA.vertexNormals[ 1 ].copy( vnm1 );
  14148. quadA.vertexNormals[ 2 ].copy( vnm2 );
  14149. quadB.vertexNormals[ 0 ].copy( vnm1 );
  14150. quadB.vertexNormals[ 3 ].copy( vnm2 );
  14151. }
  14152. if ( face.vertexColors.length === 4 ) {
  14153. vcm1 = face.vertexColors[ 0 ].clone();
  14154. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14155. vcm2 = face.vertexColors[ 2 ].clone();
  14156. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  14157. quadA.vertexColors[ 1 ].copy( vcm1 );
  14158. quadA.vertexColors[ 2 ].copy( vcm2 );
  14159. quadB.vertexColors[ 0 ].copy( vcm1 );
  14160. quadB.vertexColors[ 3 ].copy( vcm2 );
  14161. }
  14162. edge = 0;
  14163. } else {
  14164. vm1 = vb.clone();
  14165. vm1.lerpSelf( vc, 0.5 );
  14166. vm2 = vd.clone();
  14167. vm2.lerpSelf( va, 0.5 );
  14168. quadA.a = a;
  14169. quadA.b = b;
  14170. quadA.c = m1;
  14171. quadA.d = m2;
  14172. quadB.a = m2;
  14173. quadB.b = m1;
  14174. quadB.c = c;
  14175. quadB.d = d;
  14176. if ( face.vertexNormals.length === 4 ) {
  14177. vnm1 = face.vertexNormals[ 1 ].clone();
  14178. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14179. vnm2 = face.vertexNormals[ 3 ].clone();
  14180. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  14181. quadA.vertexNormals[ 2 ].copy( vnm1 );
  14182. quadA.vertexNormals[ 3 ].copy( vnm2 );
  14183. quadB.vertexNormals[ 0 ].copy( vnm2 );
  14184. quadB.vertexNormals[ 1 ].copy( vnm1 );
  14185. }
  14186. if ( face.vertexColors.length === 4 ) {
  14187. vcm1 = face.vertexColors[ 1 ].clone();
  14188. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14189. vcm2 = face.vertexColors[ 3 ].clone();
  14190. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  14191. quadA.vertexColors[ 2 ].copy( vcm1 );
  14192. quadA.vertexColors[ 3 ].copy( vcm2 );
  14193. quadB.vertexColors[ 0 ].copy( vcm2 );
  14194. quadB.vertexColors[ 1 ].copy( vcm1 );
  14195. }
  14196. edge = 1;
  14197. }
  14198. faces.push( quadA, quadB );
  14199. geometry.vertices.push( vm1, vm2 );
  14200. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  14201. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14202. if ( geometry.faceVertexUvs[ j ].length ) {
  14203. uvs = geometry.faceVertexUvs[ j ][ i ];
  14204. uvA = uvs[ 0 ];
  14205. uvB = uvs[ 1 ];
  14206. uvC = uvs[ 2 ];
  14207. uvD = uvs[ 3 ];
  14208. // AB + CD
  14209. if ( edge === 0 ) {
  14210. uvM1 = uvA.clone();
  14211. uvM1.lerpSelf( uvB, 0.5 );
  14212. uvM2 = uvC.clone();
  14213. uvM2.lerpSelf( uvD, 0.5 );
  14214. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  14215. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  14216. // BC + AD
  14217. } else {
  14218. uvM1 = uvB.clone();
  14219. uvM1.lerpSelf( uvC, 0.5 );
  14220. uvM2 = uvD.clone();
  14221. uvM2.lerpSelf( uvA, 0.5 );
  14222. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  14223. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  14224. }
  14225. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  14226. }
  14227. }
  14228. } else {
  14229. faces.push( face );
  14230. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14231. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14232. }
  14233. }
  14234. }
  14235. }
  14236. geometry.faces = faces;
  14237. geometry.faceVertexUvs = faceVertexUvs;
  14238. }
  14239. };
  14240. THREE.GeometryUtils.random = THREE.Math.random16;
  14241. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  14242. /**
  14243. * @author alteredq / http://alteredqualia.com/
  14244. * @author mrdoob / http://mrdoob.com/
  14245. */
  14246. THREE.ImageUtils = {
  14247. crossOrigin: 'anonymous',
  14248. loadTexture: function ( url, mapping, onLoad, onError ) {
  14249. var image = new Image();
  14250. var texture = new THREE.Texture( image, mapping );
  14251. var loader = new THREE.ImageLoader();
  14252. loader.addEventListener( 'load', function ( event ) {
  14253. texture.image = event.content;
  14254. texture.needsUpdate = true;
  14255. if ( onLoad ) onLoad( texture );
  14256. } );
  14257. loader.addEventListener( 'error', function ( event ) {
  14258. if ( onError ) onError( event.message );
  14259. } );
  14260. loader.crossOrigin = this.crossOrigin;
  14261. loader.load( url, image );
  14262. return texture;
  14263. },
  14264. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  14265. var texture = new THREE.CompressedTexture();
  14266. texture.mapping = mapping;
  14267. var request = new XMLHttpRequest();
  14268. request.onload = function () {
  14269. var buffer = request.response;
  14270. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14271. texture.format = dds.format;
  14272. texture.mipmaps = dds.mipmaps;
  14273. texture.image.width = dds.width;
  14274. texture.image.height = dds.height;
  14275. // gl.generateMipmap fails for compressed textures
  14276. // mipmaps must be embedded in the DDS file
  14277. // or texture filters must not use mipmapping
  14278. texture.generateMipmaps = false;
  14279. texture.needsUpdate = true;
  14280. if ( onLoad ) onLoad( texture );
  14281. }
  14282. request.onerror = onError;
  14283. request.open( 'GET', url, true );
  14284. request.responseType = "arraybuffer";
  14285. request.send( null );
  14286. return texture;
  14287. },
  14288. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  14289. var images = [];
  14290. images.loadCount = 0;
  14291. var texture = new THREE.Texture();
  14292. texture.image = images;
  14293. if ( mapping !== undefined ) texture.mapping = mapping;
  14294. // no flipping needed for cube textures
  14295. texture.flipY = false;
  14296. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14297. var cubeImage = new Image();
  14298. images[ i ] = cubeImage;
  14299. cubeImage.onload = function () {
  14300. images.loadCount += 1;
  14301. if ( images.loadCount === 6 ) {
  14302. texture.needsUpdate = true;
  14303. if ( onLoad ) onLoad();
  14304. }
  14305. };
  14306. cubeImage.onerror = onError;
  14307. cubeImage.crossOrigin = this.crossOrigin;
  14308. cubeImage.src = array[ i ];
  14309. }
  14310. return texture;
  14311. },
  14312. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  14313. var images = [];
  14314. images.loadCount = 0;
  14315. var texture = new THREE.CompressedTexture();
  14316. texture.image = images;
  14317. if ( mapping !== undefined ) texture.mapping = mapping;
  14318. // no flipping for cube textures
  14319. // (also flipping doesn't work for compressed textures )
  14320. texture.flipY = false;
  14321. // can't generate mipmaps for compressed textures
  14322. // mips must be embedded in DDS files
  14323. texture.generateMipmaps = false;
  14324. var generateCubeFaceCallback = function ( rq, img ) {
  14325. return function () {
  14326. var buffer = rq.response;
  14327. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  14328. img.format = dds.format;
  14329. img.mipmaps = dds.mipmaps;
  14330. img.width = dds.width;
  14331. img.height = dds.height;
  14332. images.loadCount += 1;
  14333. if ( images.loadCount === 6 ) {
  14334. texture.format = dds.format;
  14335. texture.needsUpdate = true;
  14336. if ( onLoad ) onLoad();
  14337. }
  14338. }
  14339. }
  14340. for ( var i = 0, il = array.length; i < il; ++ i ) {
  14341. var cubeImage = {};
  14342. images[ i ] = cubeImage;
  14343. var request = new XMLHttpRequest();
  14344. request.onload = generateCubeFaceCallback( request, cubeImage );
  14345. request.onerror = onError;
  14346. var url = array[ i ];
  14347. request.open( 'GET', url, true );
  14348. request.responseType = "arraybuffer";
  14349. request.send( null );
  14350. }
  14351. return texture;
  14352. },
  14353. parseDDS: function ( buffer, loadMipmaps ) {
  14354. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  14355. // Adapted from @toji's DDS utils
  14356. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  14357. // All values and structures referenced from:
  14358. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  14359. var DDS_MAGIC = 0x20534444;
  14360. var DDSD_CAPS = 0x1,
  14361. DDSD_HEIGHT = 0x2,
  14362. DDSD_WIDTH = 0x4,
  14363. DDSD_PITCH = 0x8,
  14364. DDSD_PIXELFORMAT = 0x1000,
  14365. DDSD_MIPMAPCOUNT = 0x20000,
  14366. DDSD_LINEARSIZE = 0x80000,
  14367. DDSD_DEPTH = 0x800000;
  14368. var DDSCAPS_COMPLEX = 0x8,
  14369. DDSCAPS_MIPMAP = 0x400000,
  14370. DDSCAPS_TEXTURE = 0x1000;
  14371. var DDSCAPS2_CUBEMAP = 0x200,
  14372. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  14373. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  14374. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  14375. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  14376. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  14377. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  14378. DDSCAPS2_VOLUME = 0x200000;
  14379. var DDPF_ALPHAPIXELS = 0x1,
  14380. DDPF_ALPHA = 0x2,
  14381. DDPF_FOURCC = 0x4,
  14382. DDPF_RGB = 0x40,
  14383. DDPF_YUV = 0x200,
  14384. DDPF_LUMINANCE = 0x20000;
  14385. function fourCCToInt32( value ) {
  14386. return value.charCodeAt(0) +
  14387. (value.charCodeAt(1) << 8) +
  14388. (value.charCodeAt(2) << 16) +
  14389. (value.charCodeAt(3) << 24);
  14390. }
  14391. function int32ToFourCC( value ) {
  14392. return String.fromCharCode(
  14393. value & 0xff,
  14394. (value >> 8) & 0xff,
  14395. (value >> 16) & 0xff,
  14396. (value >> 24) & 0xff
  14397. );
  14398. }
  14399. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  14400. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  14401. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  14402. var headerLengthInt = 31; // The header length in 32 bit ints
  14403. // Offsets into the header array
  14404. var off_magic = 0;
  14405. var off_size = 1;
  14406. var off_flags = 2;
  14407. var off_height = 3;
  14408. var off_width = 4;
  14409. var off_mipmapCount = 7;
  14410. var off_pfFlags = 20;
  14411. var off_pfFourCC = 21;
  14412. // Parse header
  14413. var header = new Int32Array( buffer, 0, headerLengthInt );
  14414. if ( header[ off_magic ] !== DDS_MAGIC ) {
  14415. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  14416. return dds;
  14417. }
  14418. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  14419. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  14420. return dds;
  14421. }
  14422. var blockBytes;
  14423. var fourCC = header[ off_pfFourCC ];
  14424. switch ( fourCC ) {
  14425. case FOURCC_DXT1:
  14426. blockBytes = 8;
  14427. dds.format = THREE.RGB_S3TC_DXT1_Format;
  14428. break;
  14429. case FOURCC_DXT3:
  14430. blockBytes = 16;
  14431. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  14432. break;
  14433. case FOURCC_DXT5:
  14434. blockBytes = 16;
  14435. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  14436. break;
  14437. default:
  14438. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  14439. return dds;
  14440. }
  14441. dds.mipmapCount = 1;
  14442. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  14443. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  14444. }
  14445. dds.width = header[ off_width ];
  14446. dds.height = header[ off_height ];
  14447. var dataOffset = header[ off_size ] + 4;
  14448. // Extract mipmaps buffers
  14449. var width = dds.width;
  14450. var height = dds.height;
  14451. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  14452. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  14453. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  14454. var mipmap = { "data": byteArray, "width": width, "height": height };
  14455. dds.mipmaps.push( mipmap );
  14456. dataOffset += dataLength;
  14457. width = Math.max( width * 0.5, 1 );
  14458. height = Math.max( height * 0.5, 1 );
  14459. }
  14460. return dds;
  14461. },
  14462. getNormalMap: function ( image, depth ) {
  14463. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  14464. var cross = function ( a, b ) {
  14465. 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 ] ];
  14466. }
  14467. var subtract = function ( a, b ) {
  14468. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  14469. }
  14470. var normalize = function ( a ) {
  14471. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  14472. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  14473. }
  14474. depth = depth | 1;
  14475. var width = image.width;
  14476. var height = image.height;
  14477. var canvas = document.createElement( 'canvas' );
  14478. canvas.width = width;
  14479. canvas.height = height;
  14480. var context = canvas.getContext( '2d' );
  14481. context.drawImage( image, 0, 0 );
  14482. var data = context.getImageData( 0, 0, width, height ).data;
  14483. var imageData = context.createImageData( width, height );
  14484. var output = imageData.data;
  14485. for ( var x = 0; x < width; x ++ ) {
  14486. for ( var y = 0; y < height; y ++ ) {
  14487. var ly = y - 1 < 0 ? 0 : y - 1;
  14488. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  14489. var lx = x - 1 < 0 ? 0 : x - 1;
  14490. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  14491. var points = [];
  14492. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  14493. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  14494. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  14495. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  14496. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  14497. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  14498. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  14499. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  14500. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  14501. var normals = [];
  14502. var num_points = points.length;
  14503. for ( var i = 0; i < num_points; i ++ ) {
  14504. var v1 = points[ i ];
  14505. var v2 = points[ ( i + 1 ) % num_points ];
  14506. v1 = subtract( v1, origin );
  14507. v2 = subtract( v2, origin );
  14508. normals.push( normalize( cross( v1, v2 ) ) );
  14509. }
  14510. var normal = [ 0, 0, 0 ];
  14511. for ( var i = 0; i < normals.length; i ++ ) {
  14512. normal[ 0 ] += normals[ i ][ 0 ];
  14513. normal[ 1 ] += normals[ i ][ 1 ];
  14514. normal[ 2 ] += normals[ i ][ 2 ];
  14515. }
  14516. normal[ 0 ] /= normals.length;
  14517. normal[ 1 ] /= normals.length;
  14518. normal[ 2 ] /= normals.length;
  14519. var idx = ( y * width + x ) * 4;
  14520. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14521. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  14522. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  14523. output[ idx + 3 ] = 255;
  14524. }
  14525. }
  14526. context.putImageData( imageData, 0, 0 );
  14527. return canvas;
  14528. },
  14529. generateDataTexture: function ( width, height, color ) {
  14530. var size = width * height;
  14531. var data = new Uint8Array( 3 * size );
  14532. var r = Math.floor( color.r * 255 );
  14533. var g = Math.floor( color.g * 255 );
  14534. var b = Math.floor( color.b * 255 );
  14535. for ( var i = 0; i < size; i ++ ) {
  14536. data[ i * 3 ] = r;
  14537. data[ i * 3 + 1 ] = g;
  14538. data[ i * 3 + 2 ] = b;
  14539. }
  14540. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  14541. texture.needsUpdate = true;
  14542. return texture;
  14543. }
  14544. };
  14545. /**
  14546. * @author alteredq / http://alteredqualia.com/
  14547. */
  14548. THREE.SceneUtils = {
  14549. createMultiMaterialObject: function ( geometry, materials ) {
  14550. var group = new THREE.Object3D();
  14551. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  14552. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  14553. }
  14554. return group;
  14555. },
  14556. detach : function ( child, parent, scene ) {
  14557. child.applyMatrix( parent.matrixWorld );
  14558. parent.remove( child );
  14559. scene.add( child );
  14560. },
  14561. attach: function ( child, scene, parent ) {
  14562. var matrixWorldInverse = new THREE.Matrix4();
  14563. matrixWorldInverse.getInverse( parent.matrixWorld );
  14564. child.applyMatrix( matrixWorldInverse );
  14565. scene.remove( child );
  14566. parent.add( child );
  14567. }
  14568. };
  14569. /**
  14570. * @author alteredq / http://alteredqualia.com/
  14571. * @author mrdoob / http://mrdoob.com/
  14572. *
  14573. * ShaderUtils currently contains:
  14574. *
  14575. * fresnel
  14576. * normal
  14577. * cube
  14578. *
  14579. */
  14580. if ( THREE.WebGLRenderer ) {
  14581. THREE.ShaderUtils = {
  14582. lib: {
  14583. /* -------------------------------------------------------------------------
  14584. // Fresnel shader
  14585. // - based on Nvidia Cg tutorial
  14586. ------------------------------------------------------------------------- */
  14587. 'fresnel': {
  14588. uniforms: {
  14589. "mRefractionRatio": { type: "f", value: 1.02 },
  14590. "mFresnelBias": { type: "f", value: 0.1 },
  14591. "mFresnelPower": { type: "f", value: 2.0 },
  14592. "mFresnelScale": { type: "f", value: 1.0 },
  14593. "tCube": { type: "t", value: null }
  14594. },
  14595. fragmentShader: [
  14596. "uniform samplerCube tCube;",
  14597. "varying vec3 vReflect;",
  14598. "varying vec3 vRefract[3];",
  14599. "varying float vReflectionFactor;",
  14600. "void main() {",
  14601. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14602. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  14603. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  14604. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  14605. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  14606. "refractedColor.a = 1.0;",
  14607. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  14608. "}"
  14609. ].join("\n"),
  14610. vertexShader: [
  14611. "uniform float mRefractionRatio;",
  14612. "uniform float mFresnelBias;",
  14613. "uniform float mFresnelScale;",
  14614. "uniform float mFresnelPower;",
  14615. "varying vec3 vReflect;",
  14616. "varying vec3 vRefract[3];",
  14617. "varying float vReflectionFactor;",
  14618. "void main() {",
  14619. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  14620. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  14621. "vec3 nWorld = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  14622. "vec3 I = mPosition.xyz - cameraPosition;",
  14623. "vReflect = reflect( I, nWorld );",
  14624. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  14625. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  14626. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  14627. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  14628. "gl_Position = projectionMatrix * mvPosition;",
  14629. "}"
  14630. ].join("\n")
  14631. },
  14632. /* -------------------------------------------------------------------------
  14633. // Normal map shader
  14634. // - Blinn-Phong
  14635. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  14636. // - point and directional lights (use with "lights: true" material option)
  14637. ------------------------------------------------------------------------- */
  14638. 'normal' : {
  14639. uniforms: THREE.UniformsUtils.merge( [
  14640. THREE.UniformsLib[ "fog" ],
  14641. THREE.UniformsLib[ "lights" ],
  14642. THREE.UniformsLib[ "shadowmap" ],
  14643. {
  14644. "enableAO" : { type: "i", value: 0 },
  14645. "enableDiffuse" : { type: "i", value: 0 },
  14646. "enableSpecular" : { type: "i", value: 0 },
  14647. "enableReflection": { type: "i", value: 0 },
  14648. "enableDisplacement": { type: "i", value: 0 },
  14649. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  14650. "tDiffuse" : { type: "t", value: null },
  14651. "tCube" : { type: "t", value: null },
  14652. "tNormal" : { type: "t", value: null },
  14653. "tSpecular" : { type: "t", value: null },
  14654. "tAO" : { type: "t", value: null },
  14655. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14656. "uDisplacementBias": { type: "f", value: 0.0 },
  14657. "uDisplacementScale": { type: "f", value: 1.0 },
  14658. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14659. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  14660. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  14661. "uShininess": { type: "f", value: 30 },
  14662. "uOpacity": { type: "f", value: 1 },
  14663. "useRefract": { type: "i", value: 0 },
  14664. "uRefractionRatio": { type: "f", value: 0.98 },
  14665. "uReflectivity": { type: "f", value: 0.5 },
  14666. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  14667. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  14668. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  14669. }
  14670. ] ),
  14671. fragmentShader: [
  14672. "uniform vec3 uAmbientColor;",
  14673. "uniform vec3 uDiffuseColor;",
  14674. "uniform vec3 uSpecularColor;",
  14675. "uniform float uShininess;",
  14676. "uniform float uOpacity;",
  14677. "uniform bool enableDiffuse;",
  14678. "uniform bool enableSpecular;",
  14679. "uniform bool enableAO;",
  14680. "uniform bool enableReflection;",
  14681. "uniform sampler2D tDiffuse;",
  14682. "uniform sampler2D tNormal;",
  14683. "uniform sampler2D tSpecular;",
  14684. "uniform sampler2D tAO;",
  14685. "uniform samplerCube tCube;",
  14686. "uniform vec2 uNormalScale;",
  14687. "uniform bool useRefract;",
  14688. "uniform float uRefractionRatio;",
  14689. "uniform float uReflectivity;",
  14690. "varying vec3 vTangent;",
  14691. "varying vec3 vBinormal;",
  14692. "varying vec3 vNormal;",
  14693. "varying vec2 vUv;",
  14694. "uniform vec3 ambientLightColor;",
  14695. "#if MAX_DIR_LIGHTS > 0",
  14696. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  14697. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  14698. "#endif",
  14699. "#if MAX_HEMI_LIGHTS > 0",
  14700. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  14701. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  14702. "uniform vec3 hemisphereLightPosition[ MAX_HEMI_LIGHTS ];",
  14703. "#endif",
  14704. "#if MAX_POINT_LIGHTS > 0",
  14705. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  14706. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  14707. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  14708. "#endif",
  14709. "#if MAX_SPOT_LIGHTS > 0",
  14710. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  14711. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  14712. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  14713. "uniform float spotLightAngle[ MAX_SPOT_LIGHTS ];",
  14714. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  14715. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  14716. "#endif",
  14717. "#ifdef WRAP_AROUND",
  14718. "uniform vec3 wrapRGB;",
  14719. "#endif",
  14720. "varying vec3 vWorldPosition;",
  14721. "varying vec3 vViewPosition;",
  14722. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  14723. THREE.ShaderChunk[ "fog_pars_fragment" ],
  14724. "void main() {",
  14725. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  14726. "vec3 specularTex = vec3( 1.0 );",
  14727. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  14728. "normalTex.xy *= uNormalScale;",
  14729. "normalTex = normalize( normalTex );",
  14730. "if( enableDiffuse ) {",
  14731. "#ifdef GAMMA_INPUT",
  14732. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  14733. "texelColor.xyz *= texelColor.xyz;",
  14734. "gl_FragColor = gl_FragColor * texelColor;",
  14735. "#else",
  14736. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  14737. "#endif",
  14738. "}",
  14739. "if( enableAO ) {",
  14740. "#ifdef GAMMA_INPUT",
  14741. "vec4 aoColor = texture2D( tAO, vUv );",
  14742. "aoColor.xyz *= aoColor.xyz;",
  14743. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  14744. "#else",
  14745. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  14746. "#endif",
  14747. "}",
  14748. "if( enableSpecular )",
  14749. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  14750. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  14751. "vec3 finalNormal = tsb * normalTex;",
  14752. "#ifdef FLIP_SIDED",
  14753. "finalNormal = -finalNormal;",
  14754. "#endif",
  14755. "vec3 normal = normalize( finalNormal );",
  14756. "vec3 viewPosition = normalize( vViewPosition );",
  14757. // point lights
  14758. "#if MAX_POINT_LIGHTS > 0",
  14759. "vec3 pointDiffuse = vec3( 0.0 );",
  14760. "vec3 pointSpecular = vec3( 0.0 );",
  14761. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  14762. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  14763. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  14764. "float pointDistance = 1.0;",
  14765. "if ( pointLightDistance[ i ] > 0.0 )",
  14766. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  14767. "pointVector = normalize( pointVector );",
  14768. // diffuse
  14769. "#ifdef WRAP_AROUND",
  14770. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  14771. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  14772. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  14773. "#else",
  14774. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  14775. "#endif",
  14776. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  14777. // specular
  14778. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  14779. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  14780. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  14781. "#ifdef PHYSICALLY_BASED_SHADING",
  14782. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14783. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14784. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  14785. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  14786. "#else",
  14787. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  14788. "#endif",
  14789. "}",
  14790. "#endif",
  14791. // spot lights
  14792. "#if MAX_SPOT_LIGHTS > 0",
  14793. "vec3 spotDiffuse = vec3( 0.0 );",
  14794. "vec3 spotSpecular = vec3( 0.0 );",
  14795. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  14796. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  14797. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  14798. "float spotDistance = 1.0;",
  14799. "if ( spotLightDistance[ i ] > 0.0 )",
  14800. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  14801. "spotVector = normalize( spotVector );",
  14802. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  14803. "if ( spotEffect > spotLightAngle[ i ] ) {",
  14804. "spotEffect = pow( spotEffect, spotLightExponent[ i ] );",
  14805. // diffuse
  14806. "#ifdef WRAP_AROUND",
  14807. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  14808. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  14809. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  14810. "#else",
  14811. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  14812. "#endif",
  14813. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  14814. // specular
  14815. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  14816. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  14817. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  14818. "#ifdef PHYSICALLY_BASED_SHADING",
  14819. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14820. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14821. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  14822. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  14823. "#else",
  14824. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  14825. "#endif",
  14826. "}",
  14827. "}",
  14828. "#endif",
  14829. // directional lights
  14830. "#if MAX_DIR_LIGHTS > 0",
  14831. "vec3 dirDiffuse = vec3( 0.0 );",
  14832. "vec3 dirSpecular = vec3( 0.0 );",
  14833. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  14834. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  14835. "vec3 dirVector = normalize( lDirection.xyz );",
  14836. // diffuse
  14837. "#ifdef WRAP_AROUND",
  14838. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  14839. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  14840. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  14841. "#else",
  14842. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  14843. "#endif",
  14844. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  14845. // specular
  14846. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  14847. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  14848. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  14849. "#ifdef PHYSICALLY_BASED_SHADING",
  14850. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14851. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14852. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  14853. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  14854. "#else",
  14855. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  14856. "#endif",
  14857. "}",
  14858. "#endif",
  14859. // hemisphere lights
  14860. "#if MAX_HEMI_LIGHTS > 0",
  14861. "vec3 hemiDiffuse = vec3( 0.0 );",
  14862. "vec3 hemiSpecular = vec3( 0.0 );" ,
  14863. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  14864. "vec4 lPosition = viewMatrix * vec4( hemisphereLightPosition[ i ], 1.0 );",
  14865. "vec3 lVector = normalize( lPosition.xyz + vViewPosition.xyz );",
  14866. // diffuse
  14867. "float dotProduct = dot( normal, lVector );",
  14868. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  14869. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  14870. "hemiDiffuse += uDiffuseColor * hemiColor;",
  14871. // specular (sky light)
  14872. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  14873. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  14874. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  14875. // specular (ground light)
  14876. "vec3 lVectorGround = normalize( -lPosition.xyz + vViewPosition.xyz );",
  14877. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  14878. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  14879. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  14880. "#ifdef PHYSICALLY_BASED_SHADING",
  14881. "float dotProductGround = dot( normal, lVectorGround );",
  14882. // 2.0 => 2.0001 is hack to work around ANGLE bug
  14883. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  14884. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  14885. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  14886. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  14887. "#else",
  14888. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  14889. "#endif",
  14890. "}",
  14891. "#endif",
  14892. // all lights contribution summation
  14893. "vec3 totalDiffuse = vec3( 0.0 );",
  14894. "vec3 totalSpecular = vec3( 0.0 );",
  14895. "#if MAX_DIR_LIGHTS > 0",
  14896. "totalDiffuse += dirDiffuse;",
  14897. "totalSpecular += dirSpecular;",
  14898. "#endif",
  14899. "#if MAX_HEMI_LIGHTS > 0",
  14900. "totalDiffuse += hemiDiffuse;",
  14901. "totalSpecular += hemiSpecular;",
  14902. "#endif",
  14903. "#if MAX_POINT_LIGHTS > 0",
  14904. "totalDiffuse += pointDiffuse;",
  14905. "totalSpecular += pointSpecular;",
  14906. "#endif",
  14907. "#if MAX_SPOT_LIGHTS > 0",
  14908. "totalDiffuse += spotDiffuse;",
  14909. "totalSpecular += spotSpecular;",
  14910. "#endif",
  14911. "#ifdef METAL",
  14912. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  14913. "#else",
  14914. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  14915. "#endif",
  14916. "if ( enableReflection ) {",
  14917. "vec3 vReflect;",
  14918. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  14919. "if ( useRefract ) {",
  14920. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  14921. "} else {",
  14922. "vReflect = reflect( cameraToVertex, normal );",
  14923. "}",
  14924. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  14925. "#ifdef GAMMA_INPUT",
  14926. "cubeColor.xyz *= cubeColor.xyz;",
  14927. "#endif",
  14928. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  14929. "}",
  14930. THREE.ShaderChunk[ "shadowmap_fragment" ],
  14931. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  14932. THREE.ShaderChunk[ "fog_fragment" ],
  14933. "}"
  14934. ].join("\n"),
  14935. vertexShader: [
  14936. "attribute vec4 tangent;",
  14937. "uniform vec2 uOffset;",
  14938. "uniform vec2 uRepeat;",
  14939. "uniform bool enableDisplacement;",
  14940. "#ifdef VERTEX_TEXTURES",
  14941. "uniform sampler2D tDisplacement;",
  14942. "uniform float uDisplacementScale;",
  14943. "uniform float uDisplacementBias;",
  14944. "#endif",
  14945. "varying vec3 vTangent;",
  14946. "varying vec3 vBinormal;",
  14947. "varying vec3 vNormal;",
  14948. "varying vec2 vUv;",
  14949. "varying vec3 vWorldPosition;",
  14950. "varying vec3 vViewPosition;",
  14951. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  14952. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  14953. "void main() {",
  14954. THREE.ShaderChunk[ "skinbase_vertex" ],
  14955. THREE.ShaderChunk[ "skinnormal_vertex" ],
  14956. // normal, tangent and binormal vectors
  14957. "#ifdef USE_SKINNING",
  14958. "vNormal = normalMatrix * skinnedNormal.xyz;",
  14959. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  14960. "vTangent = normalMatrix * skinnedTangent.xyz;",
  14961. "#else",
  14962. "vNormal = normalMatrix * normal;",
  14963. "vTangent = normalMatrix * tangent.xyz;",
  14964. "#endif",
  14965. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  14966. "vUv = uv * uRepeat + uOffset;",
  14967. // displacement mapping
  14968. "vec3 displacedPosition;",
  14969. "#ifdef VERTEX_TEXTURES",
  14970. "if ( enableDisplacement ) {",
  14971. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  14972. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  14973. "displacedPosition = position + normalize( normal ) * df;",
  14974. "} else {",
  14975. "#ifdef USE_SKINNING",
  14976. "vec4 skinVertex = vec4( position, 1.0 );",
  14977. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14978. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14979. "displacedPosition = skinned.xyz;",
  14980. "#else",
  14981. "displacedPosition = position;",
  14982. "#endif",
  14983. "}",
  14984. "#else",
  14985. "#ifdef USE_SKINNING",
  14986. "vec4 skinVertex = vec4( position, 1.0 );",
  14987. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  14988. "skinned += boneMatY * skinVertex * skinWeight.y;",
  14989. "displacedPosition = skinned.xyz;",
  14990. "#else",
  14991. "displacedPosition = position;",
  14992. "#endif",
  14993. "#endif",
  14994. //
  14995. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  14996. "vec4 mPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  14997. "gl_Position = projectionMatrix * mvPosition;",
  14998. //
  14999. "vWorldPosition = mPosition.xyz;",
  15000. "vViewPosition = -mvPosition.xyz;",
  15001. // shadows
  15002. "#ifdef USE_SHADOWMAP",
  15003. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15004. "vShadowCoord[ i ] = shadowMatrix[ i ] * mPosition;",
  15005. "}",
  15006. "#endif",
  15007. "}"
  15008. ].join("\n")
  15009. },
  15010. /* -------------------------------------------------------------------------
  15011. // Cube map shader
  15012. ------------------------------------------------------------------------- */
  15013. 'cube': {
  15014. uniforms: { "tCube": { type: "t", value: null },
  15015. "tFlip": { type: "f", value: -1 } },
  15016. vertexShader: [
  15017. "varying vec3 vViewPosition;",
  15018. "void main() {",
  15019. "vec4 mPosition = modelMatrix * vec4( position, 1.0 );",
  15020. "vViewPosition = cameraPosition - mPosition.xyz;",
  15021. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15022. "}"
  15023. ].join("\n"),
  15024. fragmentShader: [
  15025. "uniform samplerCube tCube;",
  15026. "uniform float tFlip;",
  15027. "varying vec3 vViewPosition;",
  15028. "void main() {",
  15029. "vec3 wPos = cameraPosition - vViewPosition;",
  15030. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  15031. "}"
  15032. ].join("\n")
  15033. }
  15034. }
  15035. };
  15036. };
  15037. /**
  15038. * @author zz85 / http://www.lab4games.net/zz85/blog
  15039. * @author alteredq / http://alteredqualia.com/
  15040. *
  15041. * For Text operations in three.js (See TextGeometry)
  15042. *
  15043. * It uses techniques used in:
  15044. *
  15045. * typeface.js and canvastext
  15046. * For converting fonts and rendering with javascript
  15047. * http://typeface.neocracy.org
  15048. *
  15049. * Triangulation ported from AS3
  15050. * Simple Polygon Triangulation
  15051. * http://actionsnippet.com/?p=1462
  15052. *
  15053. * A Method to triangulate shapes with holes
  15054. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15055. *
  15056. */
  15057. THREE.FontUtils = {
  15058. faces : {},
  15059. // Just for now. face[weight][style]
  15060. face : "helvetiker",
  15061. weight: "normal",
  15062. style : "normal",
  15063. size : 150,
  15064. divisions : 10,
  15065. getFace : function() {
  15066. return this.faces[ this.face ][ this.weight ][ this.style ];
  15067. },
  15068. loadFace : function( data ) {
  15069. var family = data.familyName.toLowerCase();
  15070. var ThreeFont = this;
  15071. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15072. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15073. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15074. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15075. return data;
  15076. },
  15077. drawText : function( text ) {
  15078. var characterPts = [], allPts = [];
  15079. // RenderText
  15080. var i, p,
  15081. face = this.getFace(),
  15082. scale = this.size / face.resolution,
  15083. offset = 0,
  15084. chars = String( text ).split( '' ),
  15085. length = chars.length;
  15086. var fontPaths = [];
  15087. for ( i = 0; i < length; i ++ ) {
  15088. var path = new THREE.Path();
  15089. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15090. offset += ret.offset;
  15091. fontPaths.push( ret.path );
  15092. }
  15093. // get the width
  15094. var width = offset / 2;
  15095. //
  15096. // for ( p = 0; p < allPts.length; p++ ) {
  15097. //
  15098. // allPts[ p ].x -= width;
  15099. //
  15100. // }
  15101. //var extract = this.extractPoints( allPts, characterPts );
  15102. //extract.contour = allPts;
  15103. //extract.paths = fontPaths;
  15104. //extract.offset = width;
  15105. return { paths : fontPaths, offset : width };
  15106. },
  15107. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15108. var pts = [];
  15109. var i, i2, divisions,
  15110. outline, action, length,
  15111. scaleX, scaleY,
  15112. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15113. laste,
  15114. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15115. if ( !glyph ) return;
  15116. if ( glyph.o ) {
  15117. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15118. length = outline.length;
  15119. scaleX = scale;
  15120. scaleY = scale;
  15121. for ( i = 0; i < length; ) {
  15122. action = outline[ i ++ ];
  15123. //console.log( action );
  15124. switch( action ) {
  15125. case 'm':
  15126. // Move To
  15127. x = outline[ i++ ] * scaleX + offset;
  15128. y = outline[ i++ ] * scaleY;
  15129. path.moveTo( x, y );
  15130. break;
  15131. case 'l':
  15132. // Line To
  15133. x = outline[ i++ ] * scaleX + offset;
  15134. y = outline[ i++ ] * scaleY;
  15135. path.lineTo(x,y);
  15136. break;
  15137. case 'q':
  15138. // QuadraticCurveTo
  15139. cpx = outline[ i++ ] * scaleX + offset;
  15140. cpy = outline[ i++ ] * scaleY;
  15141. cpx1 = outline[ i++ ] * scaleX + offset;
  15142. cpy1 = outline[ i++ ] * scaleY;
  15143. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15144. laste = pts[ pts.length - 1 ];
  15145. if ( laste ) {
  15146. cpx0 = laste.x;
  15147. cpy0 = laste.y;
  15148. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15149. var t = i2 / divisions;
  15150. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15151. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15152. }
  15153. }
  15154. break;
  15155. case 'b':
  15156. // Cubic Bezier Curve
  15157. cpx = outline[ i++ ] * scaleX + offset;
  15158. cpy = outline[ i++ ] * scaleY;
  15159. cpx1 = outline[ i++ ] * scaleX + offset;
  15160. cpy1 = outline[ i++ ] * -scaleY;
  15161. cpx2 = outline[ i++ ] * scaleX + offset;
  15162. cpy2 = outline[ i++ ] * -scaleY;
  15163. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15164. laste = pts[ pts.length - 1 ];
  15165. if ( laste ) {
  15166. cpx0 = laste.x;
  15167. cpy0 = laste.y;
  15168. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15169. var t = i2 / divisions;
  15170. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15171. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15172. }
  15173. }
  15174. break;
  15175. }
  15176. }
  15177. }
  15178. return { offset: glyph.ha*scale, path:path};
  15179. }
  15180. };
  15181. THREE.FontUtils.generateShapes = function( text, parameters ) {
  15182. // Parameters
  15183. parameters = parameters || {};
  15184. var size = parameters.size !== undefined ? parameters.size : 100;
  15185. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  15186. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  15187. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  15188. var style = parameters.style !== undefined ? parameters.style : "normal";
  15189. THREE.FontUtils.size = size;
  15190. THREE.FontUtils.divisions = curveSegments;
  15191. THREE.FontUtils.face = font;
  15192. THREE.FontUtils.weight = weight;
  15193. THREE.FontUtils.style = style;
  15194. // Get a Font data json object
  15195. var data = THREE.FontUtils.drawText( text );
  15196. var paths = data.paths;
  15197. var shapes = [];
  15198. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  15199. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  15200. }
  15201. return shapes;
  15202. };
  15203. /**
  15204. * This code is a quick port of code written in C++ which was submitted to
  15205. * flipcode.com by John W. Ratcliff // July 22, 2000
  15206. * See original code and more information here:
  15207. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15208. *
  15209. * ported to actionscript by Zevan Rosser
  15210. * www.actionsnippet.com
  15211. *
  15212. * ported to javascript by Joshua Koo
  15213. * http://www.lab4games.net/zz85/blog
  15214. *
  15215. */
  15216. ( function( namespace ) {
  15217. var EPSILON = 0.0000000001;
  15218. // takes in an contour array and returns
  15219. var process = function( contour, indices ) {
  15220. var n = contour.length;
  15221. if ( n < 3 ) return null;
  15222. var result = [],
  15223. verts = [],
  15224. vertIndices = [];
  15225. /* we want a counter-clockwise polygon in verts */
  15226. var u, v, w;
  15227. if ( area( contour ) > 0.0 ) {
  15228. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15229. } else {
  15230. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15231. }
  15232. var nv = n;
  15233. /* remove nv - 2 vertices, creating 1 triangle every time */
  15234. var count = 2 * nv; /* error detection */
  15235. for( v = nv - 1; nv > 2; ) {
  15236. /* if we loop, it is probably a non-simple polygon */
  15237. if ( ( count-- ) <= 0 ) {
  15238. //** Triangulate: ERROR - probable bad polygon!
  15239. //throw ( "Warning, unable to triangulate polygon!" );
  15240. //return null;
  15241. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15242. console.log( "Warning, unable to triangulate polygon!" );
  15243. if ( indices ) return vertIndices;
  15244. return result;
  15245. }
  15246. /* three consecutive vertices in current polygon, <u,v,w> */
  15247. u = v; if ( nv <= u ) u = 0; /* previous */
  15248. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15249. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15250. if ( snip( contour, u, v, w, nv, verts ) ) {
  15251. var a, b, c, s, t;
  15252. /* true names of the vertices */
  15253. a = verts[ u ];
  15254. b = verts[ v ];
  15255. c = verts[ w ];
  15256. /* output Triangle */
  15257. /*
  15258. result.push( contour[ a ] );
  15259. result.push( contour[ b ] );
  15260. result.push( contour[ c ] );
  15261. */
  15262. result.push( [ contour[ a ],
  15263. contour[ b ],
  15264. contour[ c ] ] );
  15265. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15266. /* remove v from the remaining polygon */
  15267. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15268. verts[ s ] = verts[ t ];
  15269. }
  15270. nv--;
  15271. /* reset error detection counter */
  15272. count = 2 * nv;
  15273. }
  15274. }
  15275. if ( indices ) return vertIndices;
  15276. return result;
  15277. };
  15278. // calculate area of the contour polygon
  15279. var area = function ( contour ) {
  15280. var n = contour.length;
  15281. var a = 0.0;
  15282. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15283. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15284. }
  15285. return a * 0.5;
  15286. };
  15287. // see if p is inside triangle abc
  15288. var insideTriangle = function( ax, ay,
  15289. bx, by,
  15290. cx, cy,
  15291. px, py ) {
  15292. var aX, aY, bX, bY;
  15293. var cX, cY, apx, apy;
  15294. var bpx, bpy, cpx, cpy;
  15295. var cCROSSap, bCROSScp, aCROSSbp;
  15296. aX = cx - bx; aY = cy - by;
  15297. bX = ax - cx; bY = ay - cy;
  15298. cX = bx - ax; cY = by - ay;
  15299. apx= px -ax; apy= py - ay;
  15300. bpx= px - bx; bpy= py - by;
  15301. cpx= px - cx; cpy= py - cy;
  15302. aCROSSbp = aX*bpy - aY*bpx;
  15303. cCROSSap = cX*apy - cY*apx;
  15304. bCROSScp = bX*cpy - bY*cpx;
  15305. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15306. };
  15307. var snip = function ( contour, u, v, w, n, verts ) {
  15308. var p;
  15309. var ax, ay, bx, by;
  15310. var cx, cy, px, py;
  15311. ax = contour[ verts[ u ] ].x;
  15312. ay = contour[ verts[ u ] ].y;
  15313. bx = contour[ verts[ v ] ].x;
  15314. by = contour[ verts[ v ] ].y;
  15315. cx = contour[ verts[ w ] ].x;
  15316. cy = contour[ verts[ w ] ].y;
  15317. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15318. for ( p = 0; p < n; p++ ) {
  15319. if( (p == u) || (p == v) || (p == w) ) continue;
  15320. px = contour[ verts[ p ] ].x
  15321. py = contour[ verts[ p ] ].y
  15322. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15323. }
  15324. return true;
  15325. };
  15326. namespace.Triangulate = process;
  15327. namespace.Triangulate.area = area;
  15328. return namespace;
  15329. })(THREE.FontUtils);
  15330. // To use the typeface.js face files, hook up the API
  15331. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  15332. * @author zz85 / http://www.lab4games.net/zz85/blog
  15333. * Extensible curve object
  15334. *
  15335. * Some common of Curve methods
  15336. * .getPoint(t), getTangent(t)
  15337. * .getPointAt(u), getTagentAt(u)
  15338. * .getPoints(), .getSpacedPoints()
  15339. * .getLength()
  15340. * .updateArcLengths()
  15341. *
  15342. * This file contains following classes:
  15343. *
  15344. * -- 2d classes --
  15345. * THREE.Curve
  15346. * THREE.LineCurve
  15347. * THREE.QuadraticBezierCurve
  15348. * THREE.CubicBezierCurve
  15349. * THREE.SplineCurve
  15350. * THREE.ArcCurve
  15351. * THREE.EllipseCurve
  15352. *
  15353. * -- 3d classes --
  15354. * THREE.LineCurve3
  15355. * THREE.QuadraticBezierCurve3
  15356. * THREE.CubicBezierCurve3
  15357. * THREE.SplineCurve3
  15358. * THREE.ClosedSplineCurve3
  15359. *
  15360. * A series of curves can be represented as a THREE.CurvePath
  15361. *
  15362. **/
  15363. /**************************************************************
  15364. * Abstract Curve base class
  15365. **************************************************************/
  15366. THREE.Curve = function () {
  15367. };
  15368. // Virtual base class method to overwrite and implement in subclasses
  15369. // - t [0 .. 1]
  15370. THREE.Curve.prototype.getPoint = function ( t ) {
  15371. console.log( "Warning, getPoint() not implemented!" );
  15372. return null;
  15373. };
  15374. // Get point at relative position in curve according to arc length
  15375. // - u [0 .. 1]
  15376. THREE.Curve.prototype.getPointAt = function ( u ) {
  15377. var t = this.getUtoTmapping( u );
  15378. return this.getPoint( t );
  15379. };
  15380. // Get sequence of points using getPoint( t )
  15381. THREE.Curve.prototype.getPoints = function ( divisions ) {
  15382. if ( !divisions ) divisions = 5;
  15383. var d, pts = [];
  15384. for ( d = 0; d <= divisions; d ++ ) {
  15385. pts.push( this.getPoint( d / divisions ) );
  15386. }
  15387. return pts;
  15388. };
  15389. // Get sequence of points using getPointAt( u )
  15390. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  15391. if ( !divisions ) divisions = 5;
  15392. var d, pts = [];
  15393. for ( d = 0; d <= divisions; d ++ ) {
  15394. pts.push( this.getPointAt( d / divisions ) );
  15395. }
  15396. return pts;
  15397. };
  15398. // Get total curve arc length
  15399. THREE.Curve.prototype.getLength = function () {
  15400. var lengths = this.getLengths();
  15401. return lengths[ lengths.length - 1 ];
  15402. };
  15403. // Get list of cumulative segment lengths
  15404. THREE.Curve.prototype.getLengths = function ( divisions ) {
  15405. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  15406. if ( this.cacheArcLengths
  15407. && ( this.cacheArcLengths.length == divisions + 1 )
  15408. && !this.needsUpdate) {
  15409. //console.log( "cached", this.cacheArcLengths );
  15410. return this.cacheArcLengths;
  15411. }
  15412. this.needsUpdate = false;
  15413. var cache = [];
  15414. var current, last = this.getPoint( 0 );
  15415. var p, sum = 0;
  15416. cache.push( 0 );
  15417. for ( p = 1; p <= divisions; p ++ ) {
  15418. current = this.getPoint ( p / divisions );
  15419. sum += current.distanceTo( last );
  15420. cache.push( sum );
  15421. last = current;
  15422. }
  15423. this.cacheArcLengths = cache;
  15424. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  15425. };
  15426. THREE.Curve.prototype.updateArcLengths = function() {
  15427. this.needsUpdate = true;
  15428. this.getLengths();
  15429. };
  15430. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  15431. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  15432. var arcLengths = this.getLengths();
  15433. var i = 0, il = arcLengths.length;
  15434. var targetArcLength; // The targeted u distance value to get
  15435. if ( distance ) {
  15436. targetArcLength = distance;
  15437. } else {
  15438. targetArcLength = u * arcLengths[ il - 1 ];
  15439. }
  15440. //var time = Date.now();
  15441. // binary search for the index with largest value smaller than target u distance
  15442. var low = 0, high = il - 1, comparison;
  15443. while ( low <= high ) {
  15444. 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
  15445. comparison = arcLengths[ i ] - targetArcLength;
  15446. if ( comparison < 0 ) {
  15447. low = i + 1;
  15448. continue;
  15449. } else if ( comparison > 0 ) {
  15450. high = i - 1;
  15451. continue;
  15452. } else {
  15453. high = i;
  15454. break;
  15455. // DONE
  15456. }
  15457. }
  15458. i = high;
  15459. //console.log('b' , i, low, high, Date.now()- time);
  15460. if ( arcLengths[ i ] == targetArcLength ) {
  15461. var t = i / ( il - 1 );
  15462. return t;
  15463. }
  15464. // we could get finer grain at lengths, or use simple interpolatation between two points
  15465. var lengthBefore = arcLengths[ i ];
  15466. var lengthAfter = arcLengths[ i + 1 ];
  15467. var segmentLength = lengthAfter - lengthBefore;
  15468. // determine where we are between the 'before' and 'after' points
  15469. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  15470. // add that fractional amount to t
  15471. var t = ( i + segmentFraction ) / ( il -1 );
  15472. return t;
  15473. };
  15474. // In 2D space, there are actually 2 normal vectors,
  15475. // and in 3D space, infinte
  15476. // TODO this should be depreciated.
  15477. THREE.Curve.prototype.getNormalVector = function( t ) {
  15478. var vec = this.getTangent( t );
  15479. return new THREE.Vector2( -vec.y , vec.x );
  15480. };
  15481. // Returns a unit vector tangent at t
  15482. // In case any sub curve does not implement its tangent / normal finding,
  15483. // we get 2 points with a small delta and find a gradient of the 2 points
  15484. // which seems to make a reasonable approximation
  15485. THREE.Curve.prototype.getTangent = function( t ) {
  15486. var delta = 0.0001;
  15487. var t1 = t - delta;
  15488. var t2 = t + delta;
  15489. // Capping in case of danger
  15490. if ( t1 < 0 ) t1 = 0;
  15491. if ( t2 > 1 ) t2 = 1;
  15492. var pt1 = this.getPoint( t1 );
  15493. var pt2 = this.getPoint( t2 );
  15494. var vec = pt2.clone().subSelf(pt1);
  15495. return vec.normalize();
  15496. };
  15497. THREE.Curve.prototype.getTangentAt = function ( u ) {
  15498. var t = this.getUtoTmapping( u );
  15499. return this.getTangent( t );
  15500. };
  15501. /**************************************************************
  15502. * Line
  15503. **************************************************************/
  15504. THREE.LineCurve = function ( v1, v2 ) {
  15505. this.v1 = v1;
  15506. this.v2 = v2;
  15507. };
  15508. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  15509. THREE.LineCurve.prototype.getPoint = function ( t ) {
  15510. var point = this.v2.clone().subSelf(this.v1);
  15511. point.multiplyScalar( t ).addSelf( this.v1 );
  15512. return point;
  15513. };
  15514. // Line curve is linear, so we can overwrite default getPointAt
  15515. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  15516. return this.getPoint( u );
  15517. };
  15518. THREE.LineCurve.prototype.getTangent = function( t ) {
  15519. var tangent = this.v2.clone().subSelf(this.v1);
  15520. return tangent.normalize();
  15521. };
  15522. /**************************************************************
  15523. * Quadratic Bezier curve
  15524. **************************************************************/
  15525. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  15526. this.v0 = v0;
  15527. this.v1 = v1;
  15528. this.v2 = v2;
  15529. };
  15530. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15531. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  15532. var tx, ty;
  15533. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15534. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15535. return new THREE.Vector2( tx, ty );
  15536. };
  15537. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  15538. var tx, ty;
  15539. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  15540. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  15541. // returns unit vector
  15542. var tangent = new THREE.Vector2( tx, ty );
  15543. tangent.normalize();
  15544. return tangent;
  15545. };
  15546. /**************************************************************
  15547. * Cubic Bezier curve
  15548. **************************************************************/
  15549. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  15550. this.v0 = v0;
  15551. this.v1 = v1;
  15552. this.v2 = v2;
  15553. this.v3 = v3;
  15554. };
  15555. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  15556. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  15557. var tx, ty;
  15558. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15559. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15560. return new THREE.Vector2( tx, ty );
  15561. };
  15562. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  15563. var tx, ty;
  15564. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15565. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15566. var tangent = new THREE.Vector2( tx, ty );
  15567. tangent.normalize();
  15568. return tangent;
  15569. };
  15570. /**************************************************************
  15571. * Spline curve
  15572. **************************************************************/
  15573. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  15574. this.points = (points == undefined) ? [] : points;
  15575. };
  15576. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  15577. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  15578. var v = new THREE.Vector2();
  15579. var c = [];
  15580. var points = this.points, point, intPoint, weight;
  15581. point = ( points.length - 1 ) * t;
  15582. intPoint = Math.floor( point );
  15583. weight = point - intPoint;
  15584. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15585. c[ 1 ] = intPoint;
  15586. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  15587. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  15588. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15589. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15590. return v;
  15591. };
  15592. /**************************************************************
  15593. * Ellipse curve
  15594. **************************************************************/
  15595. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  15596. aStartAngle, aEndAngle,
  15597. aClockwise ) {
  15598. this.aX = aX;
  15599. this.aY = aY;
  15600. this.xRadius = xRadius;
  15601. this.yRadius = yRadius;
  15602. this.aStartAngle = aStartAngle;
  15603. this.aEndAngle = aEndAngle;
  15604. this.aClockwise = aClockwise;
  15605. };
  15606. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  15607. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  15608. var deltaAngle = this.aEndAngle - this.aStartAngle;
  15609. if ( !this.aClockwise ) {
  15610. t = 1 - t;
  15611. }
  15612. var angle = this.aStartAngle + t * deltaAngle;
  15613. var tx = this.aX + this.xRadius * Math.cos( angle );
  15614. var ty = this.aY + this.yRadius * Math.sin( angle );
  15615. return new THREE.Vector2( tx, ty );
  15616. };
  15617. /**************************************************************
  15618. * Arc curve
  15619. **************************************************************/
  15620. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  15621. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  15622. };
  15623. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  15624. /**************************************************************
  15625. * Utils
  15626. **************************************************************/
  15627. THREE.Curve.Utils = {
  15628. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  15629. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  15630. },
  15631. // Puay Bing, thanks for helping with this derivative!
  15632. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  15633. return -3 * p0 * (1 - t) * (1 - t) +
  15634. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  15635. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  15636. 3 * t * t * p3;
  15637. },
  15638. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  15639. // To check if my formulas are correct
  15640. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  15641. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  15642. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  15643. var h11 = 3 * t * t - 2 * t; // t3 − t2
  15644. return h00 + h10 + h01 + h11;
  15645. },
  15646. // Catmull-Rom
  15647. interpolate: function( p0, p1, p2, p3, t ) {
  15648. var v0 = ( p2 - p0 ) * 0.5;
  15649. var v1 = ( p3 - p1 ) * 0.5;
  15650. var t2 = t * t;
  15651. var t3 = t * t2;
  15652. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  15653. }
  15654. };
  15655. // TODO: Transformation for Curves?
  15656. /**************************************************************
  15657. * 3D Curves
  15658. **************************************************************/
  15659. // A Factory method for creating new curve subclasses
  15660. THREE.Curve.create = function ( constructor, getPointFunc ) {
  15661. constructor.prototype = Object.create( THREE.Curve.prototype );
  15662. constructor.prototype.getPoint = getPointFunc;
  15663. return constructor;
  15664. };
  15665. /**************************************************************
  15666. * Line3D
  15667. **************************************************************/
  15668. THREE.LineCurve3 = THREE.Curve.create(
  15669. function ( v1, v2 ) {
  15670. this.v1 = v1;
  15671. this.v2 = v2;
  15672. },
  15673. function ( t ) {
  15674. var r = new THREE.Vector3();
  15675. r.sub( this.v2, this.v1 ); // diff
  15676. r.multiplyScalar( t );
  15677. r.addSelf( this.v1 );
  15678. return r;
  15679. }
  15680. );
  15681. /**************************************************************
  15682. * Quadratic Bezier 3D curve
  15683. **************************************************************/
  15684. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  15685. function ( v0, v1, v2 ) {
  15686. this.v0 = v0;
  15687. this.v1 = v1;
  15688. this.v2 = v2;
  15689. },
  15690. function ( t ) {
  15691. var tx, ty, tz;
  15692. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  15693. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  15694. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  15695. return new THREE.Vector3( tx, ty, tz );
  15696. }
  15697. );
  15698. /**************************************************************
  15699. * Cubic Bezier 3D curve
  15700. **************************************************************/
  15701. THREE.CubicBezierCurve3 = THREE.Curve.create(
  15702. function ( v0, v1, v2, v3 ) {
  15703. this.v0 = v0;
  15704. this.v1 = v1;
  15705. this.v2 = v2;
  15706. this.v3 = v3;
  15707. },
  15708. function ( t ) {
  15709. var tx, ty, tz;
  15710. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  15711. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  15712. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  15713. return new THREE.Vector3( tx, ty, tz );
  15714. }
  15715. );
  15716. /**************************************************************
  15717. * Spline 3D curve
  15718. **************************************************************/
  15719. THREE.SplineCurve3 = THREE.Curve.create(
  15720. function ( points /* array of Vector3 */) {
  15721. this.points = (points == undefined) ? [] : points;
  15722. },
  15723. function ( t ) {
  15724. var v = new THREE.Vector3();
  15725. var c = [];
  15726. var points = this.points, point, intPoint, weight;
  15727. point = ( points.length - 1 ) * t;
  15728. intPoint = Math.floor( point );
  15729. weight = point - intPoint;
  15730. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15731. c[ 1 ] = intPoint;
  15732. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15733. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15734. var pt0 = points[ c[0] ],
  15735. pt1 = points[ c[1] ],
  15736. pt2 = points[ c[2] ],
  15737. pt3 = points[ c[3] ];
  15738. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  15739. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  15740. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  15741. return v;
  15742. }
  15743. );
  15744. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  15745. // var v = new THREE.Vector3();
  15746. // var c = [];
  15747. // var points = this.points, point, intPoint, weight;
  15748. // point = ( points.length - 1 ) * t;
  15749. // intPoint = Math.floor( point );
  15750. // weight = point - intPoint;
  15751. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  15752. // c[ 1 ] = intPoint;
  15753. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  15754. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  15755. // var pt0 = points[ c[0] ],
  15756. // pt1 = points[ c[1] ],
  15757. // pt2 = points[ c[2] ],
  15758. // pt3 = points[ c[3] ];
  15759. // // t = weight;
  15760. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  15761. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  15762. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  15763. // return v;
  15764. // }
  15765. /**************************************************************
  15766. * Closed Spline 3D curve
  15767. **************************************************************/
  15768. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  15769. function ( points /* array of Vector3 */) {
  15770. this.points = (points == undefined) ? [] : points;
  15771. },
  15772. function ( t ) {
  15773. var v = new THREE.Vector3();
  15774. var c = [];
  15775. var points = this.points, point, intPoint, weight;
  15776. point = ( points.length - 0 ) * t;
  15777. // This needs to be from 0-length +1
  15778. intPoint = Math.floor( point );
  15779. weight = point - intPoint;
  15780. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  15781. c[ 0 ] = ( intPoint - 1 ) % points.length;
  15782. c[ 1 ] = ( intPoint ) % points.length;
  15783. c[ 2 ] = ( intPoint + 1 ) % points.length;
  15784. c[ 3 ] = ( intPoint + 2 ) % points.length;
  15785. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  15786. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  15787. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  15788. return v;
  15789. }
  15790. );
  15791. /**
  15792. * @author zz85 / http://www.lab4games.net/zz85/blog
  15793. *
  15794. **/
  15795. /**************************************************************
  15796. * Curved Path - a curve path is simply a array of connected
  15797. * curves, but retains the api of a curve
  15798. **************************************************************/
  15799. THREE.CurvePath = function () {
  15800. this.curves = [];
  15801. this.bends = [];
  15802. this.autoClose = false; // Automatically closes the path
  15803. };
  15804. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  15805. THREE.CurvePath.prototype.add = function ( curve ) {
  15806. this.curves.push( curve );
  15807. };
  15808. THREE.CurvePath.prototype.checkConnection = function() {
  15809. // TODO
  15810. // If the ending of curve is not connected to the starting
  15811. // or the next curve, then, this is not a real path
  15812. };
  15813. THREE.CurvePath.prototype.closePath = function() {
  15814. // TODO Test
  15815. // and verify for vector3 (needs to implement equals)
  15816. // Add a line curve if start and end of lines are not connected
  15817. var startPoint = this.curves[0].getPoint(0);
  15818. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  15819. if (!startPoint.equals(endPoint)) {
  15820. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  15821. }
  15822. };
  15823. // To get accurate point with reference to
  15824. // entire path distance at time t,
  15825. // following has to be done:
  15826. // 1. Length of each sub path have to be known
  15827. // 2. Locate and identify type of curve
  15828. // 3. Get t for the curve
  15829. // 4. Return curve.getPointAt(t')
  15830. THREE.CurvePath.prototype.getPoint = function( t ) {
  15831. var d = t * this.getLength();
  15832. var curveLengths = this.getCurveLengths();
  15833. var i = 0, diff, curve;
  15834. // To think about boundaries points.
  15835. while ( i < curveLengths.length ) {
  15836. if ( curveLengths[ i ] >= d ) {
  15837. diff = curveLengths[ i ] - d;
  15838. curve = this.curves[ i ];
  15839. var u = 1 - diff / curve.getLength();
  15840. return curve.getPointAt( u );
  15841. break;
  15842. }
  15843. i ++;
  15844. }
  15845. return null;
  15846. // loop where sum != 0, sum > d , sum+1 <d
  15847. };
  15848. /*
  15849. THREE.CurvePath.prototype.getTangent = function( t ) {
  15850. };*/
  15851. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  15852. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  15853. // getPoint() depends on getLength
  15854. THREE.CurvePath.prototype.getLength = function() {
  15855. var lens = this.getCurveLengths();
  15856. return lens[ lens.length - 1 ];
  15857. };
  15858. // Compute lengths and cache them
  15859. // We cannot overwrite getLengths() because UtoT mapping uses it.
  15860. THREE.CurvePath.prototype.getCurveLengths = function() {
  15861. // We use cache values if curves and cache array are same length
  15862. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  15863. return this.cacheLengths;
  15864. };
  15865. // Get length of subsurve
  15866. // Push sums into cached array
  15867. var lengths = [], sums = 0;
  15868. var i, il = this.curves.length;
  15869. for ( i = 0; i < il; i ++ ) {
  15870. sums += this.curves[ i ].getLength();
  15871. lengths.push( sums );
  15872. }
  15873. this.cacheLengths = lengths;
  15874. return lengths;
  15875. };
  15876. // Returns min and max coordinates, as well as centroid
  15877. THREE.CurvePath.prototype.getBoundingBox = function () {
  15878. var points = this.getPoints();
  15879. var maxX, maxY, maxZ;
  15880. var minX, minY, minZ;
  15881. maxX = maxY = Number.NEGATIVE_INFINITY;
  15882. minX = minY = Number.POSITIVE_INFINITY;
  15883. var p, i, il, sum;
  15884. var v3 = points[0] instanceof THREE.Vector3;
  15885. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  15886. for ( i = 0, il = points.length; i < il; i ++ ) {
  15887. p = points[ i ];
  15888. if ( p.x > maxX ) maxX = p.x;
  15889. else if ( p.x < minX ) minX = p.x;
  15890. if ( p.y > maxY ) maxY = p.y;
  15891. else if ( p.y < minY ) minY = p.y;
  15892. if (v3) {
  15893. if ( p.z > maxZ ) maxZ = p.z;
  15894. else if ( p.z < minZ ) minZ = p.z;
  15895. }
  15896. sum.addSelf( p );
  15897. }
  15898. var ret = {
  15899. minX: minX,
  15900. minY: minY,
  15901. maxX: maxX,
  15902. maxY: maxY,
  15903. centroid: sum.divideScalar( il )
  15904. };
  15905. if (v3) {
  15906. ret.maxZ = maxZ;
  15907. ret.minZ = minZ;
  15908. }
  15909. return ret;
  15910. };
  15911. /**************************************************************
  15912. * Create Geometries Helpers
  15913. **************************************************************/
  15914. /// Generate geometry from path points (for Line or ParticleSystem objects)
  15915. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  15916. var pts = this.getPoints( divisions, true );
  15917. return this.createGeometry( pts );
  15918. };
  15919. // Generate geometry from equidistance sampling along the path
  15920. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  15921. var pts = this.getSpacedPoints( divisions, true );
  15922. return this.createGeometry( pts );
  15923. };
  15924. THREE.CurvePath.prototype.createGeometry = function( points ) {
  15925. var geometry = new THREE.Geometry();
  15926. for ( var i = 0; i < points.length; i ++ ) {
  15927. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  15928. }
  15929. return geometry;
  15930. };
  15931. /**************************************************************
  15932. * Bend / Wrap Helper Methods
  15933. **************************************************************/
  15934. // Wrap path / Bend modifiers?
  15935. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  15936. this.bends.push( bendpath );
  15937. };
  15938. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  15939. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  15940. var i, il;
  15941. if ( !bends ) {
  15942. bends = this.bends;
  15943. }
  15944. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15945. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15946. }
  15947. return oldPts;
  15948. };
  15949. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  15950. var oldPts = this.getSpacedPoints( segments );
  15951. var i, il;
  15952. if ( !bends ) {
  15953. bends = this.bends;
  15954. }
  15955. for ( i = 0, il = bends.length; i < il; i ++ ) {
  15956. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  15957. }
  15958. return oldPts;
  15959. };
  15960. // This returns getPoints() bend/wrapped around the contour of a path.
  15961. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  15962. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  15963. var bounds = this.getBoundingBox();
  15964. var i, il, p, oldX, oldY, xNorm;
  15965. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  15966. p = oldPts[ i ];
  15967. oldX = p.x;
  15968. oldY = p.y;
  15969. xNorm = oldX / bounds.maxX;
  15970. // If using actual distance, for length > path, requires line extrusions
  15971. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  15972. xNorm = path.getUtoTmapping( xNorm, oldX );
  15973. // check for out of bounds?
  15974. var pathPt = path.getPoint( xNorm );
  15975. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  15976. p.x = pathPt.x + normal.x;
  15977. p.y = pathPt.y + normal.y;
  15978. }
  15979. return oldPts;
  15980. };
  15981. /**
  15982. * @author alteredq / http://alteredqualia.com/
  15983. */
  15984. THREE.Gyroscope = function () {
  15985. THREE.Object3D.call( this );
  15986. };
  15987. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  15988. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  15989. this.matrixAutoUpdate && this.updateMatrix();
  15990. // update matrixWorld
  15991. if ( this.matrixWorldNeedsUpdate || force ) {
  15992. if ( this.parent ) {
  15993. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  15994. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  15995. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  15996. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  15997. } else {
  15998. this.matrixWorld.copy( this.matrix );
  15999. }
  16000. this.matrixWorldNeedsUpdate = false;
  16001. force = true;
  16002. }
  16003. // update children
  16004. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16005. this.children[ i ].updateMatrixWorld( force );
  16006. }
  16007. };
  16008. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16009. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16010. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16011. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16012. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16013. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16014. /**
  16015. * @author zz85 / http://www.lab4games.net/zz85/blog
  16016. * Creates free form 2d path using series of points, lines or curves.
  16017. *
  16018. **/
  16019. THREE.Path = function ( points ) {
  16020. THREE.CurvePath.call(this);
  16021. this.actions = [];
  16022. if ( points ) {
  16023. this.fromPoints( points );
  16024. }
  16025. };
  16026. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16027. THREE.PathActions = {
  16028. MOVE_TO: 'moveTo',
  16029. LINE_TO: 'lineTo',
  16030. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16031. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16032. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16033. ARC: 'arc', // Circle
  16034. ELLIPSE: 'ellipse'
  16035. };
  16036. // TODO Clean up PATH API
  16037. // Create path using straight lines to connect all points
  16038. // - vectors: array of Vector2
  16039. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16040. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16041. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16042. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16043. };
  16044. };
  16045. // startPath() endPath()?
  16046. THREE.Path.prototype.moveTo = function ( x, y ) {
  16047. var args = Array.prototype.slice.call( arguments );
  16048. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16049. };
  16050. THREE.Path.prototype.lineTo = function ( x, y ) {
  16051. var args = Array.prototype.slice.call( arguments );
  16052. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16053. var x0 = lastargs[ lastargs.length - 2 ];
  16054. var y0 = lastargs[ lastargs.length - 1 ];
  16055. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16056. this.curves.push( curve );
  16057. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16058. };
  16059. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16060. var args = Array.prototype.slice.call( arguments );
  16061. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16062. var x0 = lastargs[ lastargs.length - 2 ];
  16063. var y0 = lastargs[ lastargs.length - 1 ];
  16064. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16065. new THREE.Vector2( aCPx, aCPy ),
  16066. new THREE.Vector2( aX, aY ) );
  16067. this.curves.push( curve );
  16068. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16069. };
  16070. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16071. aCP2x, aCP2y,
  16072. aX, aY ) {
  16073. var args = Array.prototype.slice.call( arguments );
  16074. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16075. var x0 = lastargs[ lastargs.length - 2 ];
  16076. var y0 = lastargs[ lastargs.length - 1 ];
  16077. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16078. new THREE.Vector2( aCP1x, aCP1y ),
  16079. new THREE.Vector2( aCP2x, aCP2y ),
  16080. new THREE.Vector2( aX, aY ) );
  16081. this.curves.push( curve );
  16082. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16083. };
  16084. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16085. var args = Array.prototype.slice.call( arguments );
  16086. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16087. var x0 = lastargs[ lastargs.length - 2 ];
  16088. var y0 = lastargs[ lastargs.length - 1 ];
  16089. //---
  16090. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16091. Array.prototype.push.apply( npts, pts );
  16092. var curve = new THREE.SplineCurve( npts );
  16093. this.curves.push( curve );
  16094. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  16095. };
  16096. // FUTURE: Change the API or follow canvas API?
  16097. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  16098. aStartAngle, aEndAngle, aClockwise ) {
  16099. var lastargs = this.actions[ this.actions.length - 1].args;
  16100. var x0 = lastargs[ lastargs.length - 2 ];
  16101. var y0 = lastargs[ lastargs.length - 1 ];
  16102. this.absarc(aX + x0, aY + y0, aRadius,
  16103. aStartAngle, aEndAngle, aClockwise );
  16104. };
  16105. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  16106. aStartAngle, aEndAngle, aClockwise ) {
  16107. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  16108. };
  16109. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  16110. aStartAngle, aEndAngle, aClockwise ) {
  16111. var lastargs = this.actions[ this.actions.length - 1].args;
  16112. var x0 = lastargs[ lastargs.length - 2 ];
  16113. var y0 = lastargs[ lastargs.length - 1 ];
  16114. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  16115. aStartAngle, aEndAngle, aClockwise );
  16116. };
  16117. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  16118. aStartAngle, aEndAngle, aClockwise ) {
  16119. var args = Array.prototype.slice.call( arguments );
  16120. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  16121. aStartAngle, aEndAngle, aClockwise );
  16122. this.curves.push( curve );
  16123. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  16124. args.push(lastPoint.x);
  16125. args.push(lastPoint.y);
  16126. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  16127. };
  16128. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  16129. if ( ! divisions ) divisions = 40;
  16130. var points = [];
  16131. for ( var i = 0; i < divisions; i ++ ) {
  16132. points.push( this.getPoint( i / divisions ) );
  16133. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  16134. }
  16135. // if ( closedPath ) {
  16136. //
  16137. // points.push( points[ 0 ] );
  16138. //
  16139. // }
  16140. return points;
  16141. };
  16142. /* Return an array of vectors based on contour of the path */
  16143. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  16144. if (this.useSpacedPoints) {
  16145. console.log('tata');
  16146. return this.getSpacedPoints( divisions, closedPath );
  16147. }
  16148. divisions = divisions || 12;
  16149. var points = [];
  16150. var i, il, item, action, args;
  16151. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  16152. laste, j,
  16153. t, tx, ty;
  16154. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16155. item = this.actions[ i ];
  16156. action = item.action;
  16157. args = item.args;
  16158. switch( action ) {
  16159. case THREE.PathActions.MOVE_TO:
  16160. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16161. break;
  16162. case THREE.PathActions.LINE_TO:
  16163. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  16164. break;
  16165. case THREE.PathActions.QUADRATIC_CURVE_TO:
  16166. cpx = args[ 2 ];
  16167. cpy = args[ 3 ];
  16168. cpx1 = args[ 0 ];
  16169. cpy1 = args[ 1 ];
  16170. if ( points.length > 0 ) {
  16171. laste = points[ points.length - 1 ];
  16172. cpx0 = laste.x;
  16173. cpy0 = laste.y;
  16174. } else {
  16175. laste = this.actions[ i - 1 ].args;
  16176. cpx0 = laste[ laste.length - 2 ];
  16177. cpy0 = laste[ laste.length - 1 ];
  16178. }
  16179. for ( j = 1; j <= divisions; j ++ ) {
  16180. t = j / divisions;
  16181. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16182. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16183. points.push( new THREE.Vector2( tx, ty ) );
  16184. }
  16185. break;
  16186. case THREE.PathActions.BEZIER_CURVE_TO:
  16187. cpx = args[ 4 ];
  16188. cpy = args[ 5 ];
  16189. cpx1 = args[ 0 ];
  16190. cpy1 = args[ 1 ];
  16191. cpx2 = args[ 2 ];
  16192. cpy2 = args[ 3 ];
  16193. if ( points.length > 0 ) {
  16194. laste = points[ points.length - 1 ];
  16195. cpx0 = laste.x;
  16196. cpy0 = laste.y;
  16197. } else {
  16198. laste = this.actions[ i - 1 ].args;
  16199. cpx0 = laste[ laste.length - 2 ];
  16200. cpy0 = laste[ laste.length - 1 ];
  16201. }
  16202. for ( j = 1; j <= divisions; j ++ ) {
  16203. t = j / divisions;
  16204. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16205. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16206. points.push( new THREE.Vector2( tx, ty ) );
  16207. }
  16208. break;
  16209. case THREE.PathActions.CSPLINE_THRU:
  16210. laste = this.actions[ i - 1 ].args;
  16211. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  16212. var spts = [ last ];
  16213. var n = divisions * args[ 0 ].length;
  16214. spts = spts.concat( args[ 0 ] );
  16215. var spline = new THREE.SplineCurve( spts );
  16216. for ( j = 1; j <= n; j ++ ) {
  16217. points.push( spline.getPointAt( j / n ) ) ;
  16218. }
  16219. break;
  16220. case THREE.PathActions.ARC:
  16221. var aX = args[ 0 ], aY = args[ 1 ],
  16222. aRadius = args[ 2 ],
  16223. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  16224. aClockwise = !!args[ 5 ];
  16225. var deltaAngle = aEndAngle - aStartAngle;
  16226. var angle;
  16227. var tdivisions = divisions * 2;
  16228. for ( j = 1; j <= tdivisions; j ++ ) {
  16229. t = j / tdivisions;
  16230. if ( ! aClockwise ) {
  16231. t = 1 - t;
  16232. }
  16233. angle = aStartAngle + t * deltaAngle;
  16234. tx = aX + aRadius * Math.cos( angle );
  16235. ty = aY + aRadius * Math.sin( angle );
  16236. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16237. points.push( new THREE.Vector2( tx, ty ) );
  16238. }
  16239. //console.log(points);
  16240. break;
  16241. case THREE.PathActions.ELLIPSE:
  16242. var aX = args[ 0 ], aY = args[ 1 ],
  16243. xRadius = args[ 2 ],
  16244. yRadius = args[ 3 ],
  16245. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  16246. aClockwise = !!args[ 6 ];
  16247. var deltaAngle = aEndAngle - aStartAngle;
  16248. var angle;
  16249. var tdivisions = divisions * 2;
  16250. for ( j = 1; j <= tdivisions; j ++ ) {
  16251. t = j / tdivisions;
  16252. if ( ! aClockwise ) {
  16253. t = 1 - t;
  16254. }
  16255. angle = aStartAngle + t * deltaAngle;
  16256. tx = aX + xRadius * Math.cos( angle );
  16257. ty = aY + yRadius * Math.sin( angle );
  16258. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  16259. points.push( new THREE.Vector2( tx, ty ) );
  16260. }
  16261. //console.log(points);
  16262. break;
  16263. } // end switch
  16264. }
  16265. // Normalize to remove the closing point by default.
  16266. var lastPoint = points[ points.length - 1];
  16267. var EPSILON = 0.0000000001;
  16268. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  16269. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  16270. points.splice( points.length - 1, 1);
  16271. if ( closedPath ) {
  16272. points.push( points[ 0 ] );
  16273. }
  16274. return points;
  16275. };
  16276. // Breaks path into shapes
  16277. THREE.Path.prototype.toShapes = function() {
  16278. var i, il, item, action, args;
  16279. var subPaths = [], lastPath = new THREE.Path();
  16280. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  16281. item = this.actions[ i ];
  16282. args = item.args;
  16283. action = item.action;
  16284. if ( action == THREE.PathActions.MOVE_TO ) {
  16285. if ( lastPath.actions.length != 0 ) {
  16286. subPaths.push( lastPath );
  16287. lastPath = new THREE.Path();
  16288. }
  16289. }
  16290. lastPath[ action ].apply( lastPath, args );
  16291. }
  16292. if ( lastPath.actions.length != 0 ) {
  16293. subPaths.push( lastPath );
  16294. }
  16295. // console.log(subPaths);
  16296. if ( subPaths.length == 0 ) return [];
  16297. var tmpPath, tmpShape, shapes = [];
  16298. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  16299. // console.log("Holes first", holesFirst);
  16300. if ( subPaths.length == 1) {
  16301. tmpPath = subPaths[0];
  16302. tmpShape = new THREE.Shape();
  16303. tmpShape.actions = tmpPath.actions;
  16304. tmpShape.curves = tmpPath.curves;
  16305. shapes.push( tmpShape );
  16306. return shapes;
  16307. };
  16308. if ( holesFirst ) {
  16309. tmpShape = new THREE.Shape();
  16310. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16311. tmpPath = subPaths[ i ];
  16312. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16313. tmpShape.actions = tmpPath.actions;
  16314. tmpShape.curves = tmpPath.curves;
  16315. shapes.push( tmpShape );
  16316. tmpShape = new THREE.Shape();
  16317. //console.log('cw', i);
  16318. } else {
  16319. tmpShape.holes.push( tmpPath );
  16320. //console.log('ccw', i);
  16321. }
  16322. }
  16323. } else {
  16324. // Shapes first
  16325. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  16326. tmpPath = subPaths[ i ];
  16327. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  16328. if ( tmpShape ) shapes.push( tmpShape );
  16329. tmpShape = new THREE.Shape();
  16330. tmpShape.actions = tmpPath.actions;
  16331. tmpShape.curves = tmpPath.curves;
  16332. } else {
  16333. tmpShape.holes.push( tmpPath );
  16334. }
  16335. }
  16336. shapes.push( tmpShape );
  16337. }
  16338. //console.log("shape", shapes);
  16339. return shapes;
  16340. };
  16341. /**
  16342. * @author zz85 / http://www.lab4games.net/zz85/blog
  16343. * Defines a 2d shape plane using paths.
  16344. **/
  16345. // STEP 1 Create a path.
  16346. // STEP 2 Turn path into shape.
  16347. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  16348. // STEP 3a - Extract points from each shape, turn to vertices
  16349. // STEP 3b - Triangulate each shape, add faces.
  16350. THREE.Shape = function ( ) {
  16351. THREE.Path.apply( this, arguments );
  16352. this.holes = [];
  16353. };
  16354. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  16355. // Convenience method to return ExtrudeGeometry
  16356. THREE.Shape.prototype.extrude = function ( options ) {
  16357. var extruded = new THREE.ExtrudeGeometry( this, options );
  16358. return extruded;
  16359. };
  16360. // Convenience method to return ShapeGeometry
  16361. THREE.Shape.prototype.makeGeometry = function ( options ) {
  16362. var geometry = new THREE.ShapeGeometry( this, options );
  16363. return geometry;
  16364. };
  16365. // Get points of holes
  16366. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  16367. var i, il = this.holes.length, holesPts = [];
  16368. for ( i = 0; i < il; i ++ ) {
  16369. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  16370. }
  16371. return holesPts;
  16372. };
  16373. // Get points of holes (spaced by regular distance)
  16374. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  16375. var i, il = this.holes.length, holesPts = [];
  16376. for ( i = 0; i < il; i ++ ) {
  16377. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  16378. }
  16379. return holesPts;
  16380. };
  16381. // Get points of shape and holes (keypoints based on segments parameter)
  16382. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  16383. return {
  16384. shape: this.getTransformedPoints( divisions ),
  16385. holes: this.getPointsHoles( divisions )
  16386. };
  16387. };
  16388. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  16389. if (this.useSpacedPoints) {
  16390. return this.extractAllSpacedPoints(divisions);
  16391. }
  16392. return this.extractAllPoints(divisions);
  16393. };
  16394. //
  16395. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  16396. //
  16397. // return {
  16398. //
  16399. // shape: this.transform( bend, divisions ),
  16400. // holes: this.getPointsHoles( divisions, bend )
  16401. //
  16402. // };
  16403. //
  16404. // };
  16405. // Get points of shape and holes (spaced by regular distance)
  16406. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  16407. return {
  16408. shape: this.getTransformedSpacedPoints( divisions ),
  16409. holes: this.getSpacedPointsHoles( divisions )
  16410. };
  16411. };
  16412. /**************************************************************
  16413. * Utils
  16414. **************************************************************/
  16415. THREE.Shape.Utils = {
  16416. /*
  16417. contour - array of vector2 for contour
  16418. holes - array of array of vector2
  16419. */
  16420. removeHoles: function ( contour, holes ) {
  16421. var shape = contour.concat(); // work on this shape
  16422. var allpoints = shape.concat();
  16423. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  16424. var prevShapeVert, nextShapeVert,
  16425. prevHoleVert, nextHoleVert,
  16426. holeIndex, shapeIndex,
  16427. shapeId, shapeGroup,
  16428. h, h2,
  16429. hole, shortest, d,
  16430. p, pts1, pts2,
  16431. tmpShape1, tmpShape2,
  16432. tmpHole1, tmpHole2,
  16433. verts = [];
  16434. for ( h = 0; h < holes.length; h ++ ) {
  16435. hole = holes[ h ];
  16436. /*
  16437. shapeholes[ h ].concat(); // preserves original
  16438. holes.push( hole );
  16439. */
  16440. Array.prototype.push.apply( allpoints, hole );
  16441. shortest = Number.POSITIVE_INFINITY;
  16442. // Find the shortest pair of pts between shape and hole
  16443. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  16444. // Using distanceToSquared() intead of distanceTo() should speed a little
  16445. // since running square roots operations are reduced.
  16446. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  16447. pts1 = hole[ h2 ];
  16448. var dist = [];
  16449. for ( p = 0; p < shape.length; p++ ) {
  16450. pts2 = shape[ p ];
  16451. d = pts1.distanceToSquared( pts2 );
  16452. dist.push( d );
  16453. if ( d < shortest ) {
  16454. shortest = d;
  16455. holeIndex = h2;
  16456. shapeIndex = p;
  16457. }
  16458. }
  16459. }
  16460. //console.log("shortest", shortest, dist);
  16461. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16462. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16463. var areaapts = [
  16464. hole[ holeIndex ],
  16465. shape[ shapeIndex ],
  16466. shape[ prevShapeVert ]
  16467. ];
  16468. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  16469. var areabpts = [
  16470. hole[ holeIndex ],
  16471. hole[ prevHoleVert ],
  16472. shape[ shapeIndex ]
  16473. ];
  16474. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  16475. var shapeOffset = 1;
  16476. var holeOffset = -1;
  16477. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  16478. shapeIndex += shapeOffset;
  16479. holeIndex += holeOffset;
  16480. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16481. shapeIndex %= shape.length;
  16482. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16483. holeIndex %= hole.length;
  16484. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16485. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16486. areaapts = [
  16487. hole[ holeIndex ],
  16488. shape[ shapeIndex ],
  16489. shape[ prevShapeVert ]
  16490. ];
  16491. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  16492. areabpts = [
  16493. hole[ holeIndex ],
  16494. hole[ prevHoleVert ],
  16495. shape[ shapeIndex ]
  16496. ];
  16497. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  16498. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  16499. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  16500. // In case areas are not correct.
  16501. //console.log("USE THIS");
  16502. shapeIndex = oldShapeIndex;
  16503. holeIndex = oldHoleIndex ;
  16504. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  16505. shapeIndex %= shape.length;
  16506. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  16507. holeIndex %= hole.length;
  16508. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  16509. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  16510. } else {
  16511. //console.log("USE THAT ")
  16512. }
  16513. tmpShape1 = shape.slice( 0, shapeIndex );
  16514. tmpShape2 = shape.slice( shapeIndex );
  16515. tmpHole1 = hole.slice( holeIndex );
  16516. tmpHole2 = hole.slice( 0, holeIndex );
  16517. // Should check orders here again?
  16518. var trianglea = [
  16519. hole[ holeIndex ],
  16520. shape[ shapeIndex ],
  16521. shape[ prevShapeVert ]
  16522. ];
  16523. var triangleb = [
  16524. hole[ holeIndex ] ,
  16525. hole[ prevHoleVert ],
  16526. shape[ shapeIndex ]
  16527. ];
  16528. verts.push( trianglea );
  16529. verts.push( triangleb );
  16530. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  16531. }
  16532. return {
  16533. shape:shape, /* shape with no holes */
  16534. isolatedPts: verts, /* isolated faces */
  16535. allpoints: allpoints
  16536. }
  16537. },
  16538. triangulateShape: function ( contour, holes ) {
  16539. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  16540. var shape = shapeWithoutHoles.shape,
  16541. allpoints = shapeWithoutHoles.allpoints,
  16542. isolatedPts = shapeWithoutHoles.isolatedPts;
  16543. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  16544. // 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.
  16545. //console.log( "triangles",triangles, triangles.length );
  16546. //console.log( "allpoints",allpoints, allpoints.length );
  16547. var i, il, f, face,
  16548. key, index,
  16549. allPointsMap = {},
  16550. isolatedPointsMap = {};
  16551. // prepare all points map
  16552. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  16553. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  16554. if ( allPointsMap[ key ] !== undefined ) {
  16555. console.log( "Duplicate point", key );
  16556. }
  16557. allPointsMap[ key ] = i;
  16558. }
  16559. // check all face vertices against all points map
  16560. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  16561. face = triangles[ i ];
  16562. for ( f = 0; f < 3; f ++ ) {
  16563. key = face[ f ].x + ":" + face[ f ].y;
  16564. index = allPointsMap[ key ];
  16565. if ( index !== undefined ) {
  16566. face[ f ] = index;
  16567. }
  16568. }
  16569. }
  16570. // check isolated points vertices against all points map
  16571. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  16572. face = isolatedPts[ i ];
  16573. for ( f = 0; f < 3; f ++ ) {
  16574. key = face[ f ].x + ":" + face[ f ].y;
  16575. index = allPointsMap[ key ];
  16576. if ( index !== undefined ) {
  16577. face[ f ] = index;
  16578. }
  16579. }
  16580. }
  16581. return triangles.concat( isolatedPts );
  16582. }, // end triangulate shapes
  16583. /*
  16584. triangulate2 : function( pts, holes ) {
  16585. // For use with Poly2Tri.js
  16586. var allpts = pts.concat();
  16587. var shape = [];
  16588. for (var p in pts) {
  16589. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  16590. }
  16591. var swctx = new js.poly2tri.SweepContext(shape);
  16592. for (var h in holes) {
  16593. var aHole = holes[h];
  16594. var newHole = []
  16595. for (i in aHole) {
  16596. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  16597. allpts.push(aHole[i]);
  16598. }
  16599. swctx.AddHole(newHole);
  16600. }
  16601. var find;
  16602. var findIndexForPt = function (pt) {
  16603. find = new THREE.Vector2(pt.x, pt.y);
  16604. var p;
  16605. for (p=0, pl = allpts.length; p<pl; p++) {
  16606. if (allpts[p].equals(find)) return p;
  16607. }
  16608. return -1;
  16609. };
  16610. // triangulate
  16611. js.poly2tri.sweep.Triangulate(swctx);
  16612. var triangles = swctx.GetTriangles();
  16613. var tr ;
  16614. var facesPts = [];
  16615. for (var t in triangles) {
  16616. tr = triangles[t];
  16617. facesPts.push([
  16618. findIndexForPt(tr.GetPoint(0)),
  16619. findIndexForPt(tr.GetPoint(1)),
  16620. findIndexForPt(tr.GetPoint(2))
  16621. ]);
  16622. }
  16623. // console.log(facesPts);
  16624. // console.log("triangles", triangles.length, triangles);
  16625. // Returns array of faces with 3 element each
  16626. return facesPts;
  16627. },
  16628. */
  16629. isClockWise: function ( pts ) {
  16630. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  16631. },
  16632. // Bezier Curves formulas obtained from
  16633. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  16634. // Quad Bezier Functions
  16635. b2p0: function ( t, p ) {
  16636. var k = 1 - t;
  16637. return k * k * p;
  16638. },
  16639. b2p1: function ( t, p ) {
  16640. return 2 * ( 1 - t ) * t * p;
  16641. },
  16642. b2p2: function ( t, p ) {
  16643. return t * t * p;
  16644. },
  16645. b2: function ( t, p0, p1, p2 ) {
  16646. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  16647. },
  16648. // Cubic Bezier Functions
  16649. b3p0: function ( t, p ) {
  16650. var k = 1 - t;
  16651. return k * k * k * p;
  16652. },
  16653. b3p1: function ( t, p ) {
  16654. var k = 1 - t;
  16655. return 3 * k * k * t * p;
  16656. },
  16657. b3p2: function ( t, p ) {
  16658. var k = 1 - t;
  16659. return 3 * k * t * t * p;
  16660. },
  16661. b3p3: function ( t, p ) {
  16662. return t * t * t * p;
  16663. },
  16664. b3: function ( t, p0, p1, p2, p3 ) {
  16665. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  16666. }
  16667. };
  16668. /**
  16669. * @author mikael emtinger / http://gomo.se/
  16670. */
  16671. THREE.AnimationHandler = (function() {
  16672. var playing = [];
  16673. var library = {};
  16674. var that = {};
  16675. //--- update ---
  16676. that.update = function( deltaTimeMS ) {
  16677. for( var i = 0; i < playing.length; i ++ )
  16678. playing[ i ].update( deltaTimeMS );
  16679. };
  16680. //--- add ---
  16681. that.addToUpdate = function( animation ) {
  16682. if ( playing.indexOf( animation ) === -1 )
  16683. playing.push( animation );
  16684. };
  16685. //--- remove ---
  16686. that.removeFromUpdate = function( animation ) {
  16687. var index = playing.indexOf( animation );
  16688. if( index !== -1 )
  16689. playing.splice( index, 1 );
  16690. };
  16691. //--- add ---
  16692. that.add = function( data ) {
  16693. if ( library[ data.name ] !== undefined )
  16694. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  16695. library[ data.name ] = data;
  16696. initData( data );
  16697. };
  16698. //--- get ---
  16699. that.get = function( name ) {
  16700. if ( typeof name === "string" ) {
  16701. if ( library[ name ] ) {
  16702. return library[ name ];
  16703. } else {
  16704. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  16705. return null;
  16706. }
  16707. } else {
  16708. // todo: add simple tween library
  16709. }
  16710. };
  16711. //--- parse ---
  16712. that.parse = function( root ) {
  16713. // setup hierarchy
  16714. var hierarchy = [];
  16715. if ( root instanceof THREE.SkinnedMesh ) {
  16716. for( var b = 0; b < root.bones.length; b++ ) {
  16717. hierarchy.push( root.bones[ b ] );
  16718. }
  16719. } else {
  16720. parseRecurseHierarchy( root, hierarchy );
  16721. }
  16722. return hierarchy;
  16723. };
  16724. var parseRecurseHierarchy = function( root, hierarchy ) {
  16725. hierarchy.push( root );
  16726. for( var c = 0; c < root.children.length; c++ )
  16727. parseRecurseHierarchy( root.children[ c ], hierarchy );
  16728. }
  16729. //--- init data ---
  16730. var initData = function( data ) {
  16731. if( data.initialized === true )
  16732. return;
  16733. // loop through all keys
  16734. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  16735. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16736. // remove minus times
  16737. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  16738. data.hierarchy[ h ].keys[ k ].time = 0;
  16739. // create quaternions
  16740. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  16741. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  16742. var quat = data.hierarchy[ h ].keys[ k ].rot;
  16743. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  16744. }
  16745. }
  16746. // prepare morph target keys
  16747. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  16748. // get all used
  16749. var usedMorphTargets = {};
  16750. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16751. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16752. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  16753. usedMorphTargets[ morphTargetName ] = -1;
  16754. }
  16755. }
  16756. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  16757. // set all used on all frames
  16758. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16759. var influences = {};
  16760. for ( var morphTargetName in usedMorphTargets ) {
  16761. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  16762. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  16763. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  16764. break;
  16765. }
  16766. }
  16767. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  16768. influences[ morphTargetName ] = 0;
  16769. }
  16770. }
  16771. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  16772. }
  16773. }
  16774. // remove all keys that are on the same time
  16775. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16776. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  16777. data.hierarchy[ h ].keys.splice( k, 1 );
  16778. k --;
  16779. }
  16780. }
  16781. // set index
  16782. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  16783. data.hierarchy[ h ].keys[ k ].index = k;
  16784. }
  16785. }
  16786. // JIT
  16787. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  16788. data.JIT = {};
  16789. data.JIT.hierarchy = [];
  16790. for( var h = 0; h < data.hierarchy.length; h ++ )
  16791. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  16792. // done
  16793. data.initialized = true;
  16794. };
  16795. // interpolation types
  16796. that.LINEAR = 0;
  16797. that.CATMULLROM = 1;
  16798. that.CATMULLROM_FORWARD = 2;
  16799. return that;
  16800. }());
  16801. /**
  16802. * @author mikael emtinger / http://gomo.se/
  16803. * @author mrdoob / http://mrdoob.com/
  16804. * @author alteredq / http://alteredqualia.com/
  16805. */
  16806. THREE.Animation = function ( root, name, interpolationType ) {
  16807. this.root = root;
  16808. this.data = THREE.AnimationHandler.get( name );
  16809. this.hierarchy = THREE.AnimationHandler.parse( root );
  16810. this.currentTime = 0;
  16811. this.timeScale = 1;
  16812. this.isPlaying = false;
  16813. this.isPaused = true;
  16814. this.loop = true;
  16815. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  16816. this.points = [];
  16817. this.target = new THREE.Vector3();
  16818. };
  16819. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  16820. if ( this.isPlaying === false ) {
  16821. this.isPlaying = true;
  16822. this.loop = loop !== undefined ? loop : true;
  16823. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  16824. // reset key cache
  16825. var h, hl = this.hierarchy.length,
  16826. object;
  16827. for ( h = 0; h < hl; h ++ ) {
  16828. object = this.hierarchy[ h ];
  16829. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16830. object.useQuaternion = true;
  16831. }
  16832. object.matrixAutoUpdate = true;
  16833. if ( object.animationCache === undefined ) {
  16834. object.animationCache = {};
  16835. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  16836. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  16837. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  16838. }
  16839. var prevKey = object.animationCache.prevKey;
  16840. var nextKey = object.animationCache.nextKey;
  16841. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  16842. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  16843. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  16844. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  16845. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  16846. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  16847. }
  16848. this.update( 0 );
  16849. }
  16850. this.isPaused = false;
  16851. THREE.AnimationHandler.addToUpdate( this );
  16852. };
  16853. THREE.Animation.prototype.pause = function() {
  16854. if ( this.isPaused === true ) {
  16855. THREE.AnimationHandler.addToUpdate( this );
  16856. } else {
  16857. THREE.AnimationHandler.removeFromUpdate( this );
  16858. }
  16859. this.isPaused = !this.isPaused;
  16860. };
  16861. THREE.Animation.prototype.stop = function() {
  16862. this.isPlaying = false;
  16863. this.isPaused = false;
  16864. THREE.AnimationHandler.removeFromUpdate( this );
  16865. };
  16866. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  16867. // early out
  16868. if ( this.isPlaying === false ) return;
  16869. // vars
  16870. var types = [ "pos", "rot", "scl" ];
  16871. var type;
  16872. var scale;
  16873. var vector;
  16874. var prevXYZ, nextXYZ;
  16875. var prevKey, nextKey;
  16876. var object;
  16877. var animationCache;
  16878. var frame;
  16879. var JIThierarchy = this.data.JIT.hierarchy;
  16880. var currentTime, unloopedCurrentTime;
  16881. var currentPoint, forwardPoint, angle;
  16882. this.currentTime += deltaTimeMS * this.timeScale;
  16883. unloopedCurrentTime = this.currentTime;
  16884. currentTime = this.currentTime = this.currentTime % this.data.length;
  16885. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  16886. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  16887. object = this.hierarchy[ h ];
  16888. animationCache = object.animationCache;
  16889. // loop through pos/rot/scl
  16890. for ( var t = 0; t < 3; t ++ ) {
  16891. // get keys
  16892. type = types[ t ];
  16893. prevKey = animationCache.prevKey[ type ];
  16894. nextKey = animationCache.nextKey[ type ];
  16895. // switch keys?
  16896. if ( nextKey.time <= unloopedCurrentTime ) {
  16897. // did we loop?
  16898. if ( currentTime < unloopedCurrentTime ) {
  16899. if ( this.loop ) {
  16900. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  16901. nextKey = this.getNextKeyWith( type, h, 1 );
  16902. while( nextKey.time < currentTime ) {
  16903. prevKey = nextKey;
  16904. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16905. }
  16906. } else {
  16907. this.stop();
  16908. return;
  16909. }
  16910. } else {
  16911. do {
  16912. prevKey = nextKey;
  16913. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  16914. } while( nextKey.time < currentTime )
  16915. }
  16916. animationCache.prevKey[ type ] = prevKey;
  16917. animationCache.nextKey[ type ] = nextKey;
  16918. }
  16919. object.matrixAutoUpdate = true;
  16920. object.matrixWorldNeedsUpdate = true;
  16921. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  16922. prevXYZ = prevKey[ type ];
  16923. nextXYZ = nextKey[ type ];
  16924. // check scale error
  16925. if ( scale < 0 || scale > 1 ) {
  16926. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  16927. scale = scale < 0 ? 0 : 1;
  16928. }
  16929. // interpolate
  16930. if ( type === "pos" ) {
  16931. vector = object.position;
  16932. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  16933. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16934. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16935. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16936. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  16937. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16938. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  16939. this.points[ 1 ] = prevXYZ;
  16940. this.points[ 2 ] = nextXYZ;
  16941. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  16942. scale = scale * 0.33 + 0.33;
  16943. currentPoint = this.interpolateCatmullRom( this.points, scale );
  16944. vector.x = currentPoint[ 0 ];
  16945. vector.y = currentPoint[ 1 ];
  16946. vector.z = currentPoint[ 2 ];
  16947. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  16948. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  16949. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  16950. this.target.subSelf( vector );
  16951. this.target.y = 0;
  16952. this.target.normalize();
  16953. angle = Math.atan2( this.target.x, this.target.z );
  16954. object.rotation.set( 0, angle, 0 );
  16955. }
  16956. }
  16957. } else if ( type === "rot" ) {
  16958. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  16959. } else if ( type === "scl" ) {
  16960. vector = object.scale;
  16961. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  16962. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  16963. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  16964. }
  16965. }
  16966. }
  16967. };
  16968. // Catmull-Rom spline
  16969. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  16970. var c = [], v3 = [],
  16971. point, intPoint, weight, w2, w3,
  16972. pa, pb, pc, pd;
  16973. point = ( points.length - 1 ) * scale;
  16974. intPoint = Math.floor( point );
  16975. weight = point - intPoint;
  16976. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  16977. c[ 1 ] = intPoint;
  16978. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  16979. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  16980. pa = points[ c[ 0 ] ];
  16981. pb = points[ c[ 1 ] ];
  16982. pc = points[ c[ 2 ] ];
  16983. pd = points[ c[ 3 ] ];
  16984. w2 = weight * weight;
  16985. w3 = weight * w2;
  16986. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  16987. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  16988. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  16989. return v3;
  16990. };
  16991. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  16992. var v0 = ( p2 - p0 ) * 0.5,
  16993. v1 = ( p3 - p1 ) * 0.5;
  16994. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16995. };
  16996. // Get next key with
  16997. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  16998. var keys = this.data.hierarchy[ h ].keys;
  16999. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17000. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17001. key = key < keys.length - 1 ? key : keys.length - 1;
  17002. } else {
  17003. key = key % keys.length;
  17004. }
  17005. for ( ; key < keys.length; key++ ) {
  17006. if ( keys[ key ][ type ] !== undefined ) {
  17007. return keys[ key ];
  17008. }
  17009. }
  17010. return this.data.hierarchy[ h ].keys[ 0 ];
  17011. };
  17012. // Get previous key with
  17013. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17014. var keys = this.data.hierarchy[ h ].keys;
  17015. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17016. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17017. key = key > 0 ? key : 0;
  17018. } else {
  17019. key = key >= 0 ? key : key + keys.length;
  17020. }
  17021. for ( ; key >= 0; key -- ) {
  17022. if ( keys[ key ][ type ] !== undefined ) {
  17023. return keys[ key ];
  17024. }
  17025. }
  17026. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17027. };
  17028. /**
  17029. * @author mikael emtinger / http://gomo.se/
  17030. * @author mrdoob / http://mrdoob.com/
  17031. * @author alteredq / http://alteredqualia.com/
  17032. * @author khang duong
  17033. * @author erik kitson
  17034. */
  17035. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17036. this.root = root;
  17037. this.data = THREE.AnimationHandler.get( data );
  17038. this.hierarchy = THREE.AnimationHandler.parse( root );
  17039. this.currentTime = 0;
  17040. this.timeScale = 0.001;
  17041. this.isPlaying = false;
  17042. this.isPaused = true;
  17043. this.loop = true;
  17044. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17045. // initialize to first keyframes
  17046. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17047. var keys = this.data.hierarchy[h].keys,
  17048. sids = this.data.hierarchy[h].sids,
  17049. obj = this.hierarchy[h];
  17050. if ( keys.length && sids ) {
  17051. for ( var s = 0; s < sids.length; s++ ) {
  17052. var sid = sids[ s ],
  17053. next = this.getNextKeyWith( sid, h, 0 );
  17054. if ( next ) {
  17055. next.apply( sid );
  17056. }
  17057. }
  17058. obj.matrixAutoUpdate = false;
  17059. this.data.hierarchy[h].node.updateMatrix();
  17060. obj.matrixWorldNeedsUpdate = true;
  17061. }
  17062. }
  17063. };
  17064. // Play
  17065. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17066. if( !this.isPlaying ) {
  17067. this.isPlaying = true;
  17068. this.loop = loop !== undefined ? loop : true;
  17069. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17070. this.startTimeMs = startTimeMS;
  17071. this.startTime = 10000000;
  17072. this.endTime = -this.startTime;
  17073. // reset key cache
  17074. var h, hl = this.hierarchy.length,
  17075. object,
  17076. node;
  17077. for ( h = 0; h < hl; h++ ) {
  17078. object = this.hierarchy[ h ];
  17079. node = this.data.hierarchy[ h ];
  17080. object.useQuaternion = true;
  17081. if ( node.animationCache === undefined ) {
  17082. node.animationCache = {};
  17083. node.animationCache.prevKey = null;
  17084. node.animationCache.nextKey = null;
  17085. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17086. }
  17087. var keys = this.data.hierarchy[h].keys;
  17088. if (keys.length) {
  17089. node.animationCache.prevKey = keys[ 0 ];
  17090. node.animationCache.nextKey = keys[ 1 ];
  17091. this.startTime = Math.min( keys[0].time, this.startTime );
  17092. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  17093. }
  17094. }
  17095. this.update( 0 );
  17096. }
  17097. this.isPaused = false;
  17098. THREE.AnimationHandler.addToUpdate( this );
  17099. };
  17100. // Pause
  17101. THREE.KeyFrameAnimation.prototype.pause = function() {
  17102. if( this.isPaused ) {
  17103. THREE.AnimationHandler.addToUpdate( this );
  17104. } else {
  17105. THREE.AnimationHandler.removeFromUpdate( this );
  17106. }
  17107. this.isPaused = !this.isPaused;
  17108. };
  17109. // Stop
  17110. THREE.KeyFrameAnimation.prototype.stop = function() {
  17111. this.isPlaying = false;
  17112. this.isPaused = false;
  17113. THREE.AnimationHandler.removeFromUpdate( this );
  17114. // reset JIT matrix and remove cache
  17115. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  17116. var obj = this.hierarchy[ h ];
  17117. var node = this.data.hierarchy[ h ];
  17118. if ( node.animationCache !== undefined ) {
  17119. var original = node.animationCache.originalMatrix;
  17120. if( obj instanceof THREE.Bone ) {
  17121. original.copy( obj.skinMatrix );
  17122. obj.skinMatrix = original;
  17123. } else {
  17124. original.copy( obj.matrix );
  17125. obj.matrix = original;
  17126. }
  17127. delete node.animationCache;
  17128. }
  17129. }
  17130. };
  17131. // Update
  17132. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  17133. // early out
  17134. if( !this.isPlaying ) return;
  17135. // vars
  17136. var prevKey, nextKey;
  17137. var object;
  17138. var node;
  17139. var frame;
  17140. var JIThierarchy = this.data.JIT.hierarchy;
  17141. var currentTime, unloopedCurrentTime;
  17142. var looped;
  17143. // update
  17144. this.currentTime += deltaTimeMS * this.timeScale;
  17145. unloopedCurrentTime = this.currentTime;
  17146. currentTime = this.currentTime = this.currentTime % this.data.length;
  17147. // if looped around, the current time should be based on the startTime
  17148. if ( currentTime < this.startTimeMs ) {
  17149. currentTime = this.currentTime = this.startTimeMs + currentTime;
  17150. }
  17151. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17152. looped = currentTime < unloopedCurrentTime;
  17153. if ( looped && !this.loop ) {
  17154. // Set the animation to the last keyframes and stop
  17155. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17156. var keys = this.data.hierarchy[h].keys,
  17157. sids = this.data.hierarchy[h].sids,
  17158. end = keys.length-1,
  17159. obj = this.hierarchy[h];
  17160. if ( keys.length ) {
  17161. for ( var s = 0; s < sids.length; s++ ) {
  17162. var sid = sids[ s ],
  17163. prev = this.getPrevKeyWith( sid, h, end );
  17164. if ( prev ) {
  17165. prev.apply( sid );
  17166. }
  17167. }
  17168. this.data.hierarchy[h].node.updateMatrix();
  17169. obj.matrixWorldNeedsUpdate = true;
  17170. }
  17171. }
  17172. this.stop();
  17173. return;
  17174. }
  17175. // check pre-infinity
  17176. if ( currentTime < this.startTime ) {
  17177. return;
  17178. }
  17179. // update
  17180. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17181. object = this.hierarchy[ h ];
  17182. node = this.data.hierarchy[ h ];
  17183. var keys = node.keys,
  17184. animationCache = node.animationCache;
  17185. // use JIT?
  17186. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  17187. if( object instanceof THREE.Bone ) {
  17188. object.skinMatrix = JIThierarchy[ h ][ frame ];
  17189. object.matrixWorldNeedsUpdate = false;
  17190. } else {
  17191. object.matrix = JIThierarchy[ h ][ frame ];
  17192. object.matrixWorldNeedsUpdate = true;
  17193. }
  17194. // use interpolation
  17195. } else if ( keys.length ) {
  17196. // make sure so original matrix and not JIT matrix is set
  17197. if ( this.JITCompile && animationCache ) {
  17198. if( object instanceof THREE.Bone ) {
  17199. object.skinMatrix = animationCache.originalMatrix;
  17200. } else {
  17201. object.matrix = animationCache.originalMatrix;
  17202. }
  17203. }
  17204. prevKey = animationCache.prevKey;
  17205. nextKey = animationCache.nextKey;
  17206. if ( prevKey && nextKey ) {
  17207. // switch keys?
  17208. if ( nextKey.time <= unloopedCurrentTime ) {
  17209. // did we loop?
  17210. if ( looped && this.loop ) {
  17211. prevKey = keys[ 0 ];
  17212. nextKey = keys[ 1 ];
  17213. while ( nextKey.time < currentTime ) {
  17214. prevKey = nextKey;
  17215. nextKey = keys[ prevKey.index + 1 ];
  17216. }
  17217. } else if ( !looped ) {
  17218. var lastIndex = keys.length - 1;
  17219. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  17220. prevKey = nextKey;
  17221. nextKey = keys[ prevKey.index + 1 ];
  17222. }
  17223. }
  17224. animationCache.prevKey = prevKey;
  17225. animationCache.nextKey = nextKey;
  17226. }
  17227. if(nextKey.time >= currentTime)
  17228. prevKey.interpolate( nextKey, currentTime );
  17229. else
  17230. prevKey.interpolate( nextKey, nextKey.time);
  17231. }
  17232. this.data.hierarchy[h].node.updateMatrix();
  17233. object.matrixWorldNeedsUpdate = true;
  17234. }
  17235. }
  17236. // update JIT?
  17237. if ( this.JITCompile ) {
  17238. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  17239. this.hierarchy[ 0 ].updateMatrixWorld( true );
  17240. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  17241. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  17242. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  17243. } else {
  17244. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  17245. }
  17246. }
  17247. }
  17248. }
  17249. };
  17250. // Get next key with
  17251. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  17252. var keys = this.data.hierarchy[ h ].keys;
  17253. key = key % keys.length;
  17254. for ( ; key < keys.length; key++ ) {
  17255. if ( keys[ key ].hasTarget( sid ) ) {
  17256. return keys[ key ];
  17257. }
  17258. }
  17259. return keys[ 0 ];
  17260. };
  17261. // Get previous key with
  17262. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  17263. var keys = this.data.hierarchy[ h ].keys;
  17264. key = key >= 0 ? key : key + keys.length;
  17265. for ( ; key >= 0; key-- ) {
  17266. if ( keys[ key ].hasTarget( sid ) ) {
  17267. return keys[ key ];
  17268. }
  17269. }
  17270. return keys[ keys.length - 1 ];
  17271. };
  17272. /**
  17273. * Camera for rendering cube maps
  17274. * - renders scene into axis-aligned cube
  17275. *
  17276. * @author alteredq / http://alteredqualia.com/
  17277. */
  17278. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  17279. THREE.Object3D.call( this );
  17280. var fov = 90, aspect = 1;
  17281. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17282. cameraPX.up.set( 0, -1, 0 );
  17283. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  17284. this.add( cameraPX );
  17285. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17286. cameraNX.up.set( 0, -1, 0 );
  17287. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  17288. this.add( cameraNX );
  17289. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17290. cameraPY.up.set( 0, 0, 1 );
  17291. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  17292. this.add( cameraPY );
  17293. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17294. cameraNY.up.set( 0, 0, -1 );
  17295. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  17296. this.add( cameraNY );
  17297. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17298. cameraPZ.up.set( 0, -1, 0 );
  17299. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  17300. this.add( cameraPZ );
  17301. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  17302. cameraNZ.up.set( 0, -1, 0 );
  17303. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  17304. this.add( cameraNZ );
  17305. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  17306. this.updateCubeMap = function ( renderer, scene ) {
  17307. var renderTarget = this.renderTarget;
  17308. var generateMipmaps = renderTarget.generateMipmaps;
  17309. renderTarget.generateMipmaps = false;
  17310. renderTarget.activeCubeFace = 0;
  17311. renderer.render( scene, cameraPX, renderTarget );
  17312. renderTarget.activeCubeFace = 1;
  17313. renderer.render( scene, cameraNX, renderTarget );
  17314. renderTarget.activeCubeFace = 2;
  17315. renderer.render( scene, cameraPY, renderTarget );
  17316. renderTarget.activeCubeFace = 3;
  17317. renderer.render( scene, cameraNY, renderTarget );
  17318. renderTarget.activeCubeFace = 4;
  17319. renderer.render( scene, cameraPZ, renderTarget );
  17320. renderTarget.generateMipmaps = generateMipmaps;
  17321. renderTarget.activeCubeFace = 5;
  17322. renderer.render( scene, cameraNZ, renderTarget );
  17323. };
  17324. };
  17325. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  17326. /*
  17327. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  17328. *
  17329. * A general perpose camera, for setting FOV, Lens Focal Length,
  17330. * and switching between perspective and orthographic views easily.
  17331. * Use this only if you do not wish to manage
  17332. * both a Orthographic and Perspective Camera
  17333. *
  17334. */
  17335. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  17336. THREE.Camera.call( this );
  17337. this.fov = fov;
  17338. this.left = -width / 2;
  17339. this.right = width / 2
  17340. this.top = height / 2;
  17341. this.bottom = -height / 2;
  17342. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  17343. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  17344. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  17345. this.zoom = 1;
  17346. this.toPerspective();
  17347. var aspect = width/height;
  17348. };
  17349. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  17350. THREE.CombinedCamera.prototype.toPerspective = function () {
  17351. // Switches to the Perspective Camera
  17352. this.near = this.cameraP.near;
  17353. this.far = this.cameraP.far;
  17354. this.cameraP.fov = this.fov / this.zoom ;
  17355. this.cameraP.updateProjectionMatrix();
  17356. this.projectionMatrix = this.cameraP.projectionMatrix;
  17357. this.inPerspectiveMode = true;
  17358. this.inOrthographicMode = false;
  17359. };
  17360. THREE.CombinedCamera.prototype.toOrthographic = function () {
  17361. // Switches to the Orthographic camera estimating viewport from Perspective
  17362. var fov = this.fov;
  17363. var aspect = this.cameraP.aspect;
  17364. var near = this.cameraP.near;
  17365. var far = this.cameraP.far;
  17366. // The size that we set is the mid plane of the viewing frustum
  17367. var hyperfocus = ( near + far ) / 2;
  17368. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  17369. var planeHeight = 2 * halfHeight;
  17370. var planeWidth = planeHeight * aspect;
  17371. var halfWidth = planeWidth / 2;
  17372. halfHeight /= this.zoom;
  17373. halfWidth /= this.zoom;
  17374. this.cameraO.left = -halfWidth;
  17375. this.cameraO.right = halfWidth;
  17376. this.cameraO.top = halfHeight;
  17377. this.cameraO.bottom = -halfHeight;
  17378. // this.cameraO.left = -farHalfWidth;
  17379. // this.cameraO.right = farHalfWidth;
  17380. // this.cameraO.top = farHalfHeight;
  17381. // this.cameraO.bottom = -farHalfHeight;
  17382. // this.cameraO.left = this.left / this.zoom;
  17383. // this.cameraO.right = this.right / this.zoom;
  17384. // this.cameraO.top = this.top / this.zoom;
  17385. // this.cameraO.bottom = this.bottom / this.zoom;
  17386. this.cameraO.updateProjectionMatrix();
  17387. this.near = this.cameraO.near;
  17388. this.far = this.cameraO.far;
  17389. this.projectionMatrix = this.cameraO.projectionMatrix;
  17390. this.inPerspectiveMode = false;
  17391. this.inOrthographicMode = true;
  17392. };
  17393. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  17394. this.cameraP.aspect = width / height;
  17395. this.left = -width / 2;
  17396. this.right = width / 2
  17397. this.top = height / 2;
  17398. this.bottom = -height / 2;
  17399. };
  17400. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  17401. this.fov = fov;
  17402. if ( this.inPerspectiveMode ) {
  17403. this.toPerspective();
  17404. } else {
  17405. this.toOrthographic();
  17406. }
  17407. };
  17408. // For mantaining similar API with PerspectiveCamera
  17409. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  17410. if ( this.inPerspectiveMode ) {
  17411. this.toPerspective();
  17412. } else {
  17413. this.toPerspective();
  17414. this.toOrthographic();
  17415. }
  17416. };
  17417. /*
  17418. * Uses Focal Length (in mm) to estimate and set FOV
  17419. * 35mm (fullframe) camera is used if frame size is not specified;
  17420. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  17421. */
  17422. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  17423. if ( frameHeight === undefined ) frameHeight = 24;
  17424. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  17425. this.setFov( fov );
  17426. return fov;
  17427. };
  17428. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  17429. this.zoom = zoom;
  17430. if ( this.inPerspectiveMode ) {
  17431. this.toPerspective();
  17432. } else {
  17433. this.toOrthographic();
  17434. }
  17435. };
  17436. THREE.CombinedCamera.prototype.toFrontView = function() {
  17437. this.rotation.x = 0;
  17438. this.rotation.y = 0;
  17439. this.rotation.z = 0;
  17440. // should we be modifing the matrix instead?
  17441. this.rotationAutoUpdate = false;
  17442. };
  17443. THREE.CombinedCamera.prototype.toBackView = function() {
  17444. this.rotation.x = 0;
  17445. this.rotation.y = Math.PI;
  17446. this.rotation.z = 0;
  17447. this.rotationAutoUpdate = false;
  17448. };
  17449. THREE.CombinedCamera.prototype.toLeftView = function() {
  17450. this.rotation.x = 0;
  17451. this.rotation.y = - Math.PI / 2;
  17452. this.rotation.z = 0;
  17453. this.rotationAutoUpdate = false;
  17454. };
  17455. THREE.CombinedCamera.prototype.toRightView = function() {
  17456. this.rotation.x = 0;
  17457. this.rotation.y = Math.PI / 2;
  17458. this.rotation.z = 0;
  17459. this.rotationAutoUpdate = false;
  17460. };
  17461. THREE.CombinedCamera.prototype.toTopView = function() {
  17462. this.rotation.x = - Math.PI / 2;
  17463. this.rotation.y = 0;
  17464. this.rotation.z = 0;
  17465. this.rotationAutoUpdate = false;
  17466. };
  17467. THREE.CombinedCamera.prototype.toBottomView = function() {
  17468. this.rotation.x = Math.PI / 2;
  17469. this.rotation.y = 0;
  17470. this.rotation.z = 0;
  17471. this.rotationAutoUpdate = false;
  17472. };
  17473. /**
  17474. * @author hughes
  17475. */
  17476. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  17477. THREE.Geometry.call( this );
  17478. radius = radius || 50;
  17479. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  17480. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  17481. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  17482. var i, uvs = [],
  17483. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  17484. this.vertices.push(center);
  17485. uvs.push( centerUV );
  17486. for ( i = 0; i <= segments; i ++ ) {
  17487. var vertex = new THREE.Vector3();
  17488. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  17489. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  17490. this.vertices.push( vertex );
  17491. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  17492. }
  17493. var n = new THREE.Vector3( 0, 0, -1 );
  17494. for ( i = 1; i <= segments; i ++ ) {
  17495. var v1 = i;
  17496. var v2 = i + 1 ;
  17497. var v3 = 0;
  17498. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  17499. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  17500. }
  17501. this.computeCentroids();
  17502. this.computeFaceNormals();
  17503. this.boundingSphere = { radius: radius };
  17504. };
  17505. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17506. /**
  17507. * @author mrdoob / http://mrdoob.com/
  17508. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  17509. */
  17510. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments, materials, sides ) {
  17511. THREE.Geometry.call( this );
  17512. var scope = this;
  17513. this.width = width;
  17514. this.height = height;
  17515. this.depth = depth;
  17516. this.widthSegments = widthSegments || 1;
  17517. this.heightSegments = heightSegments || 1;
  17518. this.depthSegments = depthSegments || 1;
  17519. var width_half = this.width / 2;
  17520. var height_half = this.height / 2;
  17521. var depth_half = this.depth / 2;
  17522. var mpx, mpy, mpz, mnx, mny, mnz;
  17523. if ( materials !== undefined ) {
  17524. if ( materials instanceof Array ) {
  17525. this.materials = materials;
  17526. } else {
  17527. this.materials = [];
  17528. for ( var i = 0; i < 6; i ++ ) {
  17529. this.materials.push( materials );
  17530. }
  17531. }
  17532. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  17533. } else {
  17534. this.materials = [];
  17535. }
  17536. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  17537. if ( sides != undefined ) {
  17538. for ( var s in sides ) {
  17539. if ( this.sides[ s ] !== undefined ) {
  17540. this.sides[ s ] = sides[ s ];
  17541. }
  17542. }
  17543. }
  17544. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, mpx ); // px
  17545. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, mnx ); // nx
  17546. this.sides.py && buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, mpy ); // py
  17547. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, mny ); // ny
  17548. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, mpz ); // pz
  17549. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, mnz ); // nz
  17550. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  17551. var w, ix, iy,
  17552. gridX = scope.widthSegments,
  17553. gridY = scope.heightSegments,
  17554. width_half = width / 2,
  17555. height_half = height / 2,
  17556. offset = scope.vertices.length;
  17557. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  17558. w = 'z';
  17559. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  17560. w = 'y';
  17561. gridY = scope.depthSegments;
  17562. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  17563. w = 'x';
  17564. gridX = scope.depthSegments;
  17565. }
  17566. var gridX1 = gridX + 1,
  17567. gridY1 = gridY + 1,
  17568. segment_width = width / gridX,
  17569. segment_height = height / gridY,
  17570. normal = new THREE.Vector3();
  17571. normal[ w ] = depth > 0 ? 1 : - 1;
  17572. for ( iy = 0; iy < gridY1; iy ++ ) {
  17573. for ( ix = 0; ix < gridX1; ix ++ ) {
  17574. var vector = new THREE.Vector3();
  17575. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  17576. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  17577. vector[ w ] = depth;
  17578. scope.vertices.push( vector );
  17579. }
  17580. }
  17581. for ( iy = 0; iy < gridY; iy++ ) {
  17582. for ( ix = 0; ix < gridX; ix++ ) {
  17583. var a = ix + gridX1 * iy;
  17584. var b = ix + gridX1 * ( iy + 1 );
  17585. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  17586. var d = ( ix + 1 ) + gridX1 * iy;
  17587. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  17588. face.normal.copy( normal );
  17589. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  17590. face.materialIndex = material;
  17591. scope.faces.push( face );
  17592. scope.faceVertexUvs[ 0 ].push( [
  17593. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  17594. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  17595. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  17596. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  17597. ] );
  17598. }
  17599. }
  17600. }
  17601. this.computeCentroids();
  17602. this.mergeVertices();
  17603. };
  17604. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17605. /**
  17606. * @author mrdoob / http://mrdoob.com/
  17607. */
  17608. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  17609. THREE.Geometry.call( this );
  17610. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  17611. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  17612. height = height !== undefined ? height : 100;
  17613. var heightHalf = height / 2;
  17614. var segmentsX = radiusSegments || 8;
  17615. var segmentsY = heightSegments || 1;
  17616. var x, y, vertices = [], uvs = [];
  17617. for ( y = 0; y <= segmentsY; y ++ ) {
  17618. var verticesRow = [];
  17619. var uvsRow = [];
  17620. var v = y / segmentsY;
  17621. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  17622. for ( x = 0; x <= segmentsX; x ++ ) {
  17623. var u = x / segmentsX;
  17624. var vertex = new THREE.Vector3();
  17625. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  17626. vertex.y = - v * height + heightHalf;
  17627. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  17628. this.vertices.push( vertex );
  17629. verticesRow.push( this.vertices.length - 1 );
  17630. uvsRow.push( new THREE.UV( u, 1 - v ) );
  17631. }
  17632. vertices.push( verticesRow );
  17633. uvs.push( uvsRow );
  17634. }
  17635. var tanTheta = ( radiusBottom - radiusTop ) / height;
  17636. var na, nb;
  17637. for ( x = 0; x < segmentsX; x ++ ) {
  17638. if ( radiusTop !== 0 ) {
  17639. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  17640. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  17641. } else {
  17642. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  17643. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  17644. }
  17645. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  17646. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  17647. for ( y = 0; y < segmentsY; y ++ ) {
  17648. var v1 = vertices[ y ][ x ];
  17649. var v2 = vertices[ y + 1 ][ x ];
  17650. var v3 = vertices[ y + 1 ][ x + 1 ];
  17651. var v4 = vertices[ y ][ x + 1 ];
  17652. var n1 = na.clone();
  17653. var n2 = na.clone();
  17654. var n3 = nb.clone();
  17655. var n4 = nb.clone();
  17656. var uv1 = uvs[ y ][ x ].clone();
  17657. var uv2 = uvs[ y + 1 ][ x ].clone();
  17658. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  17659. var uv4 = uvs[ y ][ x + 1 ].clone();
  17660. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  17661. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  17662. }
  17663. }
  17664. // top cap
  17665. if ( !openEnded && radiusTop > 0 ) {
  17666. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  17667. for ( x = 0; x < segmentsX; x ++ ) {
  17668. var v1 = vertices[ 0 ][ x ];
  17669. var v2 = vertices[ 0 ][ x + 1 ];
  17670. var v3 = this.vertices.length - 1;
  17671. var n1 = new THREE.Vector3( 0, 1, 0 );
  17672. var n2 = new THREE.Vector3( 0, 1, 0 );
  17673. var n3 = new THREE.Vector3( 0, 1, 0 );
  17674. var uv1 = uvs[ 0 ][ x ].clone();
  17675. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  17676. var uv3 = new THREE.UV( uv2.u, 0 );
  17677. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17678. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17679. }
  17680. }
  17681. // bottom cap
  17682. if ( !openEnded && radiusBottom > 0 ) {
  17683. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  17684. for ( x = 0; x < segmentsX; x ++ ) {
  17685. var v1 = vertices[ y ][ x + 1 ];
  17686. var v2 = vertices[ y ][ x ];
  17687. var v3 = this.vertices.length - 1;
  17688. var n1 = new THREE.Vector3( 0, - 1, 0 );
  17689. var n2 = new THREE.Vector3( 0, - 1, 0 );
  17690. var n3 = new THREE.Vector3( 0, - 1, 0 );
  17691. var uv1 = uvs[ y ][ x + 1 ].clone();
  17692. var uv2 = uvs[ y ][ x ].clone();
  17693. var uv3 = new THREE.UV( uv2.u, 1 );
  17694. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  17695. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  17696. }
  17697. }
  17698. this.computeCentroids();
  17699. this.computeFaceNormals();
  17700. }
  17701. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17702. /**
  17703. * @author zz85 / http://www.lab4games.net/zz85/blog
  17704. *
  17705. * Creates extruded geometry from a path shape.
  17706. *
  17707. * parameters = {
  17708. *
  17709. * size: <float>, // size of the text
  17710. * height: <float>, // thickness to extrude text
  17711. * curveSegments: <int>, // number of points on the curves
  17712. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  17713. * amount: <int>, // Amount
  17714. *
  17715. * bevelEnabled: <bool>, // turn on bevel
  17716. * bevelThickness: <float>, // how deep into text bevel goes
  17717. * bevelSize: <float>, // how far from text outline is bevel
  17718. * bevelSegments: <int>, // number of bevel layers
  17719. *
  17720. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  17721. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  17722. *
  17723. * material: <int> // material index for front and back faces
  17724. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  17725. * uvGenerator: <Object> // object that provides UV generator functions
  17726. *
  17727. * }
  17728. **/
  17729. THREE.ExtrudeGeometry = function ( shapes, options ) {
  17730. if ( typeof( shapes ) === "undefined" ) {
  17731. shapes = [];
  17732. return;
  17733. }
  17734. THREE.Geometry.call( this );
  17735. shapes = shapes instanceof Array ? shapes : [ shapes ];
  17736. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  17737. this.addShapeList( shapes, options );
  17738. this.computeCentroids();
  17739. this.computeFaceNormals();
  17740. // can't really use automatic vertex normals
  17741. // as then front and back sides get smoothed too
  17742. // should do separate smoothing just for sides
  17743. //this.computeVertexNormals();
  17744. //console.log( "took", ( Date.now() - startTime ) );
  17745. };
  17746. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  17747. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  17748. var sl = shapes.length;
  17749. for ( var s = 0; s < sl; s ++ ) {
  17750. var shape = shapes[ s ];
  17751. this.addShape( shape, options );
  17752. }
  17753. };
  17754. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  17755. var amount = options.amount !== undefined ? options.amount : 100;
  17756. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  17757. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  17758. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  17759. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  17760. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  17761. var steps = options.steps !== undefined ? options.steps : 1;
  17762. var extrudePath = options.extrudePath;
  17763. var extrudePts, extrudeByPath = false;
  17764. var material = options.material;
  17765. var extrudeMaterial = options.extrudeMaterial;
  17766. // Use default WorldUVGenerator if no UV generators are specified.
  17767. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  17768. var shapebb = this.shapebb;
  17769. //shapebb = shape.getBoundingBox();
  17770. var splineTube, binormal, normal, position2;
  17771. if ( extrudePath ) {
  17772. extrudePts = extrudePath.getSpacedPoints( steps );
  17773. extrudeByPath = true;
  17774. bevelEnabled = false; // bevels not supported for path extrusion
  17775. // SETUP TNB variables
  17776. // Reuse TNB from TubeGeomtry for now.
  17777. // TODO1 - have a .isClosed in spline?
  17778. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  17779. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  17780. binormal = new THREE.Vector3();
  17781. normal = new THREE.Vector3();
  17782. position2 = new THREE.Vector3();
  17783. }
  17784. // Safeguards if bevels are not enabled
  17785. if ( ! bevelEnabled ) {
  17786. bevelSegments = 0;
  17787. bevelThickness = 0;
  17788. bevelSize = 0;
  17789. }
  17790. // Variables initalization
  17791. var ahole, h, hl; // looping of holes
  17792. var scope = this;
  17793. var bevelPoints = [];
  17794. var shapesOffset = this.vertices.length;
  17795. var shapePoints = shape.extractPoints();
  17796. var vertices = shapePoints.shape;
  17797. var holes = shapePoints.holes;
  17798. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  17799. if ( reverse ) {
  17800. vertices = vertices.reverse();
  17801. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  17802. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17803. ahole = holes[ h ];
  17804. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  17805. holes[ h ] = ahole.reverse();
  17806. }
  17807. }
  17808. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  17809. }
  17810. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  17811. /* Vertices */
  17812. var contour = vertices; // vertices has all points but contour has only points of circumference
  17813. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17814. ahole = holes[ h ];
  17815. vertices = vertices.concat( ahole );
  17816. }
  17817. function scalePt2 ( pt, vec, size ) {
  17818. if ( !vec ) console.log( "die" );
  17819. return vec.clone().multiplyScalar( size ).addSelf( pt );
  17820. }
  17821. var b, bs, t, z,
  17822. vert, vlen = vertices.length,
  17823. face, flen = faces.length,
  17824. cont, clen = contour.length;
  17825. // Find directions for point movement
  17826. var RAD_TO_DEGREES = 180 / Math.PI;
  17827. function getBevelVec( pt_i, pt_j, pt_k ) {
  17828. // Algorithm 2
  17829. return getBevelVec2( pt_i, pt_j, pt_k );
  17830. }
  17831. function getBevelVec1( pt_i, pt_j, pt_k ) {
  17832. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  17833. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  17834. if ( anglea > angleb ) {
  17835. angleb += Math.PI * 2;
  17836. }
  17837. var anglec = ( anglea + angleb ) / 2;
  17838. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  17839. var x = - Math.cos( anglec );
  17840. var y = - Math.sin( anglec );
  17841. var vec = new THREE.Vector2( x, y ); //.normalize();
  17842. return vec;
  17843. }
  17844. function getBevelVec2( pt_i, pt_j, pt_k ) {
  17845. var a = THREE.ExtrudeGeometry.__v1,
  17846. b = THREE.ExtrudeGeometry.__v2,
  17847. v_hat = THREE.ExtrudeGeometry.__v3,
  17848. w_hat = THREE.ExtrudeGeometry.__v4,
  17849. p = THREE.ExtrudeGeometry.__v5,
  17850. q = THREE.ExtrudeGeometry.__v6,
  17851. v, w,
  17852. v_dot_w_hat, q_sub_p_dot_w_hat,
  17853. s, intersection;
  17854. // good reading for line-line intersection
  17855. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  17856. // define a as vector j->i
  17857. // define b as vectot k->i
  17858. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  17859. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  17860. // get unit vectors
  17861. v = a.normalize();
  17862. w = b.normalize();
  17863. // normals from pt i
  17864. v_hat.set( -v.y, v.x );
  17865. w_hat.set( w.y, -w.x );
  17866. // pts from i
  17867. p.copy( pt_i ).addSelf( v_hat );
  17868. q.copy( pt_i ).addSelf( w_hat );
  17869. if ( p.equals( q ) ) {
  17870. //console.log("Warning: lines are straight");
  17871. return w_hat.clone();
  17872. }
  17873. // Points from j, k. helps prevents points cross overover most of the time
  17874. p.copy( pt_j ).addSelf( v_hat );
  17875. q.copy( pt_k ).addSelf( w_hat );
  17876. v_dot_w_hat = v.dot( w_hat );
  17877. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  17878. // We should not reach these conditions
  17879. if ( v_dot_w_hat === 0 ) {
  17880. console.log( "Either infinite or no solutions!" );
  17881. if ( q_sub_p_dot_w_hat === 0 ) {
  17882. console.log( "Its finite solutions." );
  17883. } else {
  17884. console.log( "Too bad, no solutions." );
  17885. }
  17886. }
  17887. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  17888. if ( s < 0 ) {
  17889. // in case of emergecy, revert to algorithm 1.
  17890. return getBevelVec1( pt_i, pt_j, pt_k );
  17891. }
  17892. intersection = v.multiplyScalar( s ).addSelf( p );
  17893. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  17894. }
  17895. var contourMovements = [];
  17896. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17897. if ( j === il ) j = 0;
  17898. if ( k === il ) k = 0;
  17899. // (j)---(i)---(k)
  17900. // console.log('i,j,k', i, j , k)
  17901. var pt_i = contour[ i ];
  17902. var pt_j = contour[ j ];
  17903. var pt_k = contour[ k ];
  17904. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  17905. }
  17906. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  17907. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17908. ahole = holes[ h ];
  17909. oneHoleMovements = [];
  17910. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  17911. if ( j === il ) j = 0;
  17912. if ( k === il ) k = 0;
  17913. // (j)---(i)---(k)
  17914. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  17915. }
  17916. holesMovements.push( oneHoleMovements );
  17917. verticesMovements = verticesMovements.concat( oneHoleMovements );
  17918. }
  17919. // Loop bevelSegments, 1 for the front, 1 for the back
  17920. for ( b = 0; b < bevelSegments; b ++ ) {
  17921. //for ( b = bevelSegments; b > 0; b -- ) {
  17922. t = b / bevelSegments;
  17923. z = bevelThickness * ( 1 - t );
  17924. //z = bevelThickness * t;
  17925. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  17926. //bs = bevelSize * t ; // linear
  17927. // contract shape
  17928. for ( i = 0, il = contour.length; i < il; i ++ ) {
  17929. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  17930. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  17931. v( vert.x, vert.y, - z );
  17932. }
  17933. // expand holes
  17934. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  17935. ahole = holes[ h ];
  17936. oneHoleMovements = holesMovements[ h ];
  17937. for ( i = 0, il = ahole.length; i < il; i++ ) {
  17938. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  17939. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  17940. v( vert.x, vert.y, -z );
  17941. }
  17942. }
  17943. }
  17944. bs = bevelSize;
  17945. // Back facing vertices
  17946. for ( i = 0; i < vlen; i ++ ) {
  17947. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  17948. if ( !extrudeByPath ) {
  17949. v( vert.x, vert.y, 0 );
  17950. } else {
  17951. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  17952. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  17953. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  17954. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  17955. v( position2.x, position2.y, position2.z );
  17956. }
  17957. }
  17958. // Add stepped vertices...
  17959. // Including front facing vertices
  17960. var s;
  17961. for ( s = 1; s <= steps; s ++ ) {
  17962. for ( i = 0; i < vlen; i ++ ) {
  17963. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  17964. if ( !extrudeByPath ) {
  17965. v( vert.x, vert.y, amount / steps * s );
  17966. } else {
  17967. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  17968. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  17969. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  17970. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  17971. v( position2.x, position2.y, position2.z );
  17972. }
  17973. }
  17974. }
  17975. // Add bevel segments planes
  17976. //for ( b = 1; b <= bevelSegments; b ++ ) {
  17977. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  17978. t = b / bevelSegments;
  17979. z = bevelThickness * ( 1 - t );
  17980. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  17981. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  17982. // contract shape
  17983. for ( i = 0, il = contour.length; i < il; i ++ ) {
  17984. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  17985. v( vert.x, vert.y, amount + z );
  17986. }
  17987. // expand holes
  17988. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  17989. ahole = holes[ h ];
  17990. oneHoleMovements = holesMovements[ h ];
  17991. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  17992. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  17993. if ( !extrudeByPath ) {
  17994. v( vert.x, vert.y, amount + z );
  17995. } else {
  17996. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  17997. }
  17998. }
  17999. }
  18000. }
  18001. /* Faces */
  18002. // Top and bottom faces
  18003. buildLidFaces();
  18004. // Sides faces
  18005. buildSideFaces();
  18006. ///// Internal functions
  18007. function buildLidFaces() {
  18008. if ( bevelEnabled ) {
  18009. var layer = 0 ; // steps + 1
  18010. var offset = vlen * layer;
  18011. // Bottom faces
  18012. for ( i = 0; i < flen; i ++ ) {
  18013. face = faces[ i ];
  18014. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18015. }
  18016. layer = steps + bevelSegments * 2;
  18017. offset = vlen * layer;
  18018. // Top faces
  18019. for ( i = 0; i < flen; i ++ ) {
  18020. face = faces[ i ];
  18021. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18022. }
  18023. } else {
  18024. // Bottom faces
  18025. for ( i = 0; i < flen; i++ ) {
  18026. face = faces[ i ];
  18027. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18028. }
  18029. // Top faces
  18030. for ( i = 0; i < flen; i ++ ) {
  18031. face = faces[ i ];
  18032. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18033. }
  18034. }
  18035. }
  18036. // Create faces for the z-sides of the shape
  18037. function buildSideFaces() {
  18038. var layeroffset = 0;
  18039. sidewalls( contour, layeroffset );
  18040. layeroffset += contour.length;
  18041. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18042. ahole = holes[ h ];
  18043. sidewalls( ahole, layeroffset );
  18044. //, true
  18045. layeroffset += ahole.length;
  18046. }
  18047. }
  18048. function sidewalls( contour, layeroffset ) {
  18049. var j, k;
  18050. i = contour.length;
  18051. while ( --i >= 0 ) {
  18052. j = i;
  18053. k = i - 1;
  18054. if ( k < 0 ) k = contour.length - 1;
  18055. //console.log('b', i,j, i-1, k,vertices.length);
  18056. var s = 0, sl = steps + bevelSegments * 2;
  18057. for ( s = 0; s < sl; s ++ ) {
  18058. var slen1 = vlen * s;
  18059. var slen2 = vlen * ( s + 1 );
  18060. var a = layeroffset + j + slen1,
  18061. b = layeroffset + k + slen1,
  18062. c = layeroffset + k + slen2,
  18063. d = layeroffset + j + slen2;
  18064. f4( a, b, c, d, contour, s, sl, j, k );
  18065. }
  18066. }
  18067. }
  18068. function v( x, y, z ) {
  18069. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18070. }
  18071. function f3( a, b, c, isBottom ) {
  18072. a += shapesOffset;
  18073. b += shapesOffset;
  18074. c += shapesOffset;
  18075. // normal, color, material
  18076. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18077. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18078. scope.faceVertexUvs[ 0 ].push( uvs );
  18079. }
  18080. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18081. a += shapesOffset;
  18082. b += shapesOffset;
  18083. c += shapesOffset;
  18084. d += shapesOffset;
  18085. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18086. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  18087. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  18088. scope.faceVertexUvs[ 0 ].push( uvs );
  18089. }
  18090. };
  18091. THREE.ExtrudeGeometry.WorldUVGenerator = {
  18092. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18093. var ax = geometry.vertices[ indexA ].x,
  18094. ay = geometry.vertices[ indexA ].y,
  18095. bx = geometry.vertices[ indexB ].x,
  18096. by = geometry.vertices[ indexB ].y,
  18097. cx = geometry.vertices[ indexC ].x,
  18098. cy = geometry.vertices[ indexC ].y;
  18099. return [
  18100. new THREE.UV( ax, ay ),
  18101. new THREE.UV( bx, by ),
  18102. new THREE.UV( cx, cy )
  18103. ];
  18104. },
  18105. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  18106. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  18107. },
  18108. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  18109. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  18110. contourIndex1, contourIndex2 ) {
  18111. var ax = geometry.vertices[ indexA ].x,
  18112. ay = geometry.vertices[ indexA ].y,
  18113. az = geometry.vertices[ indexA ].z,
  18114. bx = geometry.vertices[ indexB ].x,
  18115. by = geometry.vertices[ indexB ].y,
  18116. bz = geometry.vertices[ indexB ].z,
  18117. cx = geometry.vertices[ indexC ].x,
  18118. cy = geometry.vertices[ indexC ].y,
  18119. cz = geometry.vertices[ indexC ].z,
  18120. dx = geometry.vertices[ indexD ].x,
  18121. dy = geometry.vertices[ indexD ].y,
  18122. dz = geometry.vertices[ indexD ].z;
  18123. if ( Math.abs( ay - by ) < 0.01 ) {
  18124. return [
  18125. new THREE.UV( ax, 1 - az ),
  18126. new THREE.UV( bx, 1 - bz ),
  18127. new THREE.UV( cx, 1 - cz ),
  18128. new THREE.UV( dx, 1 - dz )
  18129. ];
  18130. } else {
  18131. return [
  18132. new THREE.UV( ay, 1 - az ),
  18133. new THREE.UV( by, 1 - bz ),
  18134. new THREE.UV( cy, 1 - cz ),
  18135. new THREE.UV( dy, 1 - dz )
  18136. ];
  18137. }
  18138. }
  18139. };
  18140. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  18141. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  18142. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  18143. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  18144. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  18145. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  18146. /**
  18147. * @author jonobr1 / http://jonobr1.com
  18148. *
  18149. * Creates a one-sided polygonal geometry from a path shape. Similar to
  18150. * ExtrudeGeometry.
  18151. *
  18152. * parameters = {
  18153. *
  18154. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  18155. *
  18156. * material: <int> // material index for front and back faces
  18157. * uvGenerator: <Object> // object that provides UV generator functions
  18158. *
  18159. * }
  18160. **/
  18161. THREE.ShapeGeometry = function ( shapes, options ) {
  18162. THREE.Geometry.call( this );
  18163. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  18164. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18165. this.addShapeList( shapes, options );
  18166. this.computeCentroids();
  18167. this.computeFaceNormals();
  18168. };
  18169. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18170. /**
  18171. * Add an array of shapes to THREE.ShapeGeometry.
  18172. */
  18173. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18174. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  18175. this.addShape( shapes[ i ], options );
  18176. }
  18177. return this;
  18178. };
  18179. /**
  18180. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  18181. */
  18182. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  18183. if ( options === undefined ) options = {};
  18184. var material = options.material;
  18185. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  18186. var shapebb = this.shapebb;
  18187. //
  18188. var i, l, hole, s;
  18189. var shapesOffset = this.vertices.length;
  18190. var shapePoints = shape.extractPoints();
  18191. var vertices = shapePoints.shape;
  18192. var holes = shapePoints.holes;
  18193. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  18194. if ( reverse ) {
  18195. vertices = vertices.reverse();
  18196. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  18197. for ( i = 0, l = holes.length; i < l; i++ ) {
  18198. hole = holes[ i ];
  18199. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  18200. holes[ i ] = hole.reverse();
  18201. }
  18202. }
  18203. reverse = false;
  18204. }
  18205. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  18206. // Vertices
  18207. var contour = vertices;
  18208. for ( i = 0, l = holes.length; i < l; i++ ) {
  18209. hole = holes[ i ];
  18210. vertices = vertices.concat( hole );
  18211. }
  18212. //
  18213. var vert, vlen = vertices.length;
  18214. var face, flen = faces.length;
  18215. var cont, clen = contour.length;
  18216. for ( i = 0; i < vlen; i++ ) {
  18217. vert = vertices[ i ];
  18218. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  18219. }
  18220. for ( i = 0; i < flen; i++ ) {
  18221. face = faces[ i ];
  18222. var a = face[ 0 ] + shapesOffset;
  18223. var b = face[ 1 ] + shapesOffset;
  18224. var c = face[ 2 ] + shapesOffset;
  18225. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18226. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  18227. }
  18228. };
  18229. /**
  18230. * @author astrodud / http://astrodud.isgreat.org/
  18231. * @author zz85 / https://github.com/zz85
  18232. */
  18233. THREE.LatheGeometry = function ( points, steps, angle ) {
  18234. THREE.Geometry.call( this );
  18235. var _steps = steps || 12;
  18236. var _angle = angle || 2 * Math.PI;
  18237. var _newV = [];
  18238. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  18239. for ( var j = 0; j < points.length; j ++ ) {
  18240. _newV[ j ] = points[ j ].clone();
  18241. this.vertices.push( _newV[ j ] );
  18242. }
  18243. var i, il = _steps + 1;
  18244. for ( i = 0; i < il; i ++ ) {
  18245. for ( var j = 0; j < _newV.length; j ++ ) {
  18246. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  18247. this.vertices.push( _newV[ j ] );
  18248. }
  18249. }
  18250. for ( i = 0; i < _steps; i ++ ) {
  18251. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  18252. var a = i * kl + k;
  18253. var b = ( ( i + 1 ) % il ) * kl + k;
  18254. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  18255. var d = i * kl + ( k + 1 ) % kl;
  18256. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18257. this.faceVertexUvs[ 0 ].push( [
  18258. new THREE.UV( 1 - i / _steps, k / kl ),
  18259. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  18260. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  18261. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  18262. ] );
  18263. }
  18264. }
  18265. this.computeCentroids();
  18266. this.computeFaceNormals();
  18267. this.computeVertexNormals();
  18268. };
  18269. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18270. /**
  18271. * @author mrdoob / http://mrdoob.com/
  18272. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  18273. */
  18274. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  18275. THREE.Geometry.call( this );
  18276. this.width = width;
  18277. this.height = height;
  18278. this.widthSegments = widthSegments || 1;
  18279. this.heightSegments = heightSegments || 1;
  18280. var ix, iz;
  18281. var width_half = width / 2;
  18282. var height_half = height / 2;
  18283. var gridX = this.widthSegments;
  18284. var gridZ = this.heightSegments;
  18285. var gridX1 = gridX + 1;
  18286. var gridZ1 = gridZ + 1;
  18287. var segment_width = this.width / gridX;
  18288. var segment_height = this.height / gridZ;
  18289. var normal = new THREE.Vector3( 0, 0, 1 );
  18290. for ( iz = 0; iz < gridZ1; iz ++ ) {
  18291. for ( ix = 0; ix < gridX1; ix ++ ) {
  18292. var x = ix * segment_width - width_half;
  18293. var y = iz * segment_height - height_half;
  18294. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  18295. }
  18296. }
  18297. for ( iz = 0; iz < gridZ; iz ++ ) {
  18298. for ( ix = 0; ix < gridX; ix ++ ) {
  18299. var a = ix + gridX1 * iz;
  18300. var b = ix + gridX1 * ( iz + 1 );
  18301. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  18302. var d = ( ix + 1 ) + gridX1 * iz;
  18303. var face = new THREE.Face4( a, b, c, d );
  18304. face.normal.copy( normal );
  18305. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18306. this.faces.push( face );
  18307. this.faceVertexUvs[ 0 ].push( [
  18308. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  18309. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  18310. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  18311. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  18312. ] );
  18313. }
  18314. }
  18315. this.computeCentroids();
  18316. };
  18317. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18318. /**
  18319. * @author mrdoob / http://mrdoob.com/
  18320. */
  18321. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  18322. THREE.Geometry.call( this );
  18323. this.radius = radius || 50;
  18324. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  18325. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  18326. phiStart = phiStart !== undefined ? phiStart : 0;
  18327. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  18328. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18329. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  18330. var x, y, vertices = [], uvs = [];
  18331. for ( y = 0; y <= this.heightSegments; y ++ ) {
  18332. var verticesRow = [];
  18333. var uvsRow = [];
  18334. for ( x = 0; x <= this.widthSegments; x ++ ) {
  18335. var u = x / this.widthSegments;
  18336. var v = y / this.heightSegments;
  18337. var vertex = new THREE.Vector3();
  18338. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18339. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  18340. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  18341. this.vertices.push( vertex );
  18342. verticesRow.push( this.vertices.length - 1 );
  18343. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18344. }
  18345. vertices.push( verticesRow );
  18346. uvs.push( uvsRow );
  18347. }
  18348. for ( y = 0; y < this.heightSegments; y ++ ) {
  18349. for ( x = 0; x < this.widthSegments; x ++ ) {
  18350. var v1 = vertices[ y ][ x + 1 ];
  18351. var v2 = vertices[ y ][ x ];
  18352. var v3 = vertices[ y + 1 ][ x ];
  18353. var v4 = vertices[ y + 1 ][ x + 1 ];
  18354. var n1 = this.vertices[ v1 ].clone().normalize();
  18355. var n2 = this.vertices[ v2 ].clone().normalize();
  18356. var n3 = this.vertices[ v3 ].clone().normalize();
  18357. var n4 = this.vertices[ v4 ].clone().normalize();
  18358. var uv1 = uvs[ y ][ x + 1 ].clone();
  18359. var uv2 = uvs[ y ][ x ].clone();
  18360. var uv3 = uvs[ y + 1 ][ x ].clone();
  18361. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  18362. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  18363. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  18364. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  18365. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  18366. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18367. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18368. } else {
  18369. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18370. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18371. }
  18372. }
  18373. }
  18374. this.computeCentroids();
  18375. this.computeFaceNormals();
  18376. this.boundingSphere = { radius: this.radius };
  18377. };
  18378. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18379. /**
  18380. * @author zz85 / http://www.lab4games.net/zz85/blog
  18381. * @author alteredq / http://alteredqualia.com/
  18382. *
  18383. * For creating 3D text geometry in three.js
  18384. *
  18385. * Text = 3D Text
  18386. *
  18387. * parameters = {
  18388. * size: <float>, // size of the text
  18389. * height: <float>, // thickness to extrude text
  18390. * curveSegments: <int>, // number of points on the curves
  18391. *
  18392. * font: <string>, // font name
  18393. * weight: <string>, // font weight (normal, bold)
  18394. * style: <string>, // font style (normal, italics)
  18395. *
  18396. * bevelEnabled: <bool>, // turn on bevel
  18397. * bevelThickness: <float>, // how deep into text bevel goes
  18398. * bevelSize: <float>, // how far from text outline is bevel
  18399. * }
  18400. *
  18401. */
  18402. /* Usage Examples
  18403. // TextGeometry wrapper
  18404. var text3d = new TextGeometry( text, options );
  18405. // Complete manner
  18406. var textShapes = THREE.FontUtils.generateShapes( text, options );
  18407. var text3d = new ExtrudeGeometry( textShapes, options );
  18408. */
  18409. THREE.TextGeometry = function ( text, parameters ) {
  18410. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  18411. // translate parameters to ExtrudeGeometry API
  18412. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  18413. // defaults
  18414. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  18415. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  18416. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  18417. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  18418. };
  18419. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  18420. /**
  18421. * @author oosmoxiecode
  18422. * @author mrdoob / http://mrdoob.com/
  18423. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  18424. */
  18425. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  18426. THREE.Geometry.call( this );
  18427. var scope = this;
  18428. this.radius = radius || 100;
  18429. this.tube = tube || 40;
  18430. this.radialSegments = radialSegments || 8;
  18431. this.tubularSegments = tubularSegments || 6;
  18432. this.arc = arc || Math.PI * 2;
  18433. var center = new THREE.Vector3(), uvs = [], normals = [];
  18434. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  18435. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  18436. var u = i / this.tubularSegments * this.arc;
  18437. var v = j / this.radialSegments * Math.PI * 2;
  18438. center.x = this.radius * Math.cos( u );
  18439. center.y = this.radius * Math.sin( u );
  18440. var vertex = new THREE.Vector3();
  18441. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  18442. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  18443. vertex.z = this.tube * Math.sin( v );
  18444. this.vertices.push( vertex );
  18445. uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
  18446. normals.push( vertex.clone().subSelf( center ).normalize() );
  18447. }
  18448. }
  18449. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  18450. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  18451. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  18452. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  18453. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  18454. var d = ( this.tubularSegments + 1 ) * j + i;
  18455. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  18456. face.normal.addSelf( normals[ a ] );
  18457. face.normal.addSelf( normals[ b ] );
  18458. face.normal.addSelf( normals[ c ] );
  18459. face.normal.addSelf( normals[ d ] );
  18460. face.normal.normalize();
  18461. this.faces.push( face );
  18462. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  18463. }
  18464. }
  18465. this.computeCentroids();
  18466. };
  18467. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18468. /**
  18469. * @author oosmoxiecode
  18470. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  18471. */
  18472. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  18473. THREE.Geometry.call( this );
  18474. var scope = this;
  18475. this.radius = radius || 200;
  18476. this.tube = tube || 40;
  18477. this.radialSegments = radialSegments || 64;
  18478. this.tubularSegments = tubularSegments || 8;
  18479. this.p = p || 2;
  18480. this.q = q || 3;
  18481. this.heightScale = heightScale || 1;
  18482. this.grid = new Array(this.radialSegments);
  18483. var tang = new THREE.Vector3();
  18484. var n = new THREE.Vector3();
  18485. var bitan = new THREE.Vector3();
  18486. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18487. this.grid[ i ] = new Array( this.tubularSegments );
  18488. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18489. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  18490. var v = j / this.tubularSegments * 2 * Math.PI;
  18491. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  18492. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  18493. var cx, cy;
  18494. tang.sub( p2, p1 );
  18495. n.add( p2, p1 );
  18496. bitan.cross( tang, n );
  18497. n.cross( bitan, tang );
  18498. bitan.normalize();
  18499. n.normalize();
  18500. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18501. cy = this.tube * Math.sin( v );
  18502. p1.x += cx * n.x + cy * bitan.x;
  18503. p1.y += cx * n.y + cy * bitan.y;
  18504. p1.z += cx * n.z + cy * bitan.z;
  18505. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  18506. }
  18507. }
  18508. for ( var i = 0; i < this.radialSegments; ++ i ) {
  18509. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  18510. var ip = ( i + 1 ) % this.radialSegments;
  18511. var jp = ( j + 1 ) % this.tubularSegments;
  18512. var a = this.grid[ i ][ j ];
  18513. var b = this.grid[ ip ][ j ];
  18514. var c = this.grid[ ip ][ jp ];
  18515. var d = this.grid[ i ][ jp ];
  18516. var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
  18517. var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  18518. var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18519. var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  18520. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18521. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  18522. }
  18523. }
  18524. this.computeCentroids();
  18525. this.computeFaceNormals();
  18526. this.computeVertexNormals();
  18527. function vert( x, y, z ) {
  18528. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18529. }
  18530. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  18531. var cu = Math.cos( u );
  18532. var cv = Math.cos( v );
  18533. var su = Math.sin( u );
  18534. var quOverP = in_q / in_p * u;
  18535. var cs = Math.cos( quOverP );
  18536. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  18537. var ty = radius * ( 2 + cs ) * su * 0.5;
  18538. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  18539. return new THREE.Vector3( tx, ty, tz );
  18540. }
  18541. };
  18542. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18543. /**
  18544. * @author WestLangley / https://github.com/WestLangley
  18545. * @author zz85 / https://github.com/zz85
  18546. * @author miningold / https://github.com/miningold
  18547. *
  18548. * Modified from the TorusKnotGeometry by @oosmoxiecode
  18549. *
  18550. * Creates a tube which extrudes along a 3d spline
  18551. *
  18552. * Uses parallel transport frames as described in
  18553. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  18554. */
  18555. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  18556. THREE.Geometry.call( this );
  18557. this.path = path;
  18558. this.segments = segments || 64;
  18559. this.radius = radius || 1;
  18560. this.radiusSegments = radiusSegments || 8;
  18561. this.closed = closed || false;
  18562. if ( debug ) this.debug = new THREE.Object3D();
  18563. this.grid = [];
  18564. var scope = this,
  18565. tangent,
  18566. normal,
  18567. binormal,
  18568. numpoints = this.segments + 1,
  18569. x, y, z,
  18570. tx, ty, tz,
  18571. u, v,
  18572. cx, cy,
  18573. pos, pos2 = new THREE.Vector3(),
  18574. i, j,
  18575. ip, jp,
  18576. a, b, c, d,
  18577. uva, uvb, uvc, uvd;
  18578. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  18579. tangents = frames.tangents,
  18580. normals = frames.normals,
  18581. binormals = frames.binormals;
  18582. // proxy internals
  18583. this.tangents = tangents;
  18584. this.normals = normals;
  18585. this.binormals = binormals;
  18586. function vert( x, y, z ) {
  18587. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  18588. }
  18589. // consruct the grid
  18590. for ( i = 0; i < numpoints; i++ ) {
  18591. this.grid[ i ] = [];
  18592. u = i / ( numpoints - 1 );
  18593. pos = path.getPointAt( u );
  18594. tangent = tangents[ i ];
  18595. normal = normals[ i ];
  18596. binormal = binormals[ i ];
  18597. if ( this.debug ) {
  18598. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  18599. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  18600. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  18601. }
  18602. for ( j = 0; j < this.radiusSegments; j++ ) {
  18603. v = j / this.radiusSegments * 2 * Math.PI;
  18604. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  18605. cy = this.radius * Math.sin( v );
  18606. pos2.copy( pos );
  18607. pos2.x += cx * normal.x + cy * binormal.x;
  18608. pos2.y += cx * normal.y + cy * binormal.y;
  18609. pos2.z += cx * normal.z + cy * binormal.z;
  18610. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  18611. }
  18612. }
  18613. // construct the mesh
  18614. for ( i = 0; i < this.segments; i++ ) {
  18615. for ( j = 0; j < this.radiusSegments; j++ ) {
  18616. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  18617. jp = (j + 1) % this.radiusSegments;
  18618. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  18619. b = this.grid[ ip ][ j ];
  18620. c = this.grid[ ip ][ jp ];
  18621. d = this.grid[ i ][ jp ];
  18622. uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
  18623. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
  18624. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  18625. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
  18626. this.faces.push( new THREE.Face4( a, b, c, d ) );
  18627. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  18628. }
  18629. }
  18630. this.computeCentroids();
  18631. this.computeFaceNormals();
  18632. this.computeVertexNormals();
  18633. };
  18634. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18635. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  18636. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  18637. var
  18638. tangent = new THREE.Vector3(),
  18639. normal = new THREE.Vector3(),
  18640. binormal = new THREE.Vector3(),
  18641. tangents = [],
  18642. normals = [],
  18643. binormals = [],
  18644. vec = new THREE.Vector3(),
  18645. mat = new THREE.Matrix4(),
  18646. numpoints = segments + 1,
  18647. theta,
  18648. epsilon = 0.0001,
  18649. smallest,
  18650. tx, ty, tz,
  18651. i, u, v;
  18652. // expose internals
  18653. this.tangents = tangents;
  18654. this.normals = normals;
  18655. this.binormals = binormals;
  18656. // compute the tangent vectors for each segment on the path
  18657. for ( i = 0; i < numpoints; i++ ) {
  18658. u = i / ( numpoints - 1 );
  18659. tangents[ i ] = path.getTangentAt( u );
  18660. tangents[ i ].normalize();
  18661. }
  18662. initialNormal3();
  18663. function initialNormal1(lastBinormal) {
  18664. // fixed start binormal. Has dangers of 0 vectors
  18665. normals[ 0 ] = new THREE.Vector3();
  18666. binormals[ 0 ] = new THREE.Vector3();
  18667. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  18668. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  18669. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18670. }
  18671. function initialNormal2() {
  18672. // This uses the Frenet-Serret formula for deriving binormal
  18673. var t2 = path.getTangentAt( epsilon );
  18674. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  18675. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  18676. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  18677. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  18678. }
  18679. function initialNormal3() {
  18680. // select an initial normal vector perpenicular to the first tangent vector,
  18681. // and in the direction of the smallest tangent xyz component
  18682. normals[ 0 ] = new THREE.Vector3();
  18683. binormals[ 0 ] = new THREE.Vector3();
  18684. smallest = Number.MAX_VALUE;
  18685. tx = Math.abs( tangents[ 0 ].x );
  18686. ty = Math.abs( tangents[ 0 ].y );
  18687. tz = Math.abs( tangents[ 0 ].z );
  18688. if ( tx <= smallest ) {
  18689. smallest = tx;
  18690. normal.set( 1, 0, 0 );
  18691. }
  18692. if ( ty <= smallest ) {
  18693. smallest = ty;
  18694. normal.set( 0, 1, 0 );
  18695. }
  18696. if ( tz <= smallest ) {
  18697. normal.set( 0, 0, 1 );
  18698. }
  18699. vec.cross( tangents[ 0 ], normal ).normalize();
  18700. normals[ 0 ].cross( tangents[ 0 ], vec );
  18701. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  18702. }
  18703. // compute the slowly-varying normal and binormal vectors for each segment on the path
  18704. for ( i = 1; i < numpoints; i++ ) {
  18705. normals[ i ] = normals[ i-1 ].clone();
  18706. binormals[ i ] = binormals[ i-1 ].clone();
  18707. vec.cross( tangents[ i-1 ], tangents[ i ] );
  18708. if ( vec.length() > epsilon ) {
  18709. vec.normalize();
  18710. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  18711. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  18712. }
  18713. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18714. }
  18715. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  18716. if ( closed ) {
  18717. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  18718. theta /= ( numpoints - 1 );
  18719. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  18720. theta = -theta;
  18721. }
  18722. for ( i = 1; i < numpoints; i++ ) {
  18723. // twist a little...
  18724. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  18725. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  18726. }
  18727. }
  18728. };
  18729. /**
  18730. * @author clockworkgeek / https://github.com/clockworkgeek
  18731. * @author timothypratley / https://github.com/timothypratley
  18732. */
  18733. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  18734. THREE.Geometry.call( this );
  18735. radius = radius || 1;
  18736. detail = detail || 0;
  18737. var that = this;
  18738. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  18739. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  18740. }
  18741. var midpoints = [], p = this.vertices;
  18742. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  18743. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  18744. }
  18745. this.mergeVertices();
  18746. // Apply radius
  18747. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  18748. this.vertices[ i ].multiplyScalar( radius );
  18749. }
  18750. // Project vector onto sphere's surface
  18751. function prepare( vector ) {
  18752. var vertex = vector.normalize().clone();
  18753. vertex.index = that.vertices.push( vertex ) - 1;
  18754. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  18755. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  18756. var v = inclination( vector ) / Math.PI + 0.5;
  18757. vertex.uv = new THREE.UV( u, 1 - v );
  18758. return vertex;
  18759. }
  18760. // Approximate a curved face with recursively sub-divided triangles.
  18761. function make( v1, v2, v3, detail ) {
  18762. if ( detail < 1 ) {
  18763. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  18764. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  18765. face.normal = face.centroid.clone().normalize();
  18766. that.faces.push( face );
  18767. var azi = azimuth( face.centroid );
  18768. that.faceVertexUvs[ 0 ].push( [
  18769. correctUV( v1.uv, v1, azi ),
  18770. correctUV( v2.uv, v2, azi ),
  18771. correctUV( v3.uv, v3, azi )
  18772. ] );
  18773. } else {
  18774. detail -= 1;
  18775. // split triangle into 4 smaller triangles
  18776. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  18777. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  18778. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  18779. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  18780. }
  18781. }
  18782. function midpoint( v1, v2 ) {
  18783. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  18784. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  18785. var mid = midpoints[ v1.index ][ v2.index ];
  18786. if ( mid === undefined ) {
  18787. // generate mean point and project to surface with prepare()
  18788. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  18789. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  18790. );
  18791. }
  18792. return mid;
  18793. }
  18794. // Angle around the Y axis, counter-clockwise when looking from above.
  18795. function azimuth( vector ) {
  18796. return Math.atan2( vector.z, -vector.x );
  18797. }
  18798. // Angle above the XZ plane.
  18799. function inclination( vector ) {
  18800. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  18801. }
  18802. // Texture fixing helper. Spheres have some odd behaviours.
  18803. function correctUV( uv, vector, azimuth ) {
  18804. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  18805. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  18806. return uv;
  18807. }
  18808. this.computeCentroids();
  18809. this.boundingSphere = { radius: radius };
  18810. };
  18811. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18812. /**
  18813. * @author timothypratley / https://github.com/timothypratley
  18814. */
  18815. THREE.IcosahedronGeometry = function ( radius, detail ) {
  18816. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  18817. var vertices = [
  18818. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  18819. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  18820. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  18821. ];
  18822. var faces = [
  18823. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  18824. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  18825. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  18826. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  18827. ];
  18828. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  18829. };
  18830. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18831. /**
  18832. * @author timothypratley / https://github.com/timothypratley
  18833. */
  18834. THREE.OctahedronGeometry = function ( radius, detail ) {
  18835. var vertices = [
  18836. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  18837. ];
  18838. var faces = [
  18839. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  18840. ];
  18841. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  18842. };
  18843. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18844. /**
  18845. * @author timothypratley / https://github.com/timothypratley
  18846. */
  18847. THREE.TetrahedronGeometry = function ( radius, detail ) {
  18848. var vertices = [
  18849. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  18850. ];
  18851. var faces = [
  18852. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  18853. ];
  18854. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  18855. };
  18856. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18857. /**
  18858. * @author zz85 / https://github.com/zz85
  18859. * Parametric Surfaces Geometry
  18860. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  18861. *
  18862. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  18863. *
  18864. */
  18865. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  18866. THREE.Geometry.call( this );
  18867. var verts = this.vertices;
  18868. var faces = this.faces;
  18869. var uvs = this.faceVertexUvs[ 0 ];
  18870. useTris = (useTris === undefined) ? false : useTris;
  18871. var i, il, j, p;
  18872. var u, v;
  18873. var stackCount = stacks + 1;
  18874. var sliceCount = slices + 1;
  18875. for ( i = 0; i <= stacks; i ++ ) {
  18876. v = i / stacks;
  18877. for ( j = 0; j <= slices; j ++ ) {
  18878. u = j / slices;
  18879. p = func( u, v );
  18880. verts.push( p );
  18881. }
  18882. }
  18883. var a, b, c, d;
  18884. var uva, uvb, uvc, uvd;
  18885. for ( i = 0; i < stacks; i ++ ) {
  18886. for ( j = 0; j < slices; j ++ ) {
  18887. a = i * sliceCount + j;
  18888. b = i * sliceCount + j + 1;
  18889. c = (i + 1) * sliceCount + j;
  18890. d = (i + 1) * sliceCount + j + 1;
  18891. uva = new THREE.UV( j / slices, i / stacks );
  18892. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  18893. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  18894. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  18895. if ( useTris ) {
  18896. faces.push( new THREE.Face3( a, b, c ) );
  18897. faces.push( new THREE.Face3( b, d, c ) );
  18898. uvs.push( [ uva, uvb, uvc ] );
  18899. uvs.push( [ uvb, uvd, uvc ] );
  18900. } else {
  18901. faces.push( new THREE.Face4( a, b, d, c ) );
  18902. uvs.push( [ uva, uvb, uvd, uvc ] );
  18903. }
  18904. }
  18905. }
  18906. // console.log(this);
  18907. // magic bullet
  18908. // var diff = this.mergeVertices();
  18909. // console.log('removed ', diff, ' vertices by merging');
  18910. this.computeCentroids();
  18911. this.computeFaceNormals();
  18912. this.computeVertexNormals();
  18913. };
  18914. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18915. /**
  18916. * @author qiao / https://github.com/qiao
  18917. * @fileoverview This is a convex hull generator using the incremental method.
  18918. * The complexity is O(n^2) where n is the number of vertices.
  18919. * O(nlogn) algorithms do exist, but they are much more complicated.
  18920. *
  18921. * Benchmark:
  18922. *
  18923. * Platform: CPU: P7350 @2.00GHz Engine: V8
  18924. *
  18925. * Num Vertices Time(ms)
  18926. *
  18927. * 10 1
  18928. * 20 3
  18929. * 30 19
  18930. * 40 48
  18931. * 50 107
  18932. */
  18933. THREE.ConvexGeometry = function( vertices ) {
  18934. THREE.Geometry.call( this );
  18935. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  18936. for ( var i = 3; i < vertices.length; i++ ) {
  18937. addPoint( i );
  18938. }
  18939. function addPoint( vertexId ) {
  18940. var vertex = vertices[ vertexId ].clone();
  18941. var mag = vertex.length();
  18942. vertex.x += mag * randomOffset();
  18943. vertex.y += mag * randomOffset();
  18944. vertex.z += mag * randomOffset();
  18945. var hole = [];
  18946. for ( var f = 0; f < faces.length; ) {
  18947. var face = faces[ f ];
  18948. // for each face, if the vertex can see it,
  18949. // then we try to add the face's edges into the hole.
  18950. if ( visible( face, vertex ) ) {
  18951. for ( var e = 0; e < 3; e++ ) {
  18952. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  18953. var boundary = true;
  18954. // remove duplicated edges.
  18955. for ( var h = 0; h < hole.length; h++ ) {
  18956. if ( equalEdge( hole[ h ], edge ) ) {
  18957. hole[ h ] = hole[ hole.length - 1 ];
  18958. hole.pop();
  18959. boundary = false;
  18960. break;
  18961. }
  18962. }
  18963. if ( boundary ) {
  18964. hole.push( edge );
  18965. }
  18966. }
  18967. // remove faces[ f ]
  18968. faces[ f ] = faces[ faces.length - 1 ];
  18969. faces.pop();
  18970. } else { // not visible
  18971. f++;
  18972. }
  18973. }
  18974. // construct the new faces formed by the edges of the hole and the vertex
  18975. for ( var h = 0; h < hole.length; h++ ) {
  18976. faces.push( [
  18977. hole[ h ][ 0 ],
  18978. hole[ h ][ 1 ],
  18979. vertexId
  18980. ] );
  18981. }
  18982. }
  18983. /**
  18984. * Whether the face is visible from the vertex
  18985. */
  18986. function visible( face, vertex ) {
  18987. var va = vertices[ face[ 0 ] ];
  18988. var vb = vertices[ face[ 1 ] ];
  18989. var vc = vertices[ face[ 2 ] ];
  18990. var n = normal( va, vb, vc );
  18991. // distance from face to origin
  18992. var dist = n.dot( va );
  18993. return n.dot( vertex ) >= dist;
  18994. }
  18995. /**
  18996. * Face normal
  18997. */
  18998. function normal( va, vb, vc ) {
  18999. var cb = new THREE.Vector3();
  19000. var ab = new THREE.Vector3();
  19001. cb.sub( vc, vb );
  19002. ab.sub( va, vb );
  19003. cb.crossSelf( ab );
  19004. if ( !cb.isZero() ) {
  19005. cb.normalize();
  19006. }
  19007. return cb;
  19008. }
  19009. /**
  19010. * Detect whether two edges are equal.
  19011. * Note that when constructing the convex hull, two same edges can only
  19012. * be of the negative direction.
  19013. */
  19014. function equalEdge( ea, eb ) {
  19015. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19016. }
  19017. /**
  19018. * Create a random offset between -1e-6 and 1e-6.
  19019. */
  19020. function randomOffset() {
  19021. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19022. }
  19023. /**
  19024. * XXX: Not sure if this is the correct approach. Need someone to review.
  19025. */
  19026. function vertexUv( vertex ) {
  19027. var mag = vertex.length();
  19028. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19029. }
  19030. // Push vertices into `this.vertices`, skipping those inside the hull
  19031. var id = 0;
  19032. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19033. for ( var i = 0; i < faces.length; i++ ) {
  19034. var face = faces[ i ];
  19035. for ( var j = 0; j < 3; j++ ) {
  19036. if ( newId[ face[ j ] ] === undefined ) {
  19037. newId[ face[ j ] ] = id++;
  19038. this.vertices.push( vertices[ face[ j ] ] );
  19039. }
  19040. face[ j ] = newId[ face[ j ] ];
  19041. }
  19042. }
  19043. // Convert faces into instances of THREE.Face3
  19044. for ( var i = 0; i < faces.length; i++ ) {
  19045. this.faces.push( new THREE.Face3(
  19046. faces[ i ][ 0 ],
  19047. faces[ i ][ 1 ],
  19048. faces[ i ][ 2 ]
  19049. ) );
  19050. }
  19051. // Compute UVs
  19052. for ( var i = 0; i < this.faces.length; i++ ) {
  19053. var face = this.faces[ i ];
  19054. this.faceVertexUvs[ 0 ].push( [
  19055. vertexUv( this.vertices[ face.a ] ),
  19056. vertexUv( this.vertices[ face.b ] ),
  19057. vertexUv( this.vertices[ face.c ])
  19058. ] );
  19059. }
  19060. this.computeCentroids();
  19061. this.computeFaceNormals();
  19062. this.computeVertexNormals();
  19063. };
  19064. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19065. /**
  19066. * @author sroucheray / http://sroucheray.org/
  19067. * @author mrdoob / http://mrdoob.com/
  19068. */
  19069. THREE.AxisHelper = function ( size ) {
  19070. var geometry = new THREE.Geometry();
  19071. geometry.vertices.push(
  19072. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19073. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19074. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19075. );
  19076. geometry.colors.push(
  19077. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19078. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19079. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19080. );
  19081. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19082. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19083. };
  19084. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19085. /**
  19086. * @author WestLangley / http://github.com/WestLangley
  19087. * @author zz85 / https://github.com/zz85
  19088. *
  19089. * Creates an arrow for visualizing directions
  19090. *
  19091. * Parameters:
  19092. * dir - Vector3
  19093. * origin - Vector3
  19094. * length - Number
  19095. * hex - color in hex value
  19096. */
  19097. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  19098. THREE.Object3D.call( this );
  19099. if ( hex === undefined ) hex = 0xffff00;
  19100. if ( length === undefined ) length = 20;
  19101. var lineGeometry = new THREE.Geometry();
  19102. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  19103. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  19104. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  19105. this.add( this.line );
  19106. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  19107. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  19108. this.cone.position.set( 0, 1, 0 );
  19109. this.add( this.cone );
  19110. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  19111. this.setDirection( dir );
  19112. this.setLength( length );
  19113. };
  19114. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  19115. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  19116. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  19117. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  19118. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  19119. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  19120. };
  19121. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  19122. this.scale.set( length, length, length );
  19123. };
  19124. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  19125. this.line.material.color.setHex( hex );
  19126. this.cone.material.color.setHex( hex );
  19127. };
  19128. /**
  19129. * @author alteredq / http://alteredqualia.com/
  19130. *
  19131. * - shows frustum, line of sight and up of the camera
  19132. * - suitable for fast updates
  19133. * - based on frustum visualization in lightgl.js shadowmap example
  19134. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  19135. */
  19136. THREE.CameraHelper = function ( camera ) {
  19137. THREE.Line.call( this );
  19138. var scope = this;
  19139. this.geometry = new THREE.Geometry();
  19140. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  19141. this.type = THREE.LinePieces;
  19142. this.matrixWorld = camera.matrixWorld;
  19143. this.matrixAutoUpdate = false;
  19144. this.pointMap = {};
  19145. // colors
  19146. var hexFrustum = 0xffaa00;
  19147. var hexCone = 0xff0000;
  19148. var hexUp = 0x00aaff;
  19149. var hexTarget = 0xffffff;
  19150. var hexCross = 0x333333;
  19151. // near
  19152. addLine( "n1", "n2", hexFrustum );
  19153. addLine( "n2", "n4", hexFrustum );
  19154. addLine( "n4", "n3", hexFrustum );
  19155. addLine( "n3", "n1", hexFrustum );
  19156. // far
  19157. addLine( "f1", "f2", hexFrustum );
  19158. addLine( "f2", "f4", hexFrustum );
  19159. addLine( "f4", "f3", hexFrustum );
  19160. addLine( "f3", "f1", hexFrustum );
  19161. // sides
  19162. addLine( "n1", "f1", hexFrustum );
  19163. addLine( "n2", "f2", hexFrustum );
  19164. addLine( "n3", "f3", hexFrustum );
  19165. addLine( "n4", "f4", hexFrustum );
  19166. // cone
  19167. addLine( "p", "n1", hexCone );
  19168. addLine( "p", "n2", hexCone );
  19169. addLine( "p", "n3", hexCone );
  19170. addLine( "p", "n4", hexCone );
  19171. // up
  19172. addLine( "u1", "u2", hexUp );
  19173. addLine( "u2", "u3", hexUp );
  19174. addLine( "u3", "u1", hexUp );
  19175. // target
  19176. addLine( "c", "t", hexTarget );
  19177. addLine( "p", "c", hexCross );
  19178. // cross
  19179. addLine( "cn1", "cn2", hexCross );
  19180. addLine( "cn3", "cn4", hexCross );
  19181. addLine( "cf1", "cf2", hexCross );
  19182. addLine( "cf3", "cf4", hexCross );
  19183. this.camera = camera;
  19184. function addLine( a, b, hex ) {
  19185. addPoint( a, hex );
  19186. addPoint( b, hex );
  19187. }
  19188. function addPoint( id, hex ) {
  19189. scope.geometry.vertices.push( new THREE.Vector3() );
  19190. scope.geometry.colors.push( new THREE.Color( hex ) );
  19191. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  19192. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  19193. }
  19194. this.update( camera );
  19195. };
  19196. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  19197. THREE.CameraHelper.prototype.update = function () {
  19198. var scope = this;
  19199. var w = 1, h = 1;
  19200. // we need just camera projection matrix
  19201. // world matrix must be identity
  19202. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  19203. // center / target
  19204. setPoint( "c", 0, 0, -1 );
  19205. setPoint( "t", 0, 0, 1 );
  19206. // near
  19207. setPoint( "n1", -w, -h, -1 );
  19208. setPoint( "n2", w, -h, -1 );
  19209. setPoint( "n3", -w, h, -1 );
  19210. setPoint( "n4", w, h, -1 );
  19211. // far
  19212. setPoint( "f1", -w, -h, 1 );
  19213. setPoint( "f2", w, -h, 1 );
  19214. setPoint( "f3", -w, h, 1 );
  19215. setPoint( "f4", w, h, 1 );
  19216. // up
  19217. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  19218. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  19219. setPoint( "u3", 0, h * 2, -1 );
  19220. // cross
  19221. setPoint( "cf1", -w, 0, 1 );
  19222. setPoint( "cf2", w, 0, 1 );
  19223. setPoint( "cf3", 0, -h, 1 );
  19224. setPoint( "cf4", 0, h, 1 );
  19225. setPoint( "cn1", -w, 0, -1 );
  19226. setPoint( "cn2", w, 0, -1 );
  19227. setPoint( "cn3", 0, -h, -1 );
  19228. setPoint( "cn4", 0, h, -1 );
  19229. function setPoint( point, x, y, z ) {
  19230. THREE.CameraHelper.__v.set( x, y, z );
  19231. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  19232. var points = scope.pointMap[ point ];
  19233. if ( points !== undefined ) {
  19234. for ( var i = 0, il = points.length; i < il; i ++ ) {
  19235. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  19236. }
  19237. }
  19238. }
  19239. this.geometry.verticesNeedUpdate = true;
  19240. };
  19241. THREE.CameraHelper.__projector = new THREE.Projector();
  19242. THREE.CameraHelper.__v = new THREE.Vector3();
  19243. THREE.CameraHelper.__c = new THREE.Camera();
  19244. /*
  19245. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  19246. *
  19247. * Subdivision Geometry Modifier
  19248. * using Catmull-Clark Subdivision Surfaces
  19249. * for creating smooth geometry meshes
  19250. *
  19251. * Note: a modifier modifies vertices and faces of geometry,
  19252. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  19253. *
  19254. * Readings:
  19255. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19256. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  19257. * http://xrt.wikidot.com/blog:31
  19258. * "Subdivision Surfaces in Character Animation"
  19259. *
  19260. * (on boundary edges)
  19261. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  19262. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  19263. *
  19264. * Supports:
  19265. * Closed and Open geometries.
  19266. *
  19267. * TODO:
  19268. * crease vertex and "semi-sharp" features
  19269. * selective subdivision
  19270. */
  19271. THREE.SubdivisionModifier = function( subdivisions ) {
  19272. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  19273. // Settings
  19274. this.useOldVertexColors = false;
  19275. this.supportUVs = true;
  19276. this.debug = false;
  19277. };
  19278. // Applies the "modify" pattern
  19279. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  19280. var repeats = this.subdivisions;
  19281. while ( repeats-- > 0 ) {
  19282. this.smooth( geometry );
  19283. }
  19284. };
  19285. /// REFACTORING THIS OUT
  19286. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  19287. return Math.min( a, b ) + "_" + Math.max( a, b );
  19288. };
  19289. // Returns a hashmap - of { edge_key: face_index }
  19290. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  19291. var i, il, v1, v2, j, k,
  19292. face, faceIndices, faceIndex,
  19293. edge,
  19294. hash,
  19295. edgeFaceMap = {};
  19296. var orderedKey = THREE.GeometryUtils.orderedKey;
  19297. function mapEdgeHash( hash, i ) {
  19298. if ( edgeFaceMap[ hash ] === undefined ) {
  19299. edgeFaceMap[ hash ] = [];
  19300. }
  19301. edgeFaceMap[ hash ].push( i );
  19302. }
  19303. // construct vertex -> face map
  19304. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  19305. face = geometry.faces[ i ];
  19306. if ( face instanceof THREE.Face3 ) {
  19307. hash = orderedKey( face.a, face.b );
  19308. mapEdgeHash( hash, i );
  19309. hash = orderedKey( face.b, face.c );
  19310. mapEdgeHash( hash, i );
  19311. hash = orderedKey( face.c, face.a );
  19312. mapEdgeHash( hash, i );
  19313. } else if ( face instanceof THREE.Face4 ) {
  19314. hash = orderedKey( face.a, face.b );
  19315. mapEdgeHash( hash, i );
  19316. hash = orderedKey( face.b, face.c );
  19317. mapEdgeHash( hash, i );
  19318. hash = orderedKey( face.c, face.d );
  19319. mapEdgeHash( hash, i );
  19320. hash = orderedKey( face.d, face.a );
  19321. mapEdgeHash( hash, i );
  19322. }
  19323. }
  19324. // extract faces
  19325. // var edges = [];
  19326. //
  19327. // var numOfEdges = 0;
  19328. // for (i in edgeFaceMap) {
  19329. // numOfEdges++;
  19330. //
  19331. // edge = edgeFaceMap[i];
  19332. // edges.push(edge);
  19333. //
  19334. // }
  19335. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  19336. return edgeFaceMap;
  19337. }
  19338. /////////////////////////////
  19339. // Performs an iteration of Catmull-Clark Subdivision
  19340. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  19341. //debug( 'running smooth' );
  19342. // New set of vertices, faces and uvs
  19343. var newVertices = [], newFaces = [], newUVs = [];
  19344. function v( x, y, z ) {
  19345. newVertices.push( new THREE.Vector3( x, y, z ) );
  19346. }
  19347. var scope = this;
  19348. var orderedKey = THREE.GeometryUtils.orderedKey;
  19349. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  19350. function assert() {
  19351. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  19352. }
  19353. function debug() {
  19354. if (scope.debug) console.log.apply(console, arguments);
  19355. }
  19356. function warn() {
  19357. if (console)
  19358. console.log.apply(console, arguments);
  19359. }
  19360. function f4( a, b, c, d, oldFace, orders, facei ) {
  19361. // TODO move vertex selection over here!
  19362. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  19363. if (scope.useOldVertexColors) {
  19364. newFace.vertexColors = [];
  19365. var color, tmpColor, order;
  19366. for (var i=0;i<4;i++) {
  19367. order = orders[i];
  19368. color = new THREE.Color(),
  19369. color.setRGB(0,0,0);
  19370. for (var j=0, jl=0; j<order.length;j++) {
  19371. tmpColor = oldFace.vertexColors[order[j]-1];
  19372. color.r += tmpColor.r;
  19373. color.g += tmpColor.g;
  19374. color.b += tmpColor.b;
  19375. }
  19376. color.r /= order.length;
  19377. color.g /= order.length;
  19378. color.b /= order.length;
  19379. newFace.vertexColors[i] = color;
  19380. }
  19381. }
  19382. newFaces.push( newFace );
  19383. if (scope.supportUVs) {
  19384. var aUv = [
  19385. getUV(a, ''),
  19386. getUV(b, facei),
  19387. getUV(c, facei),
  19388. getUV(d, facei)
  19389. ];
  19390. if (!aUv[0]) debug('a :( ', a+':'+facei);
  19391. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  19392. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  19393. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  19394. else
  19395. newUVs.push( aUv );
  19396. }
  19397. }
  19398. var originalPoints = oldGeometry.vertices;
  19399. var originalFaces = oldGeometry.faces;
  19400. var originalVerticesLength = originalPoints.length;
  19401. var newPoints = originalPoints.concat(); // New set of vertices to work on
  19402. var facePoints = [], // these are new points on exisiting faces
  19403. edgePoints = {}; // these are new points on exisiting edges
  19404. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  19405. // TODO: handle this correctly.
  19406. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  19407. function debugCoreStuff() {
  19408. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  19409. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  19410. }
  19411. function getUV(vertexNo, oldFaceNo) {
  19412. var j,jl;
  19413. var key = vertexNo+':'+oldFaceNo;
  19414. var theUV = uvForVertices[key];
  19415. if (!theUV) {
  19416. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  19417. debug('face pt');
  19418. } else {
  19419. debug('edge pt');
  19420. }
  19421. warn('warning, UV not found for', key);
  19422. return null;
  19423. }
  19424. return theUV;
  19425. // Original faces -> Vertex Nos.
  19426. // new Facepoint -> Vertex Nos.
  19427. // edge Points
  19428. }
  19429. function addUV(vertexNo, oldFaceNo, value) {
  19430. var key = vertexNo+':'+oldFaceNo;
  19431. if (!(key in uvForVertices)) {
  19432. uvForVertices[key] = value;
  19433. } else {
  19434. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  19435. }
  19436. }
  19437. // Step 1
  19438. // For each face, add a face point
  19439. // Set each face point to be the centroid of all original points for the respective face.
  19440. // debug(oldGeometry);
  19441. var i, il, j, jl, face;
  19442. // For Uvs
  19443. var uvs = oldGeometry.faceVertexUvs[0];
  19444. var abcd = 'abcd', vertice;
  19445. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  19446. if (scope.supportUVs)
  19447. for (i=0, il = uvs.length; i<il; i++ ) {
  19448. for (j=0,jl=uvs[i].length;j<jl;j++) {
  19449. vertice = originalFaces[i][abcd.charAt(j)];
  19450. addUV(vertice, i, uvs[i][j]);
  19451. }
  19452. }
  19453. if (uvs.length == 0) scope.supportUVs = false;
  19454. // Additional UVs check, if we index original
  19455. var uvCount = 0;
  19456. for (var u in uvForVertices) {
  19457. uvCount++;
  19458. }
  19459. if (!uvCount) {
  19460. scope.supportUVs = false;
  19461. debug('no uvs');
  19462. }
  19463. var avgUv ;
  19464. for (i=0, il = originalFaces.length; i<il ;i++) {
  19465. face = originalFaces[ i ];
  19466. facePoints.push( face.centroid );
  19467. newPoints.push( face.centroid );
  19468. if (!scope.supportUVs) continue;
  19469. // Prepare subdivided uv
  19470. avgUv = new THREE.UV();
  19471. if ( face instanceof THREE.Face3 ) {
  19472. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  19473. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  19474. avgUv.u /= 3;
  19475. avgUv.v /= 3;
  19476. } else if ( face instanceof THREE.Face4 ) {
  19477. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  19478. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  19479. avgUv.u /= 4;
  19480. avgUv.v /= 4;
  19481. }
  19482. addUV(originalVerticesLength + i, '', avgUv);
  19483. }
  19484. // Step 2
  19485. // For each edge, add an edge point.
  19486. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  19487. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  19488. var edge, faceIndexA, faceIndexB, avg;
  19489. // debug('edgeFaceMap', edgeFaceMap);
  19490. var edgeCount = 0;
  19491. var edgeVertex, edgeVertexA, edgeVertexB;
  19492. ////
  19493. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  19494. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  19495. function addVertexEdgeMap(vertex, edge) {
  19496. if (vertexEdgeMap[vertex]===undefined) {
  19497. vertexEdgeMap[vertex] = [];
  19498. }
  19499. vertexEdgeMap[vertex].push(edge);
  19500. }
  19501. function addVertexFaceMap(vertex, face, edge) {
  19502. if (vertexFaceMap[vertex]===undefined) {
  19503. vertexFaceMap[vertex] = {};
  19504. }
  19505. vertexFaceMap[vertex][face] = edge;
  19506. // vertexFaceMap[vertex][face] = null;
  19507. }
  19508. // Prepares vertexEdgeMap and vertexFaceMap
  19509. for (i in edgeFaceMap) { // This is for every edge
  19510. edge = edgeFaceMap[i];
  19511. edgeVertex = i.split('_');
  19512. edgeVertexA = edgeVertex[0];
  19513. edgeVertexB = edgeVertex[1];
  19514. // Maps an edgeVertex to connecting edges
  19515. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  19516. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  19517. for (j=0,jl=edge.length;j<jl;j++) {
  19518. face = edge[j];
  19519. addVertexFaceMap(edgeVertexA, face, i);
  19520. addVertexFaceMap(edgeVertexB, face, i);
  19521. }
  19522. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  19523. // this thing is fishy right now.
  19524. if (edge.length < 2) {
  19525. // edge is "sharp";
  19526. sharpEdges[i] = true;
  19527. sharpVertices[edgeVertexA] = true;
  19528. sharpVertices[edgeVertexB] = true;
  19529. }
  19530. }
  19531. for (i in edgeFaceMap) {
  19532. edge = edgeFaceMap[i];
  19533. faceIndexA = edge[0]; // face index a
  19534. faceIndexB = edge[1]; // face index b
  19535. edgeVertex = i.split('_');
  19536. edgeVertexA = edgeVertex[0];
  19537. edgeVertexB = edgeVertex[1];
  19538. avg = new THREE.Vector3();
  19539. //debug(i, faceIndexB,facePoints[faceIndexB]);
  19540. assert(edge.length > 0, 'an edge without faces?!');
  19541. if (edge.length==1) {
  19542. avg.addSelf(originalPoints[edgeVertexA]);
  19543. avg.addSelf(originalPoints[edgeVertexB]);
  19544. avg.multiplyScalar(0.5);
  19545. sharpVertices[newPoints.length] = true;
  19546. } else {
  19547. avg.addSelf(facePoints[faceIndexA]);
  19548. avg.addSelf(facePoints[faceIndexB]);
  19549. avg.addSelf(originalPoints[edgeVertexA]);
  19550. avg.addSelf(originalPoints[edgeVertexB]);
  19551. avg.multiplyScalar(0.25);
  19552. }
  19553. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  19554. newPoints.push( avg );
  19555. edgeCount ++;
  19556. if (!scope.supportUVs) {
  19557. continue;
  19558. }
  19559. // Prepare subdivided uv
  19560. avgUv = new THREE.UV();
  19561. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  19562. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  19563. avgUv.u /= 2;
  19564. avgUv.v /= 2;
  19565. addUV(edgePoints[i], faceIndexA, avgUv);
  19566. if (edge.length>=2) {
  19567. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  19568. avgUv = new THREE.UV();
  19569. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  19570. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  19571. avgUv.u /= 2;
  19572. avgUv.v /= 2;
  19573. addUV(edgePoints[i], faceIndexB, avgUv);
  19574. }
  19575. }
  19576. debug('-- Step 2 done');
  19577. // Step 3
  19578. // For each face point, add an edge for every edge of the face,
  19579. // connecting the face point to each edge point for the face.
  19580. var facePt, currentVerticeIndex;
  19581. var hashAB, hashBC, hashCD, hashDA, hashCA;
  19582. var abc123 = ['123', '12', '2', '23'];
  19583. var bca123 = ['123', '23', '3', '31'];
  19584. var cab123 = ['123', '31', '1', '12'];
  19585. var abc1234 = ['1234', '12', '2', '23'];
  19586. var bcd1234 = ['1234', '23', '3', '34'];
  19587. var cda1234 = ['1234', '34', '4', '41'];
  19588. var dab1234 = ['1234', '41', '1', '12'];
  19589. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  19590. facePt = facePoints[i];
  19591. face = originalFaces[i];
  19592. currentVerticeIndex = originalVerticesLength+ i;
  19593. if ( face instanceof THREE.Face3 ) {
  19594. // create 3 face4s
  19595. hashAB = orderedKey( face.a, face.b );
  19596. hashBC = orderedKey( face.b, face.c );
  19597. hashCA = orderedKey( face.c, face.a );
  19598. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  19599. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  19600. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  19601. } else if ( face instanceof THREE.Face4 ) {
  19602. // create 4 face4s
  19603. hashAB = orderedKey( face.a, face.b );
  19604. hashBC = orderedKey( face.b, face.c );
  19605. hashCD = orderedKey( face.c, face.d );
  19606. hashDA = orderedKey( face.d, face.a );
  19607. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  19608. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  19609. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  19610. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  19611. } else {
  19612. debug('face should be a face!', face);
  19613. }
  19614. }
  19615. newVertices = newPoints;
  19616. // Step 4
  19617. // For each original point P,
  19618. // take the average F of all n face points for faces touching P,
  19619. // and take the average R of all n edge midpoints for edges touching P,
  19620. // where each edge midpoint is the average of its two endpoint vertices.
  19621. // Move each original point to the point
  19622. var F = new THREE.Vector3();
  19623. var R = new THREE.Vector3();
  19624. var n;
  19625. for (i=0, il = originalPoints.length; i<il; i++) {
  19626. // (F + 2R + (n-3)P) / n
  19627. if (vertexEdgeMap[i]===undefined) continue;
  19628. F.set(0,0,0);
  19629. R.set(0,0,0);
  19630. var newPos = new THREE.Vector3(0,0,0);
  19631. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  19632. for (j in vertexFaceMap[i]) {
  19633. F.addSelf(facePoints[j]);
  19634. f++;
  19635. }
  19636. var sharpEdgeCount = 0;
  19637. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  19638. // Are we on the border?
  19639. var boundary_case = f != n;
  19640. // if (boundary_case) {
  19641. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  19642. // }
  19643. for (j=0;j<n;j++) {
  19644. if (
  19645. sharpEdges[
  19646. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  19647. ]) {
  19648. sharpEdgeCount++;
  19649. }
  19650. }
  19651. // if ( sharpEdgeCount==2 ) {
  19652. // continue;
  19653. // // Do not move vertex if there's 2 connecting sharp edges.
  19654. // }
  19655. /*
  19656. if (sharpEdgeCount>2) {
  19657. // TODO
  19658. }
  19659. */
  19660. F.divideScalar(f);
  19661. var boundary_edges = 0;
  19662. if (boundary_case) {
  19663. var bb_edge;
  19664. for (j=0; j<n;j++) {
  19665. edge = vertexEdgeMap[i][j];
  19666. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  19667. if (bb_edge) {
  19668. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  19669. R.addSelf(midPt);
  19670. boundary_edges++;
  19671. }
  19672. }
  19673. R.divideScalar(4);
  19674. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  19675. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  19676. } else {
  19677. for (j=0; j<n;j++) {
  19678. edge = vertexEdgeMap[i][j];
  19679. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  19680. R.addSelf(midPt);
  19681. }
  19682. R.divideScalar(n);
  19683. }
  19684. // Sum the formula
  19685. newPos.addSelf(originalPoints[i]);
  19686. if (boundary_case) {
  19687. newPos.divideScalar(2);
  19688. newPos.addSelf(R);
  19689. } else {
  19690. newPos.multiplyScalar(n - 3);
  19691. newPos.addSelf(F);
  19692. newPos.addSelf(R.multiplyScalar(2));
  19693. newPos.divideScalar(n);
  19694. }
  19695. newVertices[i] = newPos;
  19696. }
  19697. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  19698. newGeometry.vertices = newVertices;
  19699. newGeometry.faces = newFaces;
  19700. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  19701. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  19702. newGeometry.computeCentroids();
  19703. newGeometry.computeFaceNormals();
  19704. newGeometry.computeVertexNormals();
  19705. };/**
  19706. * @author alteredq / http://alteredqualia.com/
  19707. */
  19708. THREE.ImmediateRenderObject = function ( ) {
  19709. THREE.Object3D.call( this );
  19710. this.render = function ( renderCallback ) { };
  19711. };
  19712. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  19713. /**
  19714. * @author mikael emtinger / http://gomo.se/
  19715. * @author alteredq / http://alteredqualia.com/
  19716. */
  19717. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  19718. THREE.Object3D.call( this );
  19719. this.lensFlares = [];
  19720. this.positionScreen = new THREE.Vector3();
  19721. this.customUpdateCallback = undefined;
  19722. if( texture !== undefined ) {
  19723. this.add( texture, size, distance, blending, color );
  19724. }
  19725. };
  19726. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  19727. /*
  19728. * Add: adds another flare
  19729. */
  19730. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  19731. if( size === undefined ) size = -1;
  19732. if( distance === undefined ) distance = 0;
  19733. if( opacity === undefined ) opacity = 1;
  19734. if( color === undefined ) color = new THREE.Color( 0xffffff );
  19735. if( blending === undefined ) blending = THREE.NormalBlending;
  19736. distance = Math.min( distance, Math.max( 0, distance ) );
  19737. this.lensFlares.push( { texture: texture, // THREE.Texture
  19738. size: size, // size in pixels (-1 = use texture.width)
  19739. distance: distance, // distance (0-1) from light source (0=at light source)
  19740. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  19741. scale: 1, // scale
  19742. rotation: 1, // rotation
  19743. opacity: opacity, // opacity
  19744. color: color, // color
  19745. blending: blending } ); // blending
  19746. };
  19747. /*
  19748. * Update lens flares update positions on all flares based on the screen position
  19749. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  19750. */
  19751. THREE.LensFlare.prototype.updateLensFlares = function () {
  19752. var f, fl = this.lensFlares.length;
  19753. var flare;
  19754. var vecX = -this.positionScreen.x * 2;
  19755. var vecY = -this.positionScreen.y * 2;
  19756. for( f = 0; f < fl; f ++ ) {
  19757. flare = this.lensFlares[ f ];
  19758. flare.x = this.positionScreen.x + vecX * flare.distance;
  19759. flare.y = this.positionScreen.y + vecY * flare.distance;
  19760. flare.wantedRotation = flare.x * Math.PI * 0.25;
  19761. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  19762. }
  19763. };
  19764. /**
  19765. * @author alteredq / http://alteredqualia.com/
  19766. */
  19767. THREE.MorphBlendMesh = function( geometry, material ) {
  19768. THREE.Mesh.call( this, geometry, material );
  19769. this.animationsMap = {};
  19770. this.animationsList = [];
  19771. // prepare default animation
  19772. // (all frames played together in 1 second)
  19773. var numFrames = this.geometry.morphTargets.length;
  19774. var name = "__default";
  19775. var startFrame = 0;
  19776. var endFrame = numFrames - 1;
  19777. var fps = numFrames / 1;
  19778. this.createAnimation( name, startFrame, endFrame, fps );
  19779. this.setAnimationWeight( name, 1 );
  19780. };
  19781. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  19782. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  19783. var animation = {
  19784. startFrame: start,
  19785. endFrame: end,
  19786. length: end - start + 1,
  19787. fps: fps,
  19788. duration: ( end - start ) / fps,
  19789. lastFrame: 0,
  19790. currentFrame: 0,
  19791. active: false,
  19792. time: 0,
  19793. direction: 1,
  19794. weight: 1,
  19795. directionBackwards: false,
  19796. mirroredLoop: false
  19797. };
  19798. this.animationsMap[ name ] = animation;
  19799. this.animationsList.push( animation );
  19800. };
  19801. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  19802. var pattern = /([a-z]+)(\d+)/;
  19803. var firstAnimation, frameRanges = {};
  19804. var geometry = this.geometry;
  19805. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  19806. var morph = geometry.morphTargets[ i ];
  19807. var chunks = morph.name.match( pattern );
  19808. if ( chunks && chunks.length > 1 ) {
  19809. var name = chunks[ 1 ];
  19810. var num = chunks[ 2 ];
  19811. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  19812. var range = frameRanges[ name ];
  19813. if ( i < range.start ) range.start = i;
  19814. if ( i > range.end ) range.end = i;
  19815. if ( ! firstAnimation ) firstAnimation = name;
  19816. }
  19817. }
  19818. for ( var name in frameRanges ) {
  19819. var range = frameRanges[ name ];
  19820. this.createAnimation( name, range.start, range.end, fps );
  19821. }
  19822. this.firstAnimation = firstAnimation;
  19823. };
  19824. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  19825. var animation = this.animationsMap[ name ];
  19826. if ( animation ) {
  19827. animation.direction = 1;
  19828. animation.directionBackwards = false;
  19829. }
  19830. };
  19831. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  19832. var animation = this.animationsMap[ name ];
  19833. if ( animation ) {
  19834. animation.direction = -1;
  19835. animation.directionBackwards = true;
  19836. }
  19837. };
  19838. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  19839. var animation = this.animationsMap[ name ];
  19840. if ( animation ) {
  19841. animation.fps = fps;
  19842. animation.duration = ( animation.end - animation.start ) / animation.fps;
  19843. }
  19844. };
  19845. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  19846. var animation = this.animationsMap[ name ];
  19847. if ( animation ) {
  19848. animation.duration = duration;
  19849. animation.fps = ( animation.end - animation.start ) / animation.duration;
  19850. }
  19851. };
  19852. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  19853. var animation = this.animationsMap[ name ];
  19854. if ( animation ) {
  19855. animation.weight = weight;
  19856. }
  19857. };
  19858. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  19859. var animation = this.animationsMap[ name ];
  19860. if ( animation ) {
  19861. animation.time = time;
  19862. }
  19863. };
  19864. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  19865. var time = 0;
  19866. var animation = this.animationsMap[ name ];
  19867. if ( animation ) {
  19868. time = animation.time;
  19869. }
  19870. return time;
  19871. };
  19872. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  19873. var duration = -1;
  19874. var animation = this.animationsMap[ name ];
  19875. if ( animation ) {
  19876. duration = animation.duration;
  19877. }
  19878. return duration;
  19879. };
  19880. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  19881. var animation = this.animationsMap[ name ];
  19882. if ( animation ) {
  19883. animation.time = 0;
  19884. animation.active = true;
  19885. } else {
  19886. console.warn( "animation[" + name + "] undefined" );
  19887. }
  19888. };
  19889. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  19890. var animation = this.animationsMap[ name ];
  19891. if ( animation ) {
  19892. animation.active = false;
  19893. }
  19894. };
  19895. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  19896. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  19897. var animation = this.animationsList[ i ];
  19898. if ( ! animation.active ) continue;
  19899. var frameTime = animation.duration / animation.length;
  19900. animation.time += animation.direction * delta;
  19901. if ( animation.mirroredLoop ) {
  19902. if ( animation.time > animation.duration || animation.time < 0 ) {
  19903. animation.direction *= -1;
  19904. if ( animation.time > animation.duration ) {
  19905. animation.time = animation.duration;
  19906. animation.directionBackwards = true;
  19907. }
  19908. if ( animation.time < 0 ) {
  19909. animation.time = 0;
  19910. animation.directionBackwards = false;
  19911. }
  19912. }
  19913. } else {
  19914. animation.time = animation.time % animation.duration;
  19915. if ( animation.time < 0 ) animation.time += animation.duration;
  19916. }
  19917. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  19918. var weight = animation.weight;
  19919. if ( keyframe !== animation.currentFrame ) {
  19920. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  19921. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  19922. this.morphTargetInfluences[ keyframe ] = 0;
  19923. animation.lastFrame = animation.currentFrame;
  19924. animation.currentFrame = keyframe;
  19925. }
  19926. var mix = ( animation.time % frameTime ) / frameTime;
  19927. if ( animation.directionBackwards ) mix = 1 - mix;
  19928. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  19929. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  19930. }
  19931. };
  19932. /**
  19933. * @author mikael emtinger / http://gomo.se/
  19934. * @author alteredq / http://alteredqualia.com/
  19935. */
  19936. THREE.LensFlarePlugin = function ( ) {
  19937. var _gl, _renderer, _lensFlare = {};
  19938. this.init = function ( renderer ) {
  19939. _gl = renderer.context;
  19940. _renderer = renderer;
  19941. _lensFlare.vertices = new Float32Array( 8 + 8 );
  19942. _lensFlare.faces = new Uint16Array( 6 );
  19943. var i = 0;
  19944. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  19945. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  19946. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  19947. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  19948. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  19949. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  19950. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  19951. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  19952. i = 0;
  19953. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  19954. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  19955. // buffers
  19956. _lensFlare.vertexBuffer = _gl.createBuffer();
  19957. _lensFlare.elementBuffer = _gl.createBuffer();
  19958. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  19959. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  19960. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  19961. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  19962. // textures
  19963. _lensFlare.tempTexture = _gl.createTexture();
  19964. _lensFlare.occlusionTexture = _gl.createTexture();
  19965. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  19966. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  19967. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  19968. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  19969. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  19970. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  19971. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  19972. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  19973. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  19974. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  19975. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  19976. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  19977. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  19978. _lensFlare.hasVertexTexture = false;
  19979. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  19980. } else {
  19981. _lensFlare.hasVertexTexture = true;
  19982. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  19983. }
  19984. _lensFlare.attributes = {};
  19985. _lensFlare.uniforms = {};
  19986. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  19987. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  19988. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  19989. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  19990. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  19991. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  19992. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  19993. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  19994. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  19995. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  19996. _lensFlare.attributesEnabled = false;
  19997. };
  19998. /*
  19999. * Render lens flares
  20000. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20001. * reads these back and calculates occlusion.
  20002. * Then _lensFlare.update_lensFlares() is called to re-position and
  20003. * update transparency of flares. Then they are rendered.
  20004. *
  20005. */
  20006. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20007. var flares = scene.__webglFlares,
  20008. nFlares = flares.length;
  20009. if ( ! nFlares ) return;
  20010. var tempPosition = new THREE.Vector3();
  20011. var invAspect = viewportHeight / viewportWidth,
  20012. halfViewportWidth = viewportWidth * 0.5,
  20013. halfViewportHeight = viewportHeight * 0.5;
  20014. var size = 16 / viewportHeight,
  20015. scale = new THREE.Vector2( size * invAspect, size );
  20016. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20017. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20018. var uniforms = _lensFlare.uniforms,
  20019. attributes = _lensFlare.attributes;
  20020. // set _lensFlare program and reset blending
  20021. _gl.useProgram( _lensFlare.program );
  20022. if ( ! _lensFlare.attributesEnabled ) {
  20023. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20024. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20025. _lensFlare.attributesEnabled = true;
  20026. }
  20027. // loop through all lens flares to update their occlusion and positions
  20028. // setup gl and common used attribs/unforms
  20029. _gl.uniform1i( uniforms.occlusionMap, 0 );
  20030. _gl.uniform1i( uniforms.map, 1 );
  20031. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20032. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20033. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20034. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20035. _gl.disable( _gl.CULL_FACE );
  20036. _gl.depthMask( false );
  20037. var i, j, jl, flare, sprite;
  20038. for ( i = 0; i < nFlares; i ++ ) {
  20039. size = 16 / viewportHeight;
  20040. scale.set( size * invAspect, size );
  20041. // calc object screen position
  20042. flare = flares[ i ];
  20043. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  20044. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  20045. camera.projectionMatrix.multiplyVector3( tempPosition );
  20046. // setup arrays for gl programs
  20047. screenPosition.copy( tempPosition )
  20048. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  20049. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  20050. // screen cull
  20051. if ( _lensFlare.hasVertexTexture || (
  20052. screenPositionPixels.x > 0 &&
  20053. screenPositionPixels.x < viewportWidth &&
  20054. screenPositionPixels.y > 0 &&
  20055. screenPositionPixels.y < viewportHeight ) ) {
  20056. // save current RGB to temp texture
  20057. _gl.activeTexture( _gl.TEXTURE1 );
  20058. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20059. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20060. // render pink quad
  20061. _gl.uniform1i( uniforms.renderType, 0 );
  20062. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20063. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20064. _gl.disable( _gl.BLEND );
  20065. _gl.enable( _gl.DEPTH_TEST );
  20066. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20067. // copy result to occlusionMap
  20068. _gl.activeTexture( _gl.TEXTURE0 );
  20069. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20070. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  20071. // restore graphics
  20072. _gl.uniform1i( uniforms.renderType, 1 );
  20073. _gl.disable( _gl.DEPTH_TEST );
  20074. _gl.activeTexture( _gl.TEXTURE1 );
  20075. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20076. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20077. // update object positions
  20078. flare.positionScreen.copy( screenPosition )
  20079. if ( flare.customUpdateCallback ) {
  20080. flare.customUpdateCallback( flare );
  20081. } else {
  20082. flare.updateLensFlares();
  20083. }
  20084. // render flares
  20085. _gl.uniform1i( uniforms.renderType, 2 );
  20086. _gl.enable( _gl.BLEND );
  20087. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  20088. sprite = flare.lensFlares[ j ];
  20089. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  20090. screenPosition.x = sprite.x;
  20091. screenPosition.y = sprite.y;
  20092. screenPosition.z = sprite.z;
  20093. size = sprite.size * sprite.scale / viewportHeight;
  20094. scale.x = size * invAspect;
  20095. scale.y = size;
  20096. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  20097. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  20098. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20099. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20100. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20101. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20102. _renderer.setTexture( sprite.texture, 1 );
  20103. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20104. }
  20105. }
  20106. }
  20107. }
  20108. // restore gl
  20109. _gl.enable( _gl.CULL_FACE );
  20110. _gl.enable( _gl.DEPTH_TEST );
  20111. _gl.depthMask( true );
  20112. };
  20113. function createProgram ( shader ) {
  20114. var program = _gl.createProgram();
  20115. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20116. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20117. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20118. _gl.shaderSource( vertexShader, shader.vertexShader );
  20119. _gl.compileShader( fragmentShader );
  20120. _gl.compileShader( vertexShader );
  20121. _gl.attachShader( program, fragmentShader );
  20122. _gl.attachShader( program, vertexShader );
  20123. _gl.linkProgram( program );
  20124. return program;
  20125. };
  20126. };/**
  20127. * @author alteredq / http://alteredqualia.com/
  20128. */
  20129. THREE.ShadowMapPlugin = function ( ) {
  20130. var _gl,
  20131. _renderer,
  20132. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  20133. _frustum = new THREE.Frustum(),
  20134. _projScreenMatrix = new THREE.Matrix4(),
  20135. _min = new THREE.Vector3(),
  20136. _max = new THREE.Vector3();
  20137. this.init = function ( renderer ) {
  20138. _gl = renderer.context;
  20139. _renderer = renderer;
  20140. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20141. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20142. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20143. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20144. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  20145. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  20146. _depthMaterial._shadowPass = true;
  20147. _depthMaterialMorph._shadowPass = true;
  20148. _depthMaterialSkin._shadowPass = true;
  20149. _depthMaterialMorphSkin._shadowPass = true;
  20150. };
  20151. this.render = function ( scene, camera ) {
  20152. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  20153. this.update( scene, camera );
  20154. };
  20155. this.update = function ( scene, camera ) {
  20156. var i, il, j, jl, n,
  20157. shadowMap, shadowMatrix, shadowCamera,
  20158. program, buffer, material,
  20159. webglObject, object, light,
  20160. renderList,
  20161. lights = [],
  20162. k = 0,
  20163. fog = null;
  20164. // set GL state for depth map
  20165. _gl.clearColor( 1, 1, 1, 1 );
  20166. _gl.disable( _gl.BLEND );
  20167. _gl.enable( _gl.CULL_FACE );
  20168. _gl.frontFace( _gl.CCW );
  20169. if ( _renderer.shadowMapCullFrontFaces ) {
  20170. _gl.cullFace( _gl.FRONT );
  20171. } else {
  20172. _gl.cullFace( _gl.BACK );
  20173. }
  20174. _renderer.setDepthTest( true );
  20175. // preprocess lights
  20176. // - skip lights that are not casting shadows
  20177. // - create virtual lights for cascaded shadow maps
  20178. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  20179. light = scene.__lights[ i ];
  20180. if ( ! light.castShadow ) continue;
  20181. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  20182. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  20183. var virtualLight;
  20184. if ( ! light.shadowCascadeArray[ n ] ) {
  20185. virtualLight = createVirtualLight( light, n );
  20186. virtualLight.originalCamera = camera;
  20187. var gyro = new THREE.Gyroscope();
  20188. gyro.position = light.shadowCascadeOffset;
  20189. gyro.add( virtualLight );
  20190. gyro.add( virtualLight.target );
  20191. camera.add( gyro );
  20192. light.shadowCascadeArray[ n ] = virtualLight;
  20193. console.log( "Created virtualLight", virtualLight );
  20194. } else {
  20195. virtualLight = light.shadowCascadeArray[ n ];
  20196. }
  20197. updateVirtualLight( light, n );
  20198. lights[ k ] = virtualLight;
  20199. k ++;
  20200. }
  20201. } else {
  20202. lights[ k ] = light;
  20203. k ++;
  20204. }
  20205. }
  20206. // render depth map
  20207. for ( i = 0, il = lights.length; i < il; i ++ ) {
  20208. light = lights[ i ];
  20209. if ( ! light.shadowMap ) {
  20210. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  20211. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  20212. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  20213. light.shadowMatrix = new THREE.Matrix4();
  20214. }
  20215. if ( ! light.shadowCamera ) {
  20216. if ( light instanceof THREE.SpotLight ) {
  20217. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  20218. } else if ( light instanceof THREE.DirectionalLight ) {
  20219. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  20220. } else {
  20221. console.error( "Unsupported light type for shadow" );
  20222. continue;
  20223. }
  20224. scene.add( light.shadowCamera );
  20225. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20226. }
  20227. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  20228. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  20229. light.shadowCamera.add( light.cameraHelper );
  20230. }
  20231. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  20232. updateShadowCamera( camera, light );
  20233. }
  20234. shadowMap = light.shadowMap;
  20235. shadowMatrix = light.shadowMatrix;
  20236. shadowCamera = light.shadowCamera;
  20237. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  20238. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  20239. shadowCamera.updateMatrixWorld();
  20240. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  20241. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  20242. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  20243. // compute shadow matrix
  20244. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  20245. 0.0, 0.5, 0.0, 0.5,
  20246. 0.0, 0.0, 0.5, 0.5,
  20247. 0.0, 0.0, 0.0, 1.0 );
  20248. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  20249. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  20250. // update camera matrices and frustum
  20251. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  20252. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  20253. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  20254. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  20255. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  20256. _frustum.setFromMatrix( _projScreenMatrix );
  20257. // render shadow map
  20258. _renderer.setRenderTarget( shadowMap );
  20259. _renderer.clear();
  20260. // set object matrices & frustum culling
  20261. renderList = scene.__webglObjects;
  20262. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20263. webglObject = renderList[ j ];
  20264. object = webglObject.object;
  20265. webglObject.render = false;
  20266. if ( object.visible && object.castShadow ) {
  20267. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20268. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20269. webglObject.render = true;
  20270. }
  20271. }
  20272. }
  20273. // render regular objects
  20274. var objectMaterial, useMorphing, useSkinning;
  20275. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20276. webglObject = renderList[ j ];
  20277. if ( webglObject.render ) {
  20278. object = webglObject.object;
  20279. buffer = webglObject.buffer;
  20280. // culling is overriden globally for all objects
  20281. // while rendering depth map
  20282. // need to deal with MeshFaceMaterial somehow
  20283. // in that case just use the first of geometry.materials for now
  20284. // (proper solution would require to break objects by materials
  20285. // similarly to regular rendering and then set corresponding
  20286. // depth materials per each chunk instead of just once per object)
  20287. objectMaterial = getObjectMaterial( object );
  20288. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  20289. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  20290. if ( object.customDepthMaterial ) {
  20291. material = object.customDepthMaterial;
  20292. } else if ( useSkinning ) {
  20293. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  20294. } else if ( useMorphing ) {
  20295. material = _depthMaterialMorph;
  20296. } else {
  20297. material = _depthMaterial;
  20298. }
  20299. if ( buffer instanceof THREE.BufferGeometry ) {
  20300. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  20301. } else {
  20302. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  20303. }
  20304. }
  20305. }
  20306. // set matrices and render immediate objects
  20307. renderList = scene.__webglObjectsImmediate;
  20308. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20309. webglObject = renderList[ j ];
  20310. object = webglObject.object;
  20311. if ( object.visible && object.castShadow ) {
  20312. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  20313. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  20314. }
  20315. }
  20316. }
  20317. // restore GL state
  20318. var clearColor = _renderer.getClearColor(),
  20319. clearAlpha = _renderer.getClearAlpha();
  20320. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20321. _gl.enable( _gl.BLEND );
  20322. if ( _renderer.shadowMapCullFrontFaces ) {
  20323. _gl.cullFace( _gl.BACK );
  20324. }
  20325. };
  20326. function createVirtualLight( light, cascade ) {
  20327. var virtualLight = new THREE.DirectionalLight();
  20328. virtualLight.isVirtual = true;
  20329. virtualLight.onlyShadow = true;
  20330. virtualLight.castShadow = true;
  20331. virtualLight.shadowCameraNear = light.shadowCameraNear;
  20332. virtualLight.shadowCameraFar = light.shadowCameraFar;
  20333. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  20334. virtualLight.shadowCameraRight = light.shadowCameraRight;
  20335. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  20336. virtualLight.shadowCameraTop = light.shadowCameraTop;
  20337. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20338. virtualLight.shadowDarkness = light.shadowDarkness;
  20339. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20340. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  20341. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  20342. virtualLight.pointsWorld = [];
  20343. virtualLight.pointsFrustum = [];
  20344. var pointsWorld = virtualLight.pointsWorld,
  20345. pointsFrustum = virtualLight.pointsFrustum;
  20346. for ( var i = 0; i < 8; i ++ ) {
  20347. pointsWorld[ i ] = new THREE.Vector3();
  20348. pointsFrustum[ i ] = new THREE.Vector3();
  20349. }
  20350. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20351. var farZ = light.shadowCascadeFarZ[ cascade ];
  20352. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  20353. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  20354. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  20355. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  20356. pointsFrustum[ 4 ].set( -1, -1, farZ );
  20357. pointsFrustum[ 5 ].set( 1, -1, farZ );
  20358. pointsFrustum[ 6 ].set( -1, 1, farZ );
  20359. pointsFrustum[ 7 ].set( 1, 1, farZ );
  20360. return virtualLight;
  20361. }
  20362. // Synchronize virtual light with the original light
  20363. function updateVirtualLight( light, cascade ) {
  20364. var virtualLight = light.shadowCascadeArray[ cascade ];
  20365. virtualLight.position.copy( light.position );
  20366. virtualLight.target.position.copy( light.target.position );
  20367. virtualLight.lookAt( virtualLight.target );
  20368. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  20369. virtualLight.shadowDarkness = light.shadowDarkness;
  20370. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  20371. var nearZ = light.shadowCascadeNearZ[ cascade ];
  20372. var farZ = light.shadowCascadeFarZ[ cascade ];
  20373. var pointsFrustum = virtualLight.pointsFrustum;
  20374. pointsFrustum[ 0 ].z = nearZ;
  20375. pointsFrustum[ 1 ].z = nearZ;
  20376. pointsFrustum[ 2 ].z = nearZ;
  20377. pointsFrustum[ 3 ].z = nearZ;
  20378. pointsFrustum[ 4 ].z = farZ;
  20379. pointsFrustum[ 5 ].z = farZ;
  20380. pointsFrustum[ 6 ].z = farZ;
  20381. pointsFrustum[ 7 ].z = farZ;
  20382. }
  20383. // Fit shadow camera's ortho frustum to camera frustum
  20384. function updateShadowCamera( camera, light ) {
  20385. var shadowCamera = light.shadowCamera,
  20386. pointsFrustum = light.pointsFrustum,
  20387. pointsWorld = light.pointsWorld;
  20388. _min.set( Infinity, Infinity, Infinity );
  20389. _max.set( -Infinity, -Infinity, -Infinity );
  20390. for ( var i = 0; i < 8; i ++ ) {
  20391. var p = pointsWorld[ i ];
  20392. p.copy( pointsFrustum[ i ] );
  20393. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  20394. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  20395. if ( p.x < _min.x ) _min.x = p.x;
  20396. if ( p.x > _max.x ) _max.x = p.x;
  20397. if ( p.y < _min.y ) _min.y = p.y;
  20398. if ( p.y > _max.y ) _max.y = p.y;
  20399. if ( p.z < _min.z ) _min.z = p.z;
  20400. if ( p.z > _max.z ) _max.z = p.z;
  20401. }
  20402. shadowCamera.left = _min.x;
  20403. shadowCamera.right = _max.x;
  20404. shadowCamera.top = _max.y;
  20405. shadowCamera.bottom = _min.y;
  20406. // can't really fit near/far
  20407. //shadowCamera.near = _min.z;
  20408. //shadowCamera.far = _max.z;
  20409. shadowCamera.updateProjectionMatrix();
  20410. }
  20411. // For the moment just ignore objects that have multiple materials with different animation methods
  20412. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  20413. function getObjectMaterial( object ) {
  20414. return object.material instanceof THREE.MeshFaceMaterial ? object.geometry.materials[ 0 ] : object.material;
  20415. }
  20416. };
  20417. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  20418. /**
  20419. * @author mikael emtinger / http://gomo.se/
  20420. * @author alteredq / http://alteredqualia.com/
  20421. */
  20422. THREE.SpritePlugin = function ( ) {
  20423. var _gl, _renderer, _sprite = {};
  20424. this.init = function ( renderer ) {
  20425. _gl = renderer.context;
  20426. _renderer = renderer;
  20427. _sprite.vertices = new Float32Array( 8 + 8 );
  20428. _sprite.faces = new Uint16Array( 6 );
  20429. var i = 0;
  20430. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  20431. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  20432. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  20433. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  20434. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  20435. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  20436. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  20437. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  20438. i = 0;
  20439. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  20440. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  20441. _sprite.vertexBuffer = _gl.createBuffer();
  20442. _sprite.elementBuffer = _gl.createBuffer();
  20443. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20444. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  20445. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20446. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  20447. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  20448. _sprite.attributes = {};
  20449. _sprite.uniforms = {};
  20450. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  20451. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  20452. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  20453. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  20454. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  20455. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  20456. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  20457. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  20458. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  20459. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  20460. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  20461. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  20462. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  20463. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  20464. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  20465. _sprite.attributesEnabled = false;
  20466. };
  20467. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20468. var sprites = scene.__webglSprites,
  20469. nSprites = sprites.length;
  20470. if ( ! nSprites ) return;
  20471. var attributes = _sprite.attributes,
  20472. uniforms = _sprite.uniforms;
  20473. var invAspect = viewportHeight / viewportWidth;
  20474. var halfViewportWidth = viewportWidth * 0.5,
  20475. halfViewportHeight = viewportHeight * 0.5;
  20476. var mergeWith3D = true;
  20477. // setup gl
  20478. _gl.useProgram( _sprite.program );
  20479. if ( ! _sprite.attributesEnabled ) {
  20480. _gl.enableVertexAttribArray( attributes.position );
  20481. _gl.enableVertexAttribArray( attributes.uv );
  20482. _sprite.attributesEnabled = true;
  20483. }
  20484. _gl.disable( _gl.CULL_FACE );
  20485. _gl.enable( _gl.BLEND );
  20486. _gl.depthMask( true );
  20487. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  20488. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  20489. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  20490. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  20491. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  20492. _gl.activeTexture( _gl.TEXTURE0 );
  20493. _gl.uniform1i( uniforms.map, 0 );
  20494. // update positions and sort
  20495. var i, sprite, screenPosition, size, scale = [];
  20496. for( i = 0; i < nSprites; i ++ ) {
  20497. sprite = sprites[ i ];
  20498. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20499. if( ! sprite.useScreenCoordinates ) {
  20500. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  20501. sprite.z = - sprite._modelViewMatrix.elements[14];
  20502. } else {
  20503. sprite.z = - sprite.position.z;
  20504. }
  20505. }
  20506. sprites.sort( painterSort );
  20507. // render all sprites
  20508. for( i = 0; i < nSprites; i ++ ) {
  20509. sprite = sprites[ i ];
  20510. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  20511. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  20512. if ( sprite.useScreenCoordinates ) {
  20513. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  20514. _gl.uniform3f(
  20515. uniforms.screenPosition,
  20516. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  20517. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  20518. Math.max( 0, Math.min( 1, sprite.position.z ) )
  20519. );
  20520. } else {
  20521. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  20522. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  20523. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  20524. }
  20525. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  20526. scale[ 0 ] = size * invAspect * sprite.scale.x;
  20527. scale[ 1 ] = size * sprite.scale.y;
  20528. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  20529. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  20530. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  20531. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  20532. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  20533. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  20534. _gl.uniform2fv( uniforms.scale, scale );
  20535. if ( sprite.mergeWith3D && !mergeWith3D ) {
  20536. _gl.enable( _gl.DEPTH_TEST );
  20537. mergeWith3D = true;
  20538. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  20539. _gl.disable( _gl.DEPTH_TEST );
  20540. mergeWith3D = false;
  20541. }
  20542. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  20543. _renderer.setTexture( sprite.map, 0 );
  20544. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  20545. }
  20546. }
  20547. // restore gl
  20548. _gl.enable( _gl.CULL_FACE );
  20549. _gl.enable( _gl.DEPTH_TEST );
  20550. _gl.depthMask( true );
  20551. };
  20552. function createProgram ( shader ) {
  20553. var program = _gl.createProgram();
  20554. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  20555. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  20556. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  20557. _gl.shaderSource( vertexShader, shader.vertexShader );
  20558. _gl.compileShader( fragmentShader );
  20559. _gl.compileShader( vertexShader );
  20560. _gl.attachShader( program, fragmentShader );
  20561. _gl.attachShader( program, vertexShader );
  20562. _gl.linkProgram( program );
  20563. return program;
  20564. };
  20565. function painterSort ( a, b ) {
  20566. return b.z - a.z;
  20567. };
  20568. };
  20569. /**
  20570. * @author alteredq / http://alteredqualia.com/
  20571. */
  20572. THREE.DepthPassPlugin = function ( ) {
  20573. this.enabled = false;
  20574. this.renderTarget = null;
  20575. var _gl,
  20576. _renderer,
  20577. _depthMaterial, _depthMaterialMorph,
  20578. _frustum = new THREE.Frustum(),
  20579. _projScreenMatrix = new THREE.Matrix4();
  20580. this.init = function ( renderer ) {
  20581. _gl = renderer.context;
  20582. _renderer = renderer;
  20583. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  20584. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  20585. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  20586. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  20587. _depthMaterial._shadowPass = true;
  20588. _depthMaterialMorph._shadowPass = true;
  20589. };
  20590. this.render = function ( scene, camera ) {
  20591. if ( ! this.enabled ) return;
  20592. this.update( scene, camera );
  20593. };
  20594. this.update = function ( scene, camera ) {
  20595. var i, il, j, jl, n,
  20596. program, buffer, material,
  20597. webglObject, object, light,
  20598. renderList,
  20599. fog = null;
  20600. // set GL state for depth map
  20601. _gl.clearColor( 1, 1, 1, 1 );
  20602. _gl.disable( _gl.BLEND );
  20603. _renderer.setDepthTest( true );
  20604. // update scene
  20605. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  20606. // update camera matrices and frustum
  20607. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  20608. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  20609. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  20610. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  20611. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  20612. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  20613. _frustum.setFromMatrix( _projScreenMatrix );
  20614. // render depth map
  20615. _renderer.setRenderTarget( this.renderTarget );
  20616. _renderer.clear();
  20617. // set object matrices & frustum culling
  20618. renderList = scene.__webglObjects;
  20619. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20620. webglObject = renderList[ j ];
  20621. object = webglObject.object;
  20622. webglObject.render = false;
  20623. if ( object.visible ) {
  20624. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  20625. //object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20626. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20627. webglObject.render = true;
  20628. }
  20629. }
  20630. }
  20631. // render regular objects
  20632. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20633. webglObject = renderList[ j ];
  20634. if ( webglObject.render ) {
  20635. object = webglObject.object;
  20636. buffer = webglObject.buffer;
  20637. if ( object.material ) _renderer.setMaterialFaces( object.material );
  20638. if ( object.customDepthMaterial ) {
  20639. material = object.customDepthMaterial;
  20640. } else if ( object.geometry.morphTargets.length ) {
  20641. material = _depthMaterialMorph;
  20642. } else {
  20643. material = _depthMaterial;
  20644. }
  20645. if ( buffer instanceof THREE.BufferGeometry ) {
  20646. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  20647. } else {
  20648. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  20649. }
  20650. }
  20651. }
  20652. // set matrices and render immediate objects
  20653. renderList = scene.__webglObjectsImmediate;
  20654. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  20655. webglObject = renderList[ j ];
  20656. object = webglObject.object;
  20657. if ( object.visible && object.castShadow ) {
  20658. /*
  20659. if ( object.matrixAutoUpdate ) {
  20660. object.matrixWorld.flattenToArray( object._modelMatrixArray );
  20661. }
  20662. */
  20663. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  20664. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  20665. }
  20666. }
  20667. // restore GL state
  20668. var clearColor = _renderer.getClearColor(),
  20669. clearAlpha = _renderer.getClearAlpha();
  20670. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  20671. _gl.enable( _gl.BLEND );
  20672. };
  20673. };
  20674. /**
  20675. * @author mikael emtinger / http://gomo.se/
  20676. *
  20677. */
  20678. THREE.ShaderFlares = {
  20679. 'lensFlareVertexTexture': {
  20680. vertexShader: [
  20681. "uniform vec3 screenPosition;",
  20682. "uniform vec2 scale;",
  20683. "uniform float rotation;",
  20684. "uniform int renderType;",
  20685. "uniform sampler2D occlusionMap;",
  20686. "attribute vec2 position;",
  20687. "attribute vec2 uv;",
  20688. "varying vec2 vUV;",
  20689. "varying float vVisibility;",
  20690. "void main() {",
  20691. "vUV = uv;",
  20692. "vec2 pos = position;",
  20693. "if( renderType == 2 ) {",
  20694. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  20695. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  20696. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  20697. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  20698. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  20699. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  20700. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  20701. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  20702. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  20703. "vVisibility = ( visibility.r / 9.0 ) *",
  20704. "( 1.0 - visibility.g / 9.0 ) *",
  20705. "( visibility.b / 9.0 ) *",
  20706. "( 1.0 - visibility.a / 9.0 );",
  20707. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  20708. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  20709. "}",
  20710. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  20711. "}"
  20712. ].join( "\n" ),
  20713. fragmentShader: [
  20714. "precision mediump float;",
  20715. "uniform sampler2D map;",
  20716. "uniform float opacity;",
  20717. "uniform int renderType;",
  20718. "uniform vec3 color;",
  20719. "varying vec2 vUV;",
  20720. "varying float vVisibility;",
  20721. "void main() {",
  20722. // pink square
  20723. "if( renderType == 0 ) {",
  20724. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  20725. // restore
  20726. "} else if( renderType == 1 ) {",
  20727. "gl_FragColor = texture2D( map, vUV );",
  20728. // flare
  20729. "} else {",
  20730. "vec4 texture = texture2D( map, vUV );",
  20731. "texture.a *= opacity * vVisibility;",
  20732. "gl_FragColor = texture;",
  20733. "gl_FragColor.rgb *= color;",
  20734. "}",
  20735. "}"
  20736. ].join( "\n" )
  20737. },
  20738. 'lensFlare': {
  20739. vertexShader: [
  20740. "uniform vec3 screenPosition;",
  20741. "uniform vec2 scale;",
  20742. "uniform float rotation;",
  20743. "uniform int renderType;",
  20744. "attribute vec2 position;",
  20745. "attribute vec2 uv;",
  20746. "varying vec2 vUV;",
  20747. "void main() {",
  20748. "vUV = uv;",
  20749. "vec2 pos = position;",
  20750. "if( renderType == 2 ) {",
  20751. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  20752. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  20753. "}",
  20754. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  20755. "}"
  20756. ].join( "\n" ),
  20757. fragmentShader: [
  20758. "precision mediump float;",
  20759. "uniform sampler2D map;",
  20760. "uniform sampler2D occlusionMap;",
  20761. "uniform float opacity;",
  20762. "uniform int renderType;",
  20763. "uniform vec3 color;",
  20764. "varying vec2 vUV;",
  20765. "void main() {",
  20766. // pink square
  20767. "if( renderType == 0 ) {",
  20768. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  20769. // restore
  20770. "} else if( renderType == 1 ) {",
  20771. "gl_FragColor = texture2D( map, vUV );",
  20772. // flare
  20773. "} else {",
  20774. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  20775. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  20776. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  20777. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  20778. "visibility = ( 1.0 - visibility / 4.0 );",
  20779. "vec4 texture = texture2D( map, vUV );",
  20780. "texture.a *= opacity * visibility;",
  20781. "gl_FragColor = texture;",
  20782. "gl_FragColor.rgb *= color;",
  20783. "}",
  20784. "}"
  20785. ].join( "\n" )
  20786. }
  20787. };
  20788. /**
  20789. * @author mikael emtinger / http://gomo.se/
  20790. *
  20791. */
  20792. THREE.ShaderSprite = {
  20793. 'sprite': {
  20794. vertexShader: [
  20795. "uniform int useScreenCoordinates;",
  20796. "uniform int affectedByDistance;",
  20797. "uniform vec3 screenPosition;",
  20798. "uniform mat4 modelViewMatrix;",
  20799. "uniform mat4 projectionMatrix;",
  20800. "uniform float rotation;",
  20801. "uniform vec2 scale;",
  20802. "uniform vec2 alignment;",
  20803. "uniform vec2 uvOffset;",
  20804. "uniform vec2 uvScale;",
  20805. "attribute vec2 position;",
  20806. "attribute vec2 uv;",
  20807. "varying vec2 vUV;",
  20808. "void main() {",
  20809. "vUV = uvOffset + uv * uvScale;",
  20810. "vec2 alignedPosition = position + alignment;",
  20811. "vec2 rotatedPosition;",
  20812. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  20813. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  20814. "vec4 finalPosition;",
  20815. "if( useScreenCoordinates != 0 ) {",
  20816. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  20817. "} else {",
  20818. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  20819. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  20820. "}",
  20821. "gl_Position = finalPosition;",
  20822. "}"
  20823. ].join( "\n" ),
  20824. fragmentShader: [
  20825. "precision mediump float;",
  20826. "uniform vec3 color;",
  20827. "uniform sampler2D map;",
  20828. "uniform float opacity;",
  20829. "varying vec2 vUV;",
  20830. "void main() {",
  20831. "vec4 texture = texture2D( map, vUV );",
  20832. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  20833. "}"
  20834. ].join( "\n" )
  20835. }
  20836. };
粤ICP备19079148号