three.js 850 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. * @author Larry Battle / http://bateru.com/news
  4. */
  5. var THREE = THREE || { REVISION: '54dev' };
  6. self.console = self.console || {
  7. info: function () {},
  8. log: function () {},
  9. debug: function () {},
  10. warn: function () {},
  11. error: function () {}
  12. };
  13. self.Int32Array = self.Int32Array || Array;
  14. self.Float32Array = self.Float32Array || Array;
  15. // Shims for "startsWith", "endsWith", and "trim" for browsers where this is not yet implemented
  16. // not sure we should have this, or at least not have it here
  17. // http://stackoverflow.com/questions/646628/javascript-startswith
  18. // http://stackoverflow.com/questions/498970/how-do-i-trim-a-string-in-javascript
  19. // http://wiki.ecmascript.org/doku.php?id=harmony%3astring_extras
  20. String.prototype.startsWith = String.prototype.startsWith || function ( str ) {
  21. return this.slice( 0, str.length ) === str;
  22. };
  23. String.prototype.endsWith = String.prototype.endsWith || function ( str ) {
  24. var t = String( str );
  25. var index = this.lastIndexOf( t );
  26. return ( -1 < index && index ) === (this.length - t.length);
  27. };
  28. String.prototype.trim = String.prototype.trim || function () {
  29. return this.replace( /^\s+|\s+$/g, '' );
  30. };
  31. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  32. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  33. // requestAnimationFrame polyfill by Erik Möller
  34. // fixes from Paul Irish and Tino Zijdel
  35. ( function () {
  36. var lastTime = 0;
  37. var vendors = [ 'ms', 'moz', 'webkit', 'o' ];
  38. for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) {
  39. window.requestAnimationFrame = window[ vendors[ x ] + 'RequestAnimationFrame' ];
  40. window.cancelAnimationFrame = window[ vendors[ x ] + 'CancelAnimationFrame' ] || window[ vendors[ x ] + 'CancelRequestAnimationFrame' ];
  41. }
  42. if ( window.requestAnimationFrame === undefined ) {
  43. window.requestAnimationFrame = function ( callback, element ) {
  44. var currTime = Date.now(), timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  45. var id = window.setTimeout( function() { callback( currTime + timeToCall ); }, timeToCall );
  46. lastTime = currTime + timeToCall;
  47. return id;
  48. };
  49. }
  50. window.cancelAnimationFrame = window.cancelAnimationFrame || function ( id ) { window.clearTimeout( id ) };
  51. }() );
  52. // GL STATE CONSTANTS
  53. THREE.CullFaceNone = 0;
  54. THREE.CullFaceBack = 1;
  55. THREE.CullFaceFront = 2;
  56. THREE.CullFaceFrontBack = 3;
  57. THREE.FrontFaceDirectionCW = 0;
  58. THREE.FrontFaceDirectionCCW = 1;
  59. // MATERIAL CONSTANTS
  60. // side
  61. THREE.FrontSide = 0;
  62. THREE.BackSide = 1;
  63. THREE.DoubleSide = 2;
  64. // shading
  65. THREE.NoShading = 0;
  66. THREE.FlatShading = 1;
  67. THREE.SmoothShading = 2;
  68. // colors
  69. THREE.NoColors = 0;
  70. THREE.FaceColors = 1;
  71. THREE.VertexColors = 2;
  72. // blending modes
  73. THREE.NoBlending = 0;
  74. THREE.NormalBlending = 1;
  75. THREE.AdditiveBlending = 2;
  76. THREE.SubtractiveBlending = 3;
  77. THREE.MultiplyBlending = 4;
  78. THREE.CustomBlending = 5;
  79. // custom blending equations
  80. // (numbers start from 100 not to clash with other
  81. // mappings to OpenGL constants defined in Texture.js)
  82. THREE.AddEquation = 100;
  83. THREE.SubtractEquation = 101;
  84. THREE.ReverseSubtractEquation = 102;
  85. // custom blending destination factors
  86. THREE.ZeroFactor = 200;
  87. THREE.OneFactor = 201;
  88. THREE.SrcColorFactor = 202;
  89. THREE.OneMinusSrcColorFactor = 203;
  90. THREE.SrcAlphaFactor = 204;
  91. THREE.OneMinusSrcAlphaFactor = 205;
  92. THREE.DstAlphaFactor = 206;
  93. THREE.OneMinusDstAlphaFactor = 207;
  94. // custom blending source factors
  95. //THREE.ZeroFactor = 200;
  96. //THREE.OneFactor = 201;
  97. //THREE.SrcAlphaFactor = 204;
  98. //THREE.OneMinusSrcAlphaFactor = 205;
  99. //THREE.DstAlphaFactor = 206;
  100. //THREE.OneMinusDstAlphaFactor = 207;
  101. THREE.DstColorFactor = 208;
  102. THREE.OneMinusDstColorFactor = 209;
  103. THREE.SrcAlphaSaturateFactor = 210;
  104. // TEXTURE CONSTANTS
  105. THREE.MultiplyOperation = 0;
  106. THREE.MixOperation = 1;
  107. THREE.AddOperation = 2;
  108. // Mapping modes
  109. THREE.UVMapping = function () {};
  110. THREE.CubeReflectionMapping = function () {};
  111. THREE.CubeRefractionMapping = function () {};
  112. THREE.SphericalReflectionMapping = function () {};
  113. THREE.SphericalRefractionMapping = function () {};
  114. // Wrapping modes
  115. THREE.RepeatWrapping = 1000;
  116. THREE.ClampToEdgeWrapping = 1001;
  117. THREE.MirroredRepeatWrapping = 1002;
  118. // Filters
  119. THREE.NearestFilter = 1003;
  120. THREE.NearestMipMapNearestFilter = 1004;
  121. THREE.NearestMipMapLinearFilter = 1005;
  122. THREE.LinearFilter = 1006;
  123. THREE.LinearMipMapNearestFilter = 1007;
  124. THREE.LinearMipMapLinearFilter = 1008;
  125. // Data types
  126. THREE.UnsignedByteType = 1009;
  127. THREE.ByteType = 1010;
  128. THREE.ShortType = 1011;
  129. THREE.UnsignedShortType = 1012;
  130. THREE.IntType = 1013;
  131. THREE.UnsignedIntType = 1014;
  132. THREE.FloatType = 1015;
  133. // Pixel types
  134. //THREE.UnsignedByteType = 1009;
  135. THREE.UnsignedShort4444Type = 1016;
  136. THREE.UnsignedShort5551Type = 1017;
  137. THREE.UnsignedShort565Type = 1018;
  138. // Pixel formats
  139. THREE.AlphaFormat = 1019;
  140. THREE.RGBFormat = 1020;
  141. THREE.RGBAFormat = 1021;
  142. THREE.LuminanceFormat = 1022;
  143. THREE.LuminanceAlphaFormat = 1023;
  144. // Compressed texture formats
  145. THREE.RGB_S3TC_DXT1_Format = 2001;
  146. THREE.RGBA_S3TC_DXT1_Format = 2002;
  147. THREE.RGBA_S3TC_DXT3_Format = 2003;
  148. THREE.RGBA_S3TC_DXT5_Format = 2004;
  149. /*
  150. // Potential future PVRTC compressed texture formats
  151. THREE.RGB_PVRTC_4BPPV1_Format = 2100;
  152. THREE.RGB_PVRTC_2BPPV1_Format = 2101;
  153. THREE.RGBA_PVRTC_4BPPV1_Format = 2102;
  154. THREE.RGBA_PVRTC_2BPPV1_Format = 2103;
  155. */
  156. /**
  157. * @author alteredq / http://alteredqualia.com/
  158. */
  159. THREE.Clock = function ( autoStart ) {
  160. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  161. this.startTime = 0;
  162. this.oldTime = 0;
  163. this.elapsedTime = 0;
  164. this.running = false;
  165. };
  166. THREE.Clock.prototype.start = function () {
  167. this.startTime = Date.now();
  168. this.oldTime = this.startTime;
  169. this.running = true;
  170. };
  171. THREE.Clock.prototype.stop = function () {
  172. this.getElapsedTime();
  173. this.running = false;
  174. };
  175. THREE.Clock.prototype.getElapsedTime = function () {
  176. this.getDelta();
  177. return this.elapsedTime;
  178. };
  179. THREE.Clock.prototype.getDelta = function () {
  180. var diff = 0;
  181. if ( this.autoStart && ! this.running ) {
  182. this.start();
  183. }
  184. if ( this.running ) {
  185. var newTime = Date.now();
  186. diff = 0.001 * ( newTime - this.oldTime );
  187. this.oldTime = newTime;
  188. this.elapsedTime += diff;
  189. }
  190. return diff;
  191. };/**
  192. * @author mrdoob / http://mrdoob.com/
  193. */
  194. THREE.Color = function ( value ) {
  195. if ( value !== undefined ) this.set( value );
  196. return this;
  197. };
  198. THREE.Color.prototype = {
  199. constructor: THREE.Color,
  200. r: 1, g: 1, b: 1,
  201. copy: function ( color ) {
  202. this.r = color.r;
  203. this.g = color.g;
  204. this.b = color.b;
  205. return this;
  206. },
  207. copyGammaToLinear: function ( color ) {
  208. this.r = color.r * color.r;
  209. this.g = color.g * color.g;
  210. this.b = color.b * color.b;
  211. return this;
  212. },
  213. copyLinearToGamma: function ( color ) {
  214. this.r = Math.sqrt( color.r );
  215. this.g = Math.sqrt( color.g );
  216. this.b = Math.sqrt( color.b );
  217. return this;
  218. },
  219. convertGammaToLinear: function () {
  220. var r = this.r, g = this.g, b = this.b;
  221. this.r = r * r;
  222. this.g = g * g;
  223. this.b = b * b;
  224. return this;
  225. },
  226. convertLinearToGamma: function () {
  227. this.r = Math.sqrt( this.r );
  228. this.g = Math.sqrt( this.g );
  229. this.b = Math.sqrt( this.b );
  230. return this;
  231. },
  232. set: function ( value ) {
  233. switch ( typeof value ) {
  234. case "number":
  235. this.setHex( value );
  236. break;
  237. case "string":
  238. this.setStyle( value );
  239. break;
  240. }
  241. },
  242. setRGB: function ( r, g, b ) {
  243. this.r = r;
  244. this.g = g;
  245. this.b = b;
  246. return this;
  247. },
  248. setHSV: function ( h, s, v ) {
  249. // based on MochiKit implementation by Bob Ippolito
  250. // h,s,v ranges are < 0.0 - 1.0 >
  251. var i, f, p, q, t;
  252. if ( v === 0 ) {
  253. this.r = this.g = this.b = 0;
  254. } else {
  255. i = Math.floor( h * 6 );
  256. f = ( h * 6 ) - i;
  257. p = v * ( 1 - s );
  258. q = v * ( 1 - ( s * f ) );
  259. t = v * ( 1 - ( s * ( 1 - f ) ) );
  260. if ( i === 0 ) {
  261. this.r = v;
  262. this.g = t;
  263. this.b = p;
  264. } else if ( i === 1 ) {
  265. this.r = q;
  266. this.g = v;
  267. this.b = p;
  268. } else if ( i === 2 ) {
  269. this.r = p;
  270. this.g = v;
  271. this.b = t;
  272. } else if ( i === 3 ) {
  273. this.r = p;
  274. this.g = q;
  275. this.b = v;
  276. } else if ( i === 4 ) {
  277. this.r = t;
  278. this.g = p;
  279. this.b = v;
  280. } else if ( i === 5 ) {
  281. this.r = v;
  282. this.g = p;
  283. this.b = q;
  284. }
  285. }
  286. return this;
  287. },
  288. getHex: function () {
  289. return ( this.r * 255 ) << 16 ^ ( this.g * 255 ) << 8 ^ ( this.b * 255 ) << 0;
  290. },
  291. setHex: function ( hex ) {
  292. hex = Math.floor( hex );
  293. this.r = ( hex >> 16 & 255 ) / 255;
  294. this.g = ( hex >> 8 & 255 ) / 255;
  295. this.b = ( hex & 255 ) / 255;
  296. return this;
  297. },
  298. getHexString: function () {
  299. return ( '000000' + this.getHex().toString( 16 ) ).slice( - 6 );
  300. },
  301. getStyle: function () {
  302. return 'rgb(' + ( ( this.r * 255 ) | 0 ) + ',' + ( ( this.g * 255 ) | 0 ) + ',' + ( ( this.b * 255 ) | 0 ) + ')';
  303. },
  304. setStyle: function ( style ) {
  305. // rgb(255,0,0)
  306. if ( /^rgb\((\d+),(\d+),(\d+)\)$/i.test( style ) ) {
  307. var color = /^rgb\((\d+),(\d+),(\d+)\)$/i.exec( style );
  308. this.r = Math.min( 255, parseInt( color[ 1 ], 10 ) ) / 255;
  309. this.g = Math.min( 255, parseInt( color[ 2 ], 10 ) ) / 255;
  310. this.b = Math.min( 255, parseInt( color[ 3 ], 10 ) ) / 255;
  311. return this;
  312. }
  313. // rgb(100%,0%,0%)
  314. if ( /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.test( style ) ) {
  315. var color = /^rgb\((\d+)\%,(\d+)\%,(\d+)\%\)$/i.exec( style );
  316. this.r = Math.min( 100, parseInt( color[ 1 ], 10 ) ) / 100;
  317. this.g = Math.min( 100, parseInt( color[ 2 ], 10 ) ) / 100;
  318. this.b = Math.min( 100, parseInt( color[ 3 ], 10 ) ) / 100;
  319. return this;
  320. }
  321. // #ff0000
  322. if ( /^\#([0-9a-f]{6})$/i.test( style ) ) {
  323. var color = /^\#([0-9a-f]{6})$/i.exec( style );
  324. this.setHex( parseInt( color[ 1 ], 16 ) );
  325. return this;
  326. }
  327. // #f00
  328. if ( /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.test( style ) ) {
  329. var color = /^\#([0-9a-f])([0-9a-f])([0-9a-f])$/i.exec( style );
  330. this.setHex( parseInt( color[ 1 ] + color[ 1 ] + color[ 2 ] + color[ 2 ] + color[ 3 ] + color[ 3 ], 16 ) );
  331. return this;
  332. }
  333. // red
  334. if ( /^(\w+)$/i.test( style ) ) {
  335. this.setHex( THREE.ColorKeywords[ style ] );
  336. return this;
  337. }
  338. },
  339. getHSV: function ( hsv ) {
  340. // based on MochiKit implementation by Bob Ippolito
  341. // h,s,v ranges are < 0.0 - 1.0 >
  342. var r = this.r;
  343. var g = this.g;
  344. var b = this.b;
  345. var max = Math.max( Math.max( r, g ), b );
  346. var min = Math.min( Math.min( r, g ), b );
  347. var hue;
  348. var saturation;
  349. var value = max;
  350. if ( min === max ) {
  351. hue = 0;
  352. saturation = 0;
  353. } else {
  354. var delta = ( max - min );
  355. saturation = delta / max;
  356. if ( r === max ) {
  357. hue = ( g - b ) / delta;
  358. } else if ( g === max ) {
  359. hue = 2 + ( ( b - r ) / delta );
  360. } else {
  361. hue = 4 + ( ( r - g ) / delta );
  362. }
  363. hue /= 6;
  364. if ( hue < 0 ) {
  365. hue += 1;
  366. }
  367. if ( hue > 1 ) {
  368. hue -= 1;
  369. }
  370. }
  371. if ( hsv === undefined ) {
  372. hsv = { h: 0, s: 0, v: 0 };
  373. }
  374. hsv.h = hue;
  375. hsv.s = saturation;
  376. hsv.v = value;
  377. return hsv;
  378. },
  379. lerpSelf: function ( color, alpha ) {
  380. this.r += ( color.r - this.r ) * alpha;
  381. this.g += ( color.g - this.g ) * alpha;
  382. this.b += ( color.b - this.b ) * alpha;
  383. return this;
  384. },
  385. clone: function () {
  386. return new THREE.Color().setRGB( this.r, this.g, this.b );
  387. }
  388. };
  389. THREE.ColorKeywords = { "aliceblue": 0xF0F8FF, "antiquewhite": 0xFAEBD7, "aqua": 0x00FFFF, "aquamarine": 0x7FFFD4, "azure": 0xF0FFFF, "beige": 0xF5F5DC, "bisque": 0xFFE4C4, "black": 0x000000, "blanchedalmond": 0xFFEBCD, "blue": 0x0000FF, "blueviolet": 0x8A2BE2, "brown": 0xA52A2A, "burlywood": 0xDEB887, "cadetblue": 0x5F9EA0, "chartreuse": 0x7FFF00, "chocolate": 0xD2691E, "coral": 0xFF7F50, "cornflowerblue": 0x6495ED, "cornsilk": 0xFFF8DC, "crimson": 0xDC143C, "cyan": 0x00FFFF, "darkblue": 0x00008B, "darkcyan": 0x008B8B, "darkgoldenrod": 0xB8860B, "darkgray": 0xA9A9A9, "darkgreen": 0x006400, "darkgrey": 0xA9A9A9, "darkkhaki": 0xBDB76B, "darkmagenta": 0x8B008B, "darkolivegreen": 0x556B2F, "darkorange": 0xFF8C00, "darkorchid": 0x9932CC, "darkred": 0x8B0000, "darksalmon": 0xE9967A, "darkseagreen": 0x8FBC8F, "darkslateblue": 0x483D8B, "darkslategray": 0x2F4F4F, "darkslategrey": 0x2F4F4F, "darkturquoise": 0x00CED1, "darkviolet": 0x9400D3, "deeppink": 0xFF1493, "deepskyblue": 0x00BFFF, "dimgray": 0x696969, "dimgrey": 0x696969, "dodgerblue": 0x1E90FF, "firebrick": 0xB22222, "floralwhite": 0xFFFAF0, "forestgreen": 0x228B22, "fuchsia": 0xFF00FF, "gainsboro": 0xDCDCDC, "ghostwhite": 0xF8F8FF, "gold": 0xFFD700, "goldenrod": 0xDAA520, "gray": 0x808080, "green": 0x008000, "greenyellow": 0xADFF2F, "grey": 0x808080, "honeydew": 0xF0FFF0, "hotpink": 0xFF69B4, "indianred": 0xCD5C5C, "indigo": 0x4B0082, "ivory": 0xFFFFF0, "khaki": 0xF0E68C, "lavender": 0xE6E6FA, "lavenderblush": 0xFFF0F5, "lawngreen": 0x7CFC00, "lemonchiffon": 0xFFFACD, "lightblue": 0xADD8E6, "lightcoral": 0xF08080, "lightcyan": 0xE0FFFF, "lightgoldenrodyellow": 0xFAFAD2, "lightgray": 0xD3D3D3, "lightgreen": 0x90EE90, "lightgrey": 0xD3D3D3, "lightpink": 0xFFB6C1, "lightsalmon": 0xFFA07A, "lightseagreen": 0x20B2AA, "lightskyblue": 0x87CEFA, "lightslategray": 0x778899, "lightslategrey": 0x778899, "lightsteelblue": 0xB0C4DE, "lightyellow": 0xFFFFE0, "lime": 0x00FF00, "limegreen": 0x32CD32, "linen": 0xFAF0E6, "magenta": 0xFF00FF, "maroon": 0x800000, "mediumaquamarine": 0x66CDAA, "mediumblue": 0x0000CD, "mediumorchid": 0xBA55D3, "mediumpurple": 0x9370DB, "mediumseagreen": 0x3CB371, "mediumslateblue": 0x7B68EE, "mediumspringgreen": 0x00FA9A, "mediumturquoise": 0x48D1CC, "mediumvioletred": 0xC71585, "midnightblue": 0x191970, "mintcream": 0xF5FFFA, "mistyrose": 0xFFE4E1, "moccasin": 0xFFE4B5, "navajowhite": 0xFFDEAD, "navy": 0x000080, "oldlace": 0xFDF5E6, "olive": 0x808000, "olivedrab": 0x6B8E23, "orange": 0xFFA500, "orangered": 0xFF4500, "orchid": 0xDA70D6, "palegoldenrod": 0xEEE8AA, "palegreen": 0x98FB98, "paleturquoise": 0xAFEEEE, "palevioletred": 0xDB7093, "papayawhip": 0xFFEFD5, "peachpuff": 0xFFDAB9, "peru": 0xCD853F, "pink": 0xFFC0CB, "plum": 0xDDA0DD, "powderblue": 0xB0E0E6, "purple": 0x800080, "red": 0xFF0000, "rosybrown": 0xBC8F8F, "royalblue": 0x4169E1, "saddlebrown": 0x8B4513, "salmon": 0xFA8072, "sandybrown": 0xF4A460, "seagreen": 0x2E8B57, "seashell": 0xFFF5EE, "sienna": 0xA0522D, "silver": 0xC0C0C0, "skyblue": 0x87CEEB, "slateblue": 0x6A5ACD, "slategray": 0x708090, "slategrey": 0x708090, "snow": 0xFFFAFA, "springgreen": 0x00FF7F, "steelblue": 0x4682B4, "tan": 0xD2B48C, "teal": 0x008080, "thistle": 0xD8BFD8, "tomato": 0xFF6347, "turquoise": 0x40E0D0, "violet": 0xEE82EE, "wheat": 0xF5DEB3, "white": 0xFFFFFF, "whitesmoke": 0xF5F5F5, "yellow": 0xFFFF00, "yellowgreen": 0x9ACD32 };
  390. /**
  391. * @author mrdoob / http://mrdoob.com/
  392. * @author philogb / http://blog.thejit.org/
  393. * @author egraether / http://egraether.com/
  394. * @author zz85 / http://www.lab4games.net/zz85/blog
  395. */
  396. THREE.Vector2 = function ( x, y ) {
  397. this.x = x || 0;
  398. this.y = y || 0;
  399. };
  400. THREE.Vector2.prototype = {
  401. constructor: THREE.Vector2,
  402. set: function ( x, y ) {
  403. this.x = x;
  404. this.y = y;
  405. return this;
  406. },
  407. setX: function ( x ) {
  408. this.x = x;
  409. return this;
  410. },
  411. setY: function ( y ) {
  412. this.y = y;
  413. return this;
  414. },
  415. copy: function ( v ) {
  416. this.x = v.x;
  417. this.y = v.y;
  418. return this;
  419. },
  420. addScalar: function ( s ) {
  421. this.x += s;
  422. this.y += s;
  423. return this;
  424. },
  425. add: function ( a, b ) {
  426. this.x = a.x + b.x;
  427. this.y = a.y + b.y;
  428. return this;
  429. },
  430. addSelf: function ( v ) {
  431. this.x += v.x;
  432. this.y += v.y;
  433. return this;
  434. },
  435. sub: function ( a, b ) {
  436. this.x = a.x - b.x;
  437. this.y = a.y - b.y;
  438. return this;
  439. },
  440. subSelf: function ( v ) {
  441. this.x -= v.x;
  442. this.y -= v.y;
  443. return this;
  444. },
  445. multiplyScalar: function ( s ) {
  446. this.x *= s;
  447. this.y *= s;
  448. return this;
  449. },
  450. divideScalar: function ( s ) {
  451. if ( s ) {
  452. this.x /= s;
  453. this.y /= s;
  454. } else {
  455. this.set( 0, 0 );
  456. }
  457. return this;
  458. },
  459. minSelf: function ( v ) {
  460. if ( this.x > v.x ) {
  461. this.x = v.x;
  462. }
  463. if ( this.y > v.y ) {
  464. this.y = v.y;
  465. }
  466. return this;
  467. },
  468. maxSelf: function ( v ) {
  469. if ( this.x < v.x ) {
  470. this.x = v.x;
  471. }
  472. if ( this.y < v.y ) {
  473. this.y = v.y;
  474. }
  475. return this;
  476. },
  477. clampSelf: function ( min, max ) {
  478. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  479. if ( this.x < min.x ) {
  480. this.x = min.x;
  481. } else if ( this.x > max.x ) {
  482. this.x = max.x;
  483. }
  484. if ( this.y < min.y ) {
  485. this.y = min.y;
  486. } else if ( this.y > max.y ) {
  487. this.y = max.y;
  488. }
  489. return this;
  490. },
  491. negate: function() {
  492. return this.multiplyScalar( - 1 );
  493. },
  494. dot: function ( v ) {
  495. return this.x * v.x + this.y * v.y;
  496. },
  497. lengthSq: function () {
  498. return this.x * this.x + this.y * this.y;
  499. },
  500. length: function () {
  501. return Math.sqrt( this.lengthSq() );
  502. },
  503. normalize: function () {
  504. return this.divideScalar( this.length() );
  505. },
  506. distanceTo: function ( v ) {
  507. return Math.sqrt( this.distanceToSquared( v ) );
  508. },
  509. distanceToSquared: function ( v ) {
  510. var dx = this.x - v.x, dy = this.y - v.y;
  511. return dx * dx + dy * dy;
  512. },
  513. setLength: function ( l ) {
  514. return this.normalize().multiplyScalar( l );
  515. },
  516. lerpSelf: function ( v, alpha ) {
  517. this.x += ( v.x - this.x ) * alpha;
  518. this.y += ( v.y - this.y ) * alpha;
  519. return this;
  520. },
  521. equals: function( v ) {
  522. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  523. },
  524. clone: function () {
  525. return new THREE.Vector2( this.x, this.y );
  526. }
  527. };
  528. /**
  529. * @author mrdoob / http://mrdoob.com/
  530. * @author *kile / http://kile.stravaganza.org/
  531. * @author philogb / http://blog.thejit.org/
  532. * @author mikael emtinger / http://gomo.se/
  533. * @author egraether / http://egraether.com/
  534. * @author WestLangley / http://github.com/WestLangley
  535. */
  536. THREE.Vector3 = function ( x, y, z ) {
  537. this.x = x || 0;
  538. this.y = y || 0;
  539. this.z = z || 0;
  540. };
  541. THREE.Vector3.prototype = {
  542. constructor: THREE.Vector3,
  543. set: function ( x, y, z ) {
  544. this.x = x;
  545. this.y = y;
  546. this.z = z;
  547. return this;
  548. },
  549. setX: function ( x ) {
  550. this.x = x;
  551. return this;
  552. },
  553. setY: function ( y ) {
  554. this.y = y;
  555. return this;
  556. },
  557. setZ: function ( z ) {
  558. this.z = z;
  559. return this;
  560. },
  561. copy: function ( v ) {
  562. this.x = v.x;
  563. this.y = v.y;
  564. this.z = v.z;
  565. return this;
  566. },
  567. add: function ( a, b ) {
  568. this.x = a.x + b.x;
  569. this.y = a.y + b.y;
  570. this.z = a.z + b.z;
  571. return this;
  572. },
  573. addSelf: function ( v ) {
  574. this.x += v.x;
  575. this.y += v.y;
  576. this.z += v.z;
  577. return this;
  578. },
  579. addScalar: function ( s ) {
  580. this.x += s;
  581. this.y += s;
  582. this.z += s;
  583. return this;
  584. },
  585. sub: function ( a, b ) {
  586. this.x = a.x - b.x;
  587. this.y = a.y - b.y;
  588. this.z = a.z - b.z;
  589. return this;
  590. },
  591. subSelf: function ( v ) {
  592. this.x -= v.x;
  593. this.y -= v.y;
  594. this.z -= v.z;
  595. return this;
  596. },
  597. multiply: function ( a, b ) {
  598. this.x = a.x * b.x;
  599. this.y = a.y * b.y;
  600. this.z = a.z * b.z;
  601. return this;
  602. },
  603. multiplySelf: function ( v ) {
  604. this.x *= v.x;
  605. this.y *= v.y;
  606. this.z *= v.z;
  607. return this;
  608. },
  609. multiplyScalar: function ( s ) {
  610. this.x *= s;
  611. this.y *= s;
  612. this.z *= s;
  613. return this;
  614. },
  615. divideSelf: function ( v ) {
  616. this.x /= v.x;
  617. this.y /= v.y;
  618. this.z /= v.z;
  619. return this;
  620. },
  621. divideScalar: function ( s ) {
  622. if ( s ) {
  623. this.x /= s;
  624. this.y /= s;
  625. this.z /= s;
  626. } else {
  627. this.x = 0;
  628. this.y = 0;
  629. this.z = 0;
  630. }
  631. return this;
  632. },
  633. minSelf: function ( v ) {
  634. if ( this.x > v.x ) {
  635. this.x = v.x;
  636. }
  637. if ( this.y > v.y ) {
  638. this.y = v.y;
  639. }
  640. if ( this.z > v.z ) {
  641. this.z = v.z;
  642. }
  643. return this;
  644. },
  645. maxSelf: function ( v ) {
  646. if ( this.x < v.x ) {
  647. this.x = v.x;
  648. }
  649. if ( this.y < v.y ) {
  650. this.y = v.y;
  651. }
  652. if ( this.z < v.z ) {
  653. this.z = v.z;
  654. }
  655. return this;
  656. },
  657. clampSelf: function ( min, max ) {
  658. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  659. if ( this.x < min.x ) {
  660. this.x = min.x;
  661. } else if ( this.x > max.x ) {
  662. this.x = max.x;
  663. }
  664. if ( this.y < min.y ) {
  665. this.y = min.y;
  666. } else if ( this.y > max.y ) {
  667. this.y = max.y;
  668. }
  669. if ( this.z < min.z ) {
  670. this.z = min.z;
  671. } else if ( this.z > max.z ) {
  672. this.z = max.z;
  673. }
  674. return this;
  675. },
  676. negate: function() {
  677. return this.multiplyScalar( - 1 );
  678. },
  679. dot: function ( v ) {
  680. return this.x * v.x + this.y * v.y + this.z * v.z;
  681. },
  682. lengthSq: function () {
  683. return this.x * this.x + this.y * this.y + this.z * this.z;
  684. },
  685. length: function () {
  686. return Math.sqrt( this.lengthSq() );
  687. },
  688. lengthManhattan: function () {
  689. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  690. },
  691. normalize: function () {
  692. return this.divideScalar( this.length() );
  693. },
  694. setLength: function ( l ) {
  695. return this.normalize().multiplyScalar( l );
  696. },
  697. lerpSelf: function ( v, alpha ) {
  698. this.x += ( v.x - this.x ) * alpha;
  699. this.y += ( v.y - this.y ) * alpha;
  700. this.z += ( v.z - this.z ) * alpha;
  701. return this;
  702. },
  703. cross: function ( a, b ) {
  704. this.x = a.y * b.z - a.z * b.y;
  705. this.y = a.z * b.x - a.x * b.z;
  706. this.z = a.x * b.y - a.y * b.x;
  707. return this;
  708. },
  709. crossSelf: function ( v ) {
  710. var x = this.x, y = this.y, z = this.z;
  711. this.x = y * v.z - z * v.y;
  712. this.y = z * v.x - x * v.z;
  713. this.z = x * v.y - y * v.x;
  714. return this;
  715. },
  716. angleTo: function ( v ) {
  717. return Math.acos( this.dot( v ) / this.length() / v.length() );
  718. },
  719. distanceTo: function ( v ) {
  720. return Math.sqrt( this.distanceToSquared( v ) );
  721. },
  722. distanceToSquared: function ( v ) {
  723. var dx = this.x - v.x, dy = this.y - v.y, dz = this.z - v.z;
  724. return dx * dx + dy * dy + dz * dz;
  725. },
  726. getPositionFromMatrix: function ( m ) {
  727. this.x = m.elements[12];
  728. this.y = m.elements[13];
  729. this.z = m.elements[14];
  730. return this;
  731. },
  732. setEulerFromRotationMatrix: function ( m, order ) {
  733. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  734. // clamp, to handle numerical problems
  735. function clamp( x ) {
  736. return Math.min( Math.max( x, -1 ), 1 );
  737. }
  738. var te = m.elements;
  739. var m11 = te[0], m12 = te[4], m13 = te[8];
  740. var m21 = te[1], m22 = te[5], m23 = te[9];
  741. var m31 = te[2], m32 = te[6], m33 = te[10];
  742. if ( order === undefined || order === 'XYZ' ) {
  743. this.y = Math.asin( clamp( m13 ) );
  744. if ( Math.abs( m13 ) < 0.99999 ) {
  745. this.x = Math.atan2( - m23, m33 );
  746. this.z = Math.atan2( - m12, m11 );
  747. } else {
  748. this.x = Math.atan2( m32, m22 );
  749. this.z = 0;
  750. }
  751. } else if ( order === 'YXZ' ) {
  752. this.x = Math.asin( - clamp( m23 ) );
  753. if ( Math.abs( m23 ) < 0.99999 ) {
  754. this.y = Math.atan2( m13, m33 );
  755. this.z = Math.atan2( m21, m22 );
  756. } else {
  757. this.y = Math.atan2( - m31, m11 );
  758. this.z = 0;
  759. }
  760. } else if ( order === 'ZXY' ) {
  761. this.x = Math.asin( clamp( m32 ) );
  762. if ( Math.abs( m32 ) < 0.99999 ) {
  763. this.y = Math.atan2( - m31, m33 );
  764. this.z = Math.atan2( - m12, m22 );
  765. } else {
  766. this.y = 0;
  767. this.z = Math.atan2( m21, m11 );
  768. }
  769. } else if ( order === 'ZYX' ) {
  770. this.y = Math.asin( - clamp( m31 ) );
  771. if ( Math.abs( m31 ) < 0.99999 ) {
  772. this.x = Math.atan2( m32, m33 );
  773. this.z = Math.atan2( m21, m11 );
  774. } else {
  775. this.x = 0;
  776. this.z = Math.atan2( - m12, m22 );
  777. }
  778. } else if ( order === 'YZX' ) {
  779. this.z = Math.asin( clamp( m21 ) );
  780. if ( Math.abs( m21 ) < 0.99999 ) {
  781. this.x = Math.atan2( - m23, m22 );
  782. this.y = Math.atan2( - m31, m11 );
  783. } else {
  784. this.x = 0;
  785. this.y = Math.atan2( m13, m33 );
  786. }
  787. } else if ( order === 'XZY' ) {
  788. this.z = Math.asin( - clamp( m12 ) );
  789. if ( Math.abs( m12 ) < 0.99999 ) {
  790. this.x = Math.atan2( m32, m22 );
  791. this.y = Math.atan2( m13, m11 );
  792. } else {
  793. this.x = Math.atan2( - m23, m33 );
  794. this.y = 0;
  795. }
  796. }
  797. return this;
  798. },
  799. setEulerFromQuaternion: function ( q, order ) {
  800. // q is assumed to be normalized
  801. // clamp, to handle numerical problems
  802. function clamp( x ) {
  803. return Math.min( Math.max( x, -1 ), 1 );
  804. }
  805. // http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  806. var sqx = q.x * q.x;
  807. var sqy = q.y * q.y;
  808. var sqz = q.z * q.z;
  809. var sqw = q.w * q.w;
  810. if ( order === undefined || order === 'XYZ' ) {
  811. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( sqw - sqx - sqy + sqz ) );
  812. this.y = Math.asin( clamp( 2 * ( q.x * q.z + q.y * q.w ) ) );
  813. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw + sqx - sqy - sqz ) );
  814. } else if ( order === 'YXZ' ) {
  815. this.x = Math.asin( clamp( 2 * ( q.x * q.w - q.y * q.z ) ) );
  816. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw - sqx - sqy + sqz ) );
  817. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw - sqx + sqy - sqz ) );
  818. } else if ( order === 'ZXY' ) {
  819. this.x = Math.asin( clamp( 2 * ( q.x * q.w + q.y * q.z ) ) );
  820. this.y = Math.atan2( 2 * ( q.y * q.w - q.z * q.x ), ( sqw - sqx - sqy + sqz ) );
  821. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( sqw - sqx + sqy - sqz ) );
  822. } else if ( order === 'ZYX' ) {
  823. this.x = Math.atan2( 2 * ( q.x * q.w + q.z * q.y ), ( sqw - sqx - sqy + sqz ) );
  824. this.y = Math.asin( clamp( 2 * ( q.y * q.w - q.x * q.z ) ) );
  825. this.z = Math.atan2( 2 * ( q.x * q.y + q.z * q.w ), ( sqw + sqx - sqy - sqz ) );
  826. } else if ( order === 'YZX' ) {
  827. this.x = Math.atan2( 2 * ( q.x * q.w - q.z * q.y ), ( sqw - sqx + sqy - sqz ) );
  828. this.y = Math.atan2( 2 * ( q.y * q.w - q.x * q.z ), ( sqw + sqx - sqy - sqz ) );
  829. this.z = Math.asin( clamp( 2 * ( q.x * q.y + q.z * q.w ) ) );
  830. } else if ( order === 'XZY' ) {
  831. this.x = Math.atan2( 2 * ( q.x * q.w + q.y * q.z ), ( sqw - sqx + sqy - sqz ) );
  832. this.y = Math.atan2( 2 * ( q.x * q.z + q.y * q.w ), ( sqw + sqx - sqy - sqz ) );
  833. this.z = Math.asin( clamp( 2 * ( q.z * q.w - q.x * q.y ) ) );
  834. }
  835. return this;
  836. },
  837. getScaleFromMatrix: function ( m ) {
  838. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  839. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  840. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  841. this.x = sx;
  842. this.y = sy;
  843. this.z = sz;
  844. return this;
  845. },
  846. equals: function ( v ) {
  847. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  848. },
  849. clone: function () {
  850. return new THREE.Vector3( this.x, this.y, this.z );
  851. }
  852. };
  853. /**
  854. * @author supereggbert / http://www.paulbrunt.co.uk/
  855. * @author philogb / http://blog.thejit.org/
  856. * @author mikael emtinger / http://gomo.se/
  857. * @author egraether / http://egraether.com/
  858. * @author WestLangley / http://github.com/WestLangley
  859. */
  860. THREE.Vector4 = function ( x, y, z, w ) {
  861. this.x = x || 0;
  862. this.y = y || 0;
  863. this.z = z || 0;
  864. this.w = ( w !== undefined ) ? w : 1;
  865. };
  866. THREE.Vector4.prototype = {
  867. constructor: THREE.Vector4,
  868. set: function ( x, y, z, w ) {
  869. this.x = x;
  870. this.y = y;
  871. this.z = z;
  872. this.w = w;
  873. return this;
  874. },
  875. setX: function ( x ) {
  876. this.x = x;
  877. return this;
  878. },
  879. setY: function ( y ) {
  880. this.y = y;
  881. return this;
  882. },
  883. setZ: function ( z ) {
  884. this.z = z;
  885. return this;
  886. },
  887. setW: function ( w ) {
  888. this.w = w;
  889. return this;
  890. },
  891. copy: function ( v ) {
  892. this.x = v.x;
  893. this.y = v.y;
  894. this.z = v.z;
  895. this.w = ( v.w !== undefined ) ? v.w : 1;
  896. return this;
  897. },
  898. addScalar: function ( s ) {
  899. this.x += s;
  900. this.y += s;
  901. this.z += s;
  902. this.w += s;
  903. return this;
  904. },
  905. add: function ( a, b ) {
  906. this.x = a.x + b.x;
  907. this.y = a.y + b.y;
  908. this.z = a.z + b.z;
  909. this.w = a.w + b.w;
  910. return this;
  911. },
  912. addSelf: function ( v ) {
  913. this.x += v.x;
  914. this.y += v.y;
  915. this.z += v.z;
  916. this.w += v.w;
  917. return this;
  918. },
  919. sub: function ( a, b ) {
  920. this.x = a.x - b.x;
  921. this.y = a.y - b.y;
  922. this.z = a.z - b.z;
  923. this.w = a.w - b.w;
  924. return this;
  925. },
  926. subSelf: function ( v ) {
  927. this.x -= v.x;
  928. this.y -= v.y;
  929. this.z -= v.z;
  930. this.w -= v.w;
  931. return this;
  932. },
  933. multiplyScalar: function ( s ) {
  934. this.x *= s;
  935. this.y *= s;
  936. this.z *= s;
  937. this.w *= s;
  938. return this;
  939. },
  940. divideScalar: function ( s ) {
  941. if ( s ) {
  942. this.x /= s;
  943. this.y /= s;
  944. this.z /= s;
  945. this.w /= s;
  946. } else {
  947. this.x = 0;
  948. this.y = 0;
  949. this.z = 0;
  950. this.w = 1;
  951. }
  952. return this;
  953. },
  954. minSelf: function ( v ) {
  955. if ( this.x > v.x ) {
  956. this.x = v.x;
  957. }
  958. if ( this.y > v.y ) {
  959. this.y = v.y;
  960. }
  961. if ( this.z > v.z ) {
  962. this.z = v.z;
  963. }
  964. if ( this.w > v.w ) {
  965. this.w = v.w;
  966. }
  967. return this;
  968. },
  969. maxSelf: function ( v ) {
  970. if ( this.x < v.x ) {
  971. this.x = v.x;
  972. }
  973. if ( this.y < v.y ) {
  974. this.y = v.y;
  975. }
  976. if ( this.z < v.z ) {
  977. this.z = v.z;
  978. }
  979. if ( this.w < v.w ) {
  980. this.w = v.w;
  981. }
  982. return this;
  983. },
  984. clampSelf: function ( min, max ) {
  985. // This function assumes min < max, if this assumption isn't true it will not operate correctly
  986. if ( this.x < min.x ) {
  987. this.x = min.x;
  988. } else if ( this.x > max.x ) {
  989. this.x = max.x;
  990. }
  991. if ( this.y < min.y ) {
  992. this.y = min.y;
  993. } else if ( this.y > max.y ) {
  994. this.y = max.y;
  995. }
  996. if ( this.z < min.z ) {
  997. this.z = min.z;
  998. } else if ( this.z > max.z ) {
  999. this.z = max.z;
  1000. }
  1001. if ( this.w < min.w ) {
  1002. this.w = min.w;
  1003. } else if ( this.w > max.w ) {
  1004. this.w = max.w;
  1005. }
  1006. return this;
  1007. },
  1008. negate: function() {
  1009. return this.multiplyScalar( -1 );
  1010. },
  1011. dot: function ( v ) {
  1012. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  1013. },
  1014. lengthSq: function () {
  1015. return this.dot( this );
  1016. },
  1017. length: function () {
  1018. return Math.sqrt( this.lengthSq() );
  1019. },
  1020. lengthManhattan: function () {
  1021. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z ) + Math.abs( this.w );
  1022. },
  1023. normalize: function () {
  1024. return this.divideScalar( this.length() );
  1025. },
  1026. setLength: function ( l ) {
  1027. return this.normalize().multiplyScalar( l );
  1028. },
  1029. lerpSelf: function ( v, alpha ) {
  1030. this.x += ( v.x - this.x ) * alpha;
  1031. this.y += ( v.y - this.y ) * alpha;
  1032. this.z += ( v.z - this.z ) * alpha;
  1033. this.w += ( v.w - this.w ) * alpha;
  1034. return this;
  1035. },
  1036. equals: function ( v ) {
  1037. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) && ( v.w === this.w ) );
  1038. },
  1039. clone: function () {
  1040. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  1041. },
  1042. setAxisAngleFromQuaternion: function ( q ) {
  1043. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToAngle/index.htm
  1044. // q is assumed to be normalized
  1045. this.w = 2 * Math.acos( q.w );
  1046. var s = Math.sqrt( 1 - q.w * q.w );
  1047. if ( s < 0.0001 ) {
  1048. this.x = 1;
  1049. this.y = 0;
  1050. this.z = 0;
  1051. } else {
  1052. this.x = q.x / s;
  1053. this.y = q.y / s;
  1054. this.z = q.z / s;
  1055. }
  1056. return this;
  1057. },
  1058. setAxisAngleFromRotationMatrix: function ( m ) {
  1059. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToAngle/index.htm
  1060. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  1061. var angle, x, y, z, // variables for result
  1062. epsilon = 0.01, // margin to allow for rounding errors
  1063. epsilon2 = 0.1, // margin to distinguish between 0 and 180 degrees
  1064. te = m.elements,
  1065. m11 = te[0], m12 = te[4], m13 = te[8],
  1066. m21 = te[1], m22 = te[5], m23 = te[9],
  1067. m31 = te[2], m32 = te[6], m33 = te[10];
  1068. if ( ( Math.abs( m12 - m21 ) < epsilon )
  1069. && ( Math.abs( m13 - m31 ) < epsilon )
  1070. && ( Math.abs( m23 - m32 ) < epsilon ) ) {
  1071. // singularity found
  1072. // first check for identity matrix which must have +1 for all terms
  1073. // in leading diagonal and zero in other terms
  1074. if ( ( Math.abs( m12 + m21 ) < epsilon2 )
  1075. && ( Math.abs( m13 + m31 ) < epsilon2 )
  1076. && ( Math.abs( m23 + m32 ) < epsilon2 )
  1077. && ( Math.abs( m11 + m22 + m33 - 3 ) < epsilon2 ) ) {
  1078. // this singularity is identity matrix so angle = 0
  1079. this.set( 1, 0, 0, 0 );
  1080. return this; // zero angle, arbitrary axis
  1081. }
  1082. // otherwise this singularity is angle = 180
  1083. angle = Math.PI;
  1084. var xx = ( m11 + 1 ) / 2;
  1085. var yy = ( m22 + 1 ) / 2;
  1086. var zz = ( m33 + 1 ) / 2;
  1087. var xy = ( m12 + m21 ) / 4;
  1088. var xz = ( m13 + m31 ) / 4;
  1089. var yz = ( m23 + m32 ) / 4;
  1090. if ( ( xx > yy ) && ( xx > zz ) ) { // m11 is the largest diagonal term
  1091. if ( xx < epsilon ) {
  1092. x = 0;
  1093. y = 0.707106781;
  1094. z = 0.707106781;
  1095. } else {
  1096. x = Math.sqrt( xx );
  1097. y = xy / x;
  1098. z = xz / x;
  1099. }
  1100. } else if ( yy > zz ) { // m22 is the largest diagonal term
  1101. if ( yy < epsilon ) {
  1102. x = 0.707106781;
  1103. y = 0;
  1104. z = 0.707106781;
  1105. } else {
  1106. y = Math.sqrt( yy );
  1107. x = xy / y;
  1108. z = yz / y;
  1109. }
  1110. } else { // m33 is the largest diagonal term so base result on this
  1111. if ( zz < epsilon ) {
  1112. x = 0.707106781;
  1113. y = 0.707106781;
  1114. z = 0;
  1115. } else {
  1116. z = Math.sqrt( zz );
  1117. x = xz / z;
  1118. y = yz / z;
  1119. }
  1120. }
  1121. this.set( x, y, z, angle );
  1122. return this; // return 180 deg rotation
  1123. }
  1124. // as we have reached here there are no singularities so we can handle normally
  1125. var s = Math.sqrt( ( m32 - m23 ) * ( m32 - m23 )
  1126. + ( m13 - m31 ) * ( m13 - m31 )
  1127. + ( m21 - m12 ) * ( m21 - m12 ) ); // used to normalize
  1128. if ( Math.abs( s ) < 0.001 ) s = 1;
  1129. // prevent divide by zero, should not happen if matrix is orthogonal and should be
  1130. // caught by singularity test above, but I've left it in just in case
  1131. this.x = ( m32 - m23 ) / s;
  1132. this.y = ( m13 - m31 ) / s;
  1133. this.z = ( m21 - m12 ) / s;
  1134. this.w = Math.acos( ( m11 + m22 + m33 - 1 ) / 2 );
  1135. return this;
  1136. }
  1137. };
  1138. /**
  1139. * @author bhouston / http://exocortex.com
  1140. */
  1141. THREE.Box2 = function ( min, max ) {
  1142. if ( min === undefined && max === undefined ) {
  1143. this.min = new THREE.Vector2();
  1144. this.max = new THREE.Vector2();
  1145. this.makeEmpty();
  1146. } else {
  1147. this.min = min || new THREE.Vector2();
  1148. this.max = max || new THREE.Vector2().copy( this.min ); // This is done on purpose so you can make a box using a single point and then expand it.
  1149. }
  1150. };
  1151. THREE.Box2.prototype = {
  1152. constructor: THREE.Box2,
  1153. set: function ( min, max ) {
  1154. this.min = min;
  1155. this.max = max;
  1156. return this;
  1157. },
  1158. setFromPoints: function ( points ) {
  1159. if ( points.length > 0 ) {
  1160. var p = points[ 0 ];
  1161. this.min.copy( p );
  1162. this.max.copy( p );
  1163. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1164. p = points[ i ];
  1165. if ( p.x < this.min.x ) {
  1166. this.min.x = p.x;
  1167. } else if ( p.x > this.max.x ) {
  1168. this.max.x = p.x;
  1169. }
  1170. if ( p.y < this.min.y ) {
  1171. this.min.y = p.y;
  1172. } else if ( p.y > this.max.y ) {
  1173. this.max.y = p.y;
  1174. }
  1175. }
  1176. } else {
  1177. this.makeEmpty();
  1178. }
  1179. return this;
  1180. },
  1181. setFromCenterAndSize: function ( center, size ) {
  1182. var halfSize = THREE.Box2.__v1.copy( size ).multiplyScalar( 0.5 );
  1183. this.min.copy( center ).subSelf( halfSize );
  1184. this.max.copy( center ).addSelf( halfSize );
  1185. return this;
  1186. },
  1187. copy: function ( box ) {
  1188. this.min.copy( box.min );
  1189. this.max.copy( box.max );
  1190. return this;
  1191. },
  1192. makeEmpty: function () {
  1193. this.min.x = this.min.y = Infinity;
  1194. this.max.x = this.max.y = -Infinity;
  1195. return this;
  1196. },
  1197. empty: function () {
  1198. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1199. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y );
  1200. },
  1201. volume: function () {
  1202. return ( this.max.x - this.min.x ) * ( this.max.y - this.min.y );
  1203. },
  1204. center: function () {
  1205. return new THREE.Vector2().add( this.min, this.max ).multiplyScalar( 0.5 );
  1206. },
  1207. size: function () {
  1208. return new THREE.Vector2().sub( this.max, this.min );
  1209. },
  1210. expandByPoint: function ( point ) {
  1211. this.min.minSelf( point );
  1212. this.max.maxSelf( point );
  1213. return this;
  1214. },
  1215. expandByVector: function ( vector ) {
  1216. this.min.subSelf( vector );
  1217. this.max.addSelf( vector );
  1218. return this;
  1219. },
  1220. expandByScalar: function ( scalar ) {
  1221. this.min.addScalar( -scalar );
  1222. this.max.addScalar( scalar );
  1223. return this;
  1224. },
  1225. containsPoint: function ( point ) {
  1226. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1227. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) ) {
  1228. return true;
  1229. }
  1230. return false;
  1231. },
  1232. containsBox: function ( box ) {
  1233. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1234. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) ) {
  1235. return true;
  1236. }
  1237. return false;
  1238. },
  1239. getParameter: function ( point ) {
  1240. // This can potentially have a divide by zero if the box
  1241. // has a size dimension of 0.
  1242. return new THREE.Vector2(
  1243. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1244. ( point.y - this.min.y ) / ( this.max.y - this.min.y )
  1245. );
  1246. },
  1247. isIntersection: function ( box ) {
  1248. // using 6 splitting planes to rule out intersections.
  1249. if ( ( this.max.x < box.min.x ) || ( box.min.x > this.max.x ) ||
  1250. ( this.max.y < box.min.y ) || ( box.min.y > this.max.y ) ) {
  1251. return false;
  1252. }
  1253. return true;
  1254. },
  1255. clampPoint: function ( point ) {
  1256. return new THREE.Vector2().copy( point ).clampSelf( this.min, this.max );
  1257. },
  1258. distanceToPoint: function ( point ) {
  1259. var clampedPoint = THREE.Box2.__v1.copy( point ).clampSelf( this.min, this.max );
  1260. return clampedPoint.subSelf( point ).length();
  1261. },
  1262. intersect: function ( box ) {
  1263. this.min.maxSelf( box.min );
  1264. this.max.minSelf( box.max );
  1265. return this;
  1266. },
  1267. union: function ( box ) {
  1268. this.min.minSelf( box.min );
  1269. this.max.maxSelf( box.max );
  1270. return this;
  1271. },
  1272. translate: function ( offset ) {
  1273. this.min.addSelf( offset );
  1274. this.max.addSelf( offset );
  1275. return this;
  1276. },
  1277. scale: function ( factor ) {
  1278. var sizeDeltaHalf = this.size().multiplyScalar( ( 1 - factor ) * 0.5 );
  1279. this.expandByVector( sizeDeltaHalf );
  1280. return this;
  1281. },
  1282. equals: function ( box ) {
  1283. return box.min.equals( this.min ) && box.max.equals( this.max );
  1284. },
  1285. clone: function () {
  1286. return new THREE.Box2().copy( this );
  1287. }
  1288. };
  1289. THREE.Box2.__v1 = new THREE.Vector2();
  1290. /**
  1291. * @author bhouston / http://exocortex.com
  1292. */
  1293. THREE.Box3 = function ( min, max ) {
  1294. if ( min === undefined && max === undefined ) {
  1295. this.min = new THREE.Vector3();
  1296. this.max = new THREE.Vector3();
  1297. this.makeEmpty();
  1298. } else {
  1299. this.min = min || new THREE.Vector3();
  1300. this.max = max || new THREE.Vector3().copy( this.min ); // This is done on purpose so you can make a box using a single point and then expand it.
  1301. }
  1302. };
  1303. THREE.Box3.prototype = {
  1304. constructor: THREE.Box3,
  1305. set: function ( min, max ) {
  1306. this.min = min;
  1307. this.max = max;
  1308. return this;
  1309. },
  1310. setFromPoints: function ( points ) {
  1311. if ( points.length > 0 ) {
  1312. var p = points[ 0 ];
  1313. this.min.copy( p );
  1314. this.max.copy( p );
  1315. for ( var i = 1, il = points.length; i < il; i ++ ) {
  1316. p = points[ i ];
  1317. if ( p.x < this.min.x ) {
  1318. this.min.x = p.x;
  1319. } else if ( p.x > this.max.x ) {
  1320. this.max.x = p.x;
  1321. }
  1322. if ( p.y < this.min.y ) {
  1323. this.min.y = p.y;
  1324. } else if ( p.y > this.max.y ) {
  1325. this.max.y = p.y;
  1326. }
  1327. if ( p.z < this.min.z ) {
  1328. this.min.z = p.z;
  1329. } else if ( p.z > this.max.z ) {
  1330. this.max.z = p.z;
  1331. }
  1332. }
  1333. } else {
  1334. this.makeEmpty();
  1335. }
  1336. return this;
  1337. },
  1338. setFromCenterAndSize: function ( center, size ) {
  1339. var halfSize = THREE.Box3.__v1.copy( size ).multiplyScalar( 0.5 );
  1340. this.min.copy( center ).subSelf( halfSize );
  1341. this.max.copy( center ).addSelf( halfSize );
  1342. return this;
  1343. },
  1344. copy: function ( box ) {
  1345. this.min.copy( box.min );
  1346. this.max.copy( box.max );
  1347. return this;
  1348. },
  1349. makeEmpty: function () {
  1350. this.min.x = this.min.y = this.min.z = Infinity;
  1351. this.max.x = this.max.y = this.max.z = -Infinity;
  1352. return this;
  1353. },
  1354. empty: function () {
  1355. // this is a more robust check for empty than ( volume <= 0 ) because volume can get positive with two negative axes
  1356. return ( this.max.x < this.min.x ) || ( this.max.y < this.min.y ) || ( this.max.z < this.min.z );
  1357. },
  1358. volume: function () {
  1359. return ( this.max.x - this.min.x ) * ( this.max.y - this.min.y ) * ( this.max.z - this.min.z );
  1360. },
  1361. center: function () {
  1362. return new THREE.Vector3().add( this.min, this.max ).multiplyScalar( 0.5 );
  1363. },
  1364. size: function () {
  1365. return new THREE.Vector3().sub( this.max, this.min );
  1366. },
  1367. expandByPoint: function ( point ) {
  1368. this.min.minSelf( point );
  1369. this.max.maxSelf( point );
  1370. return this;
  1371. },
  1372. expandByVector: function ( vector ) {
  1373. this.min.subSelf( vector );
  1374. this.max.addSelf( vector );
  1375. return this;
  1376. },
  1377. expandByScalar: function ( scalar ) {
  1378. this.min.addScalar( -scalar );
  1379. this.max.addScalar( scalar );
  1380. return this;
  1381. },
  1382. containsPoint: function ( point ) {
  1383. if ( ( this.min.x <= point.x ) && ( point.x <= this.max.x ) &&
  1384. ( this.min.y <= point.y ) && ( point.y <= this.max.y ) &&
  1385. ( this.min.z <= point.z ) && ( point.z <= this.max.z ) ) {
  1386. return true;
  1387. }
  1388. return false;
  1389. },
  1390. containsBox: function ( box ) {
  1391. if ( ( this.min.x <= box.min.x ) && ( box.max.x <= this.max.x ) &&
  1392. ( this.min.y <= box.min.y ) && ( box.max.y <= this.max.y ) &&
  1393. ( this.min.z <= box.min.z ) && ( box.max.z <= this.max.z ) ) {
  1394. return true;
  1395. }
  1396. return false;
  1397. },
  1398. getParameter: function ( point ) {
  1399. // This can potentially have a divide by zero if the box
  1400. // has a size dimension of 0.
  1401. return new THREE.Vector3(
  1402. ( point.x - this.min.x ) / ( this.max.x - this.min.x ),
  1403. ( point.y - this.min.y ) / ( this.max.y - this.min.y ),
  1404. ( point.z - this.min.z ) / ( this.max.z - this.min.z )
  1405. );
  1406. },
  1407. isIntersection: function ( box ) {
  1408. // using 6 splitting planes to rule out intersections.
  1409. if ( ( this.max.x < box.min.x ) || ( box.min.x > this.max.x ) ||
  1410. ( this.max.y < box.min.y ) || ( box.min.y > this.max.y ) ||
  1411. ( this.max.z < box.min.z ) || ( box.min.z > this.max.z ) ) {
  1412. return false;
  1413. }
  1414. return true;
  1415. },
  1416. clampPoint: function ( point ) {
  1417. return new THREE.Vector3().copy( point ).clampSelf( this.min, this.max );
  1418. },
  1419. distanceToPoint: function ( point ) {
  1420. var clampedPoint = THREE.Box3.__v1.copy( point ).clampSelf( this.min, this.max );
  1421. return clampedPoint.subSelf( point ).length();
  1422. },
  1423. intersect: function ( box ) {
  1424. this.min.maxSelf( box.min );
  1425. this.max.minSelf( box.max );
  1426. return this;
  1427. },
  1428. union: function ( box ) {
  1429. this.min.minSelf( box.min );
  1430. this.max.maxSelf( box.max );
  1431. return this;
  1432. },
  1433. translate: function ( offset ) {
  1434. this.min.addSelf( offset );
  1435. this.max.addSelf( offset );
  1436. return this;
  1437. },
  1438. scale: function ( factor ) {
  1439. var sizeDeltaHalf = this.size().multiplyScalar( ( 1 - factor ) * 0.5 );
  1440. this.expandByVector( sizeDeltaHalf );
  1441. return this;
  1442. },
  1443. equals: function ( box ) {
  1444. return box.min.equals( this.min ) && box.max.equals( this.max );
  1445. },
  1446. clone: function () {
  1447. return new THREE.Box3().copy( this );
  1448. }
  1449. };
  1450. THREE.Box3.__v1 = new THREE.Vector3();
  1451. /**
  1452. * @author alteredq / http://alteredqualia.com/
  1453. * @author WestLangley / http://github.com/WestLangley
  1454. */
  1455. THREE.Matrix3 = function () {
  1456. this.elements = new Float32Array(9);
  1457. };
  1458. THREE.Matrix3.prototype = {
  1459. constructor: THREE.Matrix3,
  1460. multiplyVector3: function ( v ) {
  1461. var te = this.elements;
  1462. var vx = v.x, vy = v.y, vz = v.z;
  1463. v.x = te[0] * vx + te[3] * vy + te[6] * vz;
  1464. v.y = te[1] * vx + te[4] * vy + te[7] * vz;
  1465. v.z = te[2] * vx + te[5] * vy + te[8] * vz;
  1466. return v;
  1467. },
  1468. multiplyVector3Array: function ( a ) {
  1469. var tmp = THREE.Matrix3.__v1;
  1470. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1471. tmp.x = a[ i ];
  1472. tmp.y = a[ i + 1 ];
  1473. tmp.z = a[ i + 2 ];
  1474. this.multiplyVector3( tmp );
  1475. a[ i ] = tmp.x;
  1476. a[ i + 1 ] = tmp.y;
  1477. a[ i + 2 ] = tmp.z;
  1478. }
  1479. return a;
  1480. },
  1481. getInverse: function ( matrix ) {
  1482. // input: THREE.Matrix4
  1483. // ( based on http://code.google.com/p/webgl-mjs/ )
  1484. var me = matrix.elements;
  1485. var a11 = me[10] * me[5] - me[6] * me[9];
  1486. var a21 = - me[10] * me[1] + me[2] * me[9];
  1487. var a31 = me[6] * me[1] - me[2] * me[5];
  1488. var a12 = - me[10] * me[4] + me[6] * me[8];
  1489. var a22 = me[10] * me[0] - me[2] * me[8];
  1490. var a32 = - me[6] * me[0] + me[2] * me[4];
  1491. var a13 = me[9] * me[4] - me[5] * me[8];
  1492. var a23 = - me[9] * me[0] + me[1] * me[8];
  1493. var a33 = me[5] * me[0] - me[1] * me[4];
  1494. var det = me[0] * a11 + me[1] * a12 + me[2] * a13;
  1495. // no inverse
  1496. if ( det === 0 ) {
  1497. console.warn( "Matrix3.getInverse(): determinant == 0" );
  1498. }
  1499. var idet = 1.0 / det;
  1500. var m = this.elements;
  1501. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  1502. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  1503. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  1504. return this;
  1505. },
  1506. transpose: function () {
  1507. var tmp, m = this.elements;
  1508. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  1509. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  1510. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  1511. return this;
  1512. },
  1513. transposeIntoArray: function ( r ) {
  1514. var m = this.elements;
  1515. r[ 0 ] = m[ 0 ];
  1516. r[ 1 ] = m[ 3 ];
  1517. r[ 2 ] = m[ 6 ];
  1518. r[ 3 ] = m[ 1 ];
  1519. r[ 4 ] = m[ 4 ];
  1520. r[ 5 ] = m[ 7 ];
  1521. r[ 6 ] = m[ 2 ];
  1522. r[ 7 ] = m[ 5 ];
  1523. r[ 8 ] = m[ 8 ];
  1524. return this;
  1525. }
  1526. };
  1527. THREE.Matrix3.__v1 = new THREE.Vector3();/**
  1528. * @author mrdoob / http://mrdoob.com/
  1529. * @author supereggbert / http://www.paulbrunt.co.uk/
  1530. * @author philogb / http://blog.thejit.org/
  1531. * @author jordi_ros / http://plattsoft.com
  1532. * @author D1plo1d / http://github.com/D1plo1d
  1533. * @author alteredq / http://alteredqualia.com/
  1534. * @author mikael emtinger / http://gomo.se/
  1535. * @author timknip / http://www.floorplanner.com/
  1536. */
  1537. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1538. this.elements = new Float32Array( 16 );
  1539. this.set(
  1540. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  1541. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  1542. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  1543. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  1544. );
  1545. };
  1546. THREE.Matrix4.prototype = {
  1547. constructor: THREE.Matrix4,
  1548. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  1549. var te = this.elements;
  1550. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  1551. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1552. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1553. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1554. return this;
  1555. },
  1556. identity: function () {
  1557. this.set(
  1558. 1, 0, 0, 0,
  1559. 0, 1, 0, 0,
  1560. 0, 0, 1, 0,
  1561. 0, 0, 0, 1
  1562. );
  1563. return this;
  1564. },
  1565. copy: function ( m ) {
  1566. var me = m.elements;
  1567. this.set(
  1568. me[0], me[4], me[8], me[12],
  1569. me[1], me[5], me[9], me[13],
  1570. me[2], me[6], me[10], me[14],
  1571. me[3], me[7], me[11], me[15]
  1572. );
  1573. return this;
  1574. },
  1575. lookAt: function ( eye, target, up ) {
  1576. var te = this.elements;
  1577. var x = THREE.Matrix4.__v1;
  1578. var y = THREE.Matrix4.__v2;
  1579. var z = THREE.Matrix4.__v3;
  1580. z.sub( eye, target ).normalize();
  1581. if ( z.length() === 0 ) {
  1582. z.z = 1;
  1583. }
  1584. x.cross( up, z ).normalize();
  1585. if ( x.length() === 0 ) {
  1586. z.x += 0.0001;
  1587. x.cross( up, z ).normalize();
  1588. }
  1589. y.cross( z, x );
  1590. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1591. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1592. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1593. return this;
  1594. },
  1595. multiply: function ( a, b ) {
  1596. var ae = a.elements;
  1597. var be = b.elements;
  1598. var te = this.elements;
  1599. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1600. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1601. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1602. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1603. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1604. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1605. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1606. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1607. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1608. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1609. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1610. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1611. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1612. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1613. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1614. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1615. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1616. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1617. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1618. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1619. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1620. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1621. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1622. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1623. return this;
  1624. },
  1625. multiplySelf: function ( m ) {
  1626. return this.multiply( this, m );
  1627. },
  1628. multiplyToArray: function ( a, b, r ) {
  1629. var te = this.elements;
  1630. this.multiply( a, b );
  1631. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1632. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1633. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1634. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1635. return this;
  1636. },
  1637. multiplyScalar: function ( s ) {
  1638. var te = this.elements;
  1639. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1640. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1641. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1642. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1643. return this;
  1644. },
  1645. multiplyVector3: function ( v ) {
  1646. var te = this.elements;
  1647. var vx = v.x, vy = v.y, vz = v.z;
  1648. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1649. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1650. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1651. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1652. return v;
  1653. },
  1654. multiplyVector4: function ( v ) {
  1655. var te = this.elements;
  1656. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1657. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1658. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1659. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1660. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1661. return v;
  1662. },
  1663. multiplyVector3Array: function ( a ) {
  1664. var tmp = THREE.Matrix4.__v1;
  1665. for ( var i = 0, il = a.length; i < il; i += 3 ) {
  1666. tmp.x = a[ i ];
  1667. tmp.y = a[ i + 1 ];
  1668. tmp.z = a[ i + 2 ];
  1669. this.multiplyVector3( tmp );
  1670. a[ i ] = tmp.x;
  1671. a[ i + 1 ] = tmp.y;
  1672. a[ i + 2 ] = tmp.z;
  1673. }
  1674. return a;
  1675. },
  1676. rotateAxis: function ( v ) {
  1677. var te = this.elements;
  1678. var vx = v.x, vy = v.y, vz = v.z;
  1679. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1680. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1681. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1682. v.normalize();
  1683. return v;
  1684. },
  1685. crossVector: function ( a ) {
  1686. var te = this.elements;
  1687. var v = new THREE.Vector4();
  1688. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1689. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1690. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1691. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1692. return v;
  1693. },
  1694. determinant: function () {
  1695. var te = this.elements;
  1696. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1697. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1698. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1699. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1700. //TODO: make this more efficient
  1701. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1702. return (
  1703. n14 * n23 * n32 * n41-
  1704. n13 * n24 * n32 * n41-
  1705. n14 * n22 * n33 * n41+
  1706. n12 * n24 * n33 * n41+
  1707. n13 * n22 * n34 * n41-
  1708. n12 * n23 * n34 * n41-
  1709. n14 * n23 * n31 * n42+
  1710. n13 * n24 * n31 * n42+
  1711. n14 * n21 * n33 * n42-
  1712. n11 * n24 * n33 * n42-
  1713. n13 * n21 * n34 * n42+
  1714. n11 * n23 * n34 * n42+
  1715. n14 * n22 * n31 * n43-
  1716. n12 * n24 * n31 * n43-
  1717. n14 * n21 * n32 * n43+
  1718. n11 * n24 * n32 * n43+
  1719. n12 * n21 * n34 * n43-
  1720. n11 * n22 * n34 * n43-
  1721. n13 * n22 * n31 * n44+
  1722. n12 * n23 * n31 * n44+
  1723. n13 * n21 * n32 * n44-
  1724. n11 * n23 * n32 * n44-
  1725. n12 * n21 * n33 * n44+
  1726. n11 * n22 * n33 * n44
  1727. );
  1728. },
  1729. transpose: function () {
  1730. var te = this.elements;
  1731. var tmp;
  1732. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1733. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1734. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1735. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1736. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1737. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1738. return this;
  1739. },
  1740. flattenToArray: function ( flat ) {
  1741. var te = this.elements;
  1742. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1743. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1744. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1745. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1746. return flat;
  1747. },
  1748. flattenToArrayOffset: function( flat, offset ) {
  1749. var te = this.elements;
  1750. flat[ offset ] = te[0];
  1751. flat[ offset + 1 ] = te[1];
  1752. flat[ offset + 2 ] = te[2];
  1753. flat[ offset + 3 ] = te[3];
  1754. flat[ offset + 4 ] = te[4];
  1755. flat[ offset + 5 ] = te[5];
  1756. flat[ offset + 6 ] = te[6];
  1757. flat[ offset + 7 ] = te[7];
  1758. flat[ offset + 8 ] = te[8];
  1759. flat[ offset + 9 ] = te[9];
  1760. flat[ offset + 10 ] = te[10];
  1761. flat[ offset + 11 ] = te[11];
  1762. flat[ offset + 12 ] = te[12];
  1763. flat[ offset + 13 ] = te[13];
  1764. flat[ offset + 14 ] = te[14];
  1765. flat[ offset + 15 ] = te[15];
  1766. return flat;
  1767. },
  1768. getPosition: function () {
  1769. var te = this.elements;
  1770. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1771. },
  1772. setPosition: function ( v ) {
  1773. var te = this.elements;
  1774. te[12] = v.x;
  1775. te[13] = v.y;
  1776. te[14] = v.z;
  1777. return this;
  1778. },
  1779. getColumnX: function () {
  1780. var te = this.elements;
  1781. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1782. },
  1783. getColumnY: function () {
  1784. var te = this.elements;
  1785. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1786. },
  1787. getColumnZ: function() {
  1788. var te = this.elements;
  1789. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1790. },
  1791. getInverse: function ( m ) {
  1792. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1793. var te = this.elements;
  1794. var me = m.elements;
  1795. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1796. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1797. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1798. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1799. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1800. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1801. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1802. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1803. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1804. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1805. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1806. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1807. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1808. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1809. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1810. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1811. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1812. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1813. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1814. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1815. this.multiplyScalar( 1 / m.determinant() );
  1816. return this;
  1817. },
  1818. setRotationFromEuler: function ( v, order ) {
  1819. var te = this.elements;
  1820. var x = v.x, y = v.y, z = v.z;
  1821. var a = Math.cos( x ), b = Math.sin( x );
  1822. var c = Math.cos( y ), d = Math.sin( y );
  1823. var e = Math.cos( z ), f = Math.sin( z );
  1824. if ( order === undefined || order === 'XYZ' ) {
  1825. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1826. te[0] = c * e;
  1827. te[4] = - c * f;
  1828. te[8] = d;
  1829. te[1] = af + be * d;
  1830. te[5] = ae - bf * d;
  1831. te[9] = - b * c;
  1832. te[2] = bf - ae * d;
  1833. te[6] = be + af * d;
  1834. te[10] = a * c;
  1835. } else if ( order === 'YXZ' ) {
  1836. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1837. te[0] = ce + df * b;
  1838. te[4] = de * b - cf;
  1839. te[8] = a * d;
  1840. te[1] = a * f;
  1841. te[5] = a * e;
  1842. te[9] = - b;
  1843. te[2] = cf * b - de;
  1844. te[6] = df + ce * b;
  1845. te[10] = a * c;
  1846. } else if ( order === 'ZXY' ) {
  1847. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1848. te[0] = ce - df * b;
  1849. te[4] = - a * f;
  1850. te[8] = de + cf * b;
  1851. te[1] = cf + de * b;
  1852. te[5] = a * e;
  1853. te[9] = df - ce * b;
  1854. te[2] = - a * d;
  1855. te[6] = b;
  1856. te[10] = a * c;
  1857. } else if ( order === 'ZYX' ) {
  1858. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1859. te[0] = c * e;
  1860. te[4] = be * d - af;
  1861. te[8] = ae * d + bf;
  1862. te[1] = c * f;
  1863. te[5] = bf * d + ae;
  1864. te[9] = af * d - be;
  1865. te[2] = - d;
  1866. te[6] = b * c;
  1867. te[10] = a * c;
  1868. } else if ( order === 'YZX' ) {
  1869. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1870. te[0] = c * e;
  1871. te[4] = bd - ac * f;
  1872. te[8] = bc * f + ad;
  1873. te[1] = f;
  1874. te[5] = a * e;
  1875. te[9] = - b * e;
  1876. te[2] = - d * e;
  1877. te[6] = ad * f + bc;
  1878. te[10] = ac - bd * f;
  1879. } else if ( order === 'XZY' ) {
  1880. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1881. te[0] = c * e;
  1882. te[4] = - f;
  1883. te[8] = d * e;
  1884. te[1] = ac * f + bd;
  1885. te[5] = a * e;
  1886. te[9] = ad * f - bc;
  1887. te[2] = bc * f - ad;
  1888. te[6] = b * e;
  1889. te[10] = bd * f + ac;
  1890. }
  1891. return this;
  1892. },
  1893. setRotationFromQuaternion: function ( q ) {
  1894. var te = this.elements;
  1895. var x = q.x, y = q.y, z = q.z, w = q.w;
  1896. var x2 = x + x, y2 = y + y, z2 = z + z;
  1897. var xx = x * x2, xy = x * y2, xz = x * z2;
  1898. var yy = y * y2, yz = y * z2, zz = z * z2;
  1899. var wx = w * x2, wy = w * y2, wz = w * z2;
  1900. te[0] = 1 - ( yy + zz );
  1901. te[4] = xy - wz;
  1902. te[8] = xz + wy;
  1903. te[1] = xy + wz;
  1904. te[5] = 1 - ( xx + zz );
  1905. te[9] = yz - wx;
  1906. te[2] = xz - wy;
  1907. te[6] = yz + wx;
  1908. te[10] = 1 - ( xx + yy );
  1909. return this;
  1910. },
  1911. compose: function ( translation, rotation, scale ) {
  1912. var te = this.elements;
  1913. var mRotation = THREE.Matrix4.__m1;
  1914. var mScale = THREE.Matrix4.__m2;
  1915. mRotation.identity();
  1916. mRotation.setRotationFromQuaternion( rotation );
  1917. mScale.makeScale( scale.x, scale.y, scale.z );
  1918. this.multiply( mRotation, mScale );
  1919. te[12] = translation.x;
  1920. te[13] = translation.y;
  1921. te[14] = translation.z;
  1922. return this;
  1923. },
  1924. decompose: function ( translation, rotation, scale ) {
  1925. var te = this.elements;
  1926. // grab the axis vectors
  1927. var x = THREE.Matrix4.__v1;
  1928. var y = THREE.Matrix4.__v2;
  1929. var z = THREE.Matrix4.__v3;
  1930. x.set( te[0], te[1], te[2] );
  1931. y.set( te[4], te[5], te[6] );
  1932. z.set( te[8], te[9], te[10] );
  1933. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1934. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1935. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1936. scale.x = x.length();
  1937. scale.y = y.length();
  1938. scale.z = z.length();
  1939. translation.x = te[12];
  1940. translation.y = te[13];
  1941. translation.z = te[14];
  1942. // scale the rotation part
  1943. var matrix = THREE.Matrix4.__m1;
  1944. matrix.copy( this );
  1945. matrix.elements[0] /= scale.x;
  1946. matrix.elements[1] /= scale.x;
  1947. matrix.elements[2] /= scale.x;
  1948. matrix.elements[4] /= scale.y;
  1949. matrix.elements[5] /= scale.y;
  1950. matrix.elements[6] /= scale.y;
  1951. matrix.elements[8] /= scale.z;
  1952. matrix.elements[9] /= scale.z;
  1953. matrix.elements[10] /= scale.z;
  1954. rotation.setFromRotationMatrix( matrix );
  1955. return [ translation, rotation, scale ];
  1956. },
  1957. extractPosition: function ( m ) {
  1958. var te = this.elements;
  1959. var me = m.elements;
  1960. te[12] = me[12];
  1961. te[13] = me[13];
  1962. te[14] = me[14];
  1963. return this;
  1964. },
  1965. extractRotation: function ( m ) {
  1966. var te = this.elements;
  1967. var me = m.elements;
  1968. var vector = THREE.Matrix4.__v1;
  1969. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1970. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1971. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1972. te[0] = me[0] * scaleX;
  1973. te[1] = me[1] * scaleX;
  1974. te[2] = me[2] * scaleX;
  1975. te[4] = me[4] * scaleY;
  1976. te[5] = me[5] * scaleY;
  1977. te[6] = me[6] * scaleY;
  1978. te[8] = me[8] * scaleZ;
  1979. te[9] = me[9] * scaleZ;
  1980. te[10] = me[10] * scaleZ;
  1981. return this;
  1982. },
  1983. //
  1984. translate: function ( v ) {
  1985. var te = this.elements;
  1986. var x = v.x, y = v.y, z = v.z;
  1987. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1988. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1989. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1990. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1991. return this;
  1992. },
  1993. rotateX: function ( angle ) {
  1994. var te = this.elements;
  1995. var m12 = te[4];
  1996. var m22 = te[5];
  1997. var m32 = te[6];
  1998. var m42 = te[7];
  1999. var m13 = te[8];
  2000. var m23 = te[9];
  2001. var m33 = te[10];
  2002. var m43 = te[11];
  2003. var c = Math.cos( angle );
  2004. var s = Math.sin( angle );
  2005. te[4] = c * m12 + s * m13;
  2006. te[5] = c * m22 + s * m23;
  2007. te[6] = c * m32 + s * m33;
  2008. te[7] = c * m42 + s * m43;
  2009. te[8] = c * m13 - s * m12;
  2010. te[9] = c * m23 - s * m22;
  2011. te[10] = c * m33 - s * m32;
  2012. te[11] = c * m43 - s * m42;
  2013. return this;
  2014. },
  2015. rotateY: function ( angle ) {
  2016. var te = this.elements;
  2017. var m11 = te[0];
  2018. var m21 = te[1];
  2019. var m31 = te[2];
  2020. var m41 = te[3];
  2021. var m13 = te[8];
  2022. var m23 = te[9];
  2023. var m33 = te[10];
  2024. var m43 = te[11];
  2025. var c = Math.cos( angle );
  2026. var s = Math.sin( angle );
  2027. te[0] = c * m11 - s * m13;
  2028. te[1] = c * m21 - s * m23;
  2029. te[2] = c * m31 - s * m33;
  2030. te[3] = c * m41 - s * m43;
  2031. te[8] = c * m13 + s * m11;
  2032. te[9] = c * m23 + s * m21;
  2033. te[10] = c * m33 + s * m31;
  2034. te[11] = c * m43 + s * m41;
  2035. return this;
  2036. },
  2037. rotateZ: function ( angle ) {
  2038. var te = this.elements;
  2039. var m11 = te[0];
  2040. var m21 = te[1];
  2041. var m31 = te[2];
  2042. var m41 = te[3];
  2043. var m12 = te[4];
  2044. var m22 = te[5];
  2045. var m32 = te[6];
  2046. var m42 = te[7];
  2047. var c = Math.cos( angle );
  2048. var s = Math.sin( angle );
  2049. te[0] = c * m11 + s * m12;
  2050. te[1] = c * m21 + s * m22;
  2051. te[2] = c * m31 + s * m32;
  2052. te[3] = c * m41 + s * m42;
  2053. te[4] = c * m12 - s * m11;
  2054. te[5] = c * m22 - s * m21;
  2055. te[6] = c * m32 - s * m31;
  2056. te[7] = c * m42 - s * m41;
  2057. return this;
  2058. },
  2059. rotateByAxis: function ( axis, angle ) {
  2060. var te = this.elements;
  2061. // optimize by checking axis
  2062. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  2063. return this.rotateX( angle );
  2064. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  2065. return this.rotateY( angle );
  2066. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  2067. return this.rotateZ( angle );
  2068. }
  2069. var x = axis.x, y = axis.y, z = axis.z;
  2070. var n = Math.sqrt(x * x + y * y + z * z);
  2071. x /= n;
  2072. y /= n;
  2073. z /= n;
  2074. var xx = x * x, yy = y * y, zz = z * z;
  2075. var c = Math.cos( angle );
  2076. var s = Math.sin( angle );
  2077. var oneMinusCosine = 1 - c;
  2078. var xy = x * y * oneMinusCosine;
  2079. var xz = x * z * oneMinusCosine;
  2080. var yz = y * z * oneMinusCosine;
  2081. var xs = x * s;
  2082. var ys = y * s;
  2083. var zs = z * s;
  2084. var r11 = xx + (1 - xx) * c;
  2085. var r21 = xy + zs;
  2086. var r31 = xz - ys;
  2087. var r12 = xy - zs;
  2088. var r22 = yy + (1 - yy) * c;
  2089. var r32 = yz + xs;
  2090. var r13 = xz + ys;
  2091. var r23 = yz - xs;
  2092. var r33 = zz + (1 - zz) * c;
  2093. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  2094. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  2095. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  2096. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  2097. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  2098. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  2099. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  2100. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  2101. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  2102. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  2103. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  2104. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  2105. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  2106. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  2107. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  2108. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  2109. return this;
  2110. },
  2111. scale: function ( v ) {
  2112. var te = this.elements;
  2113. var x = v.x, y = v.y, z = v.z;
  2114. te[0] *= x; te[4] *= y; te[8] *= z;
  2115. te[1] *= x; te[5] *= y; te[9] *= z;
  2116. te[2] *= x; te[6] *= y; te[10] *= z;
  2117. te[3] *= x; te[7] *= y; te[11] *= z;
  2118. return this;
  2119. },
  2120. getMaxScaleOnAxis: function () {
  2121. var te = this.elements;
  2122. var scaleXSq = te[0] * te[0] + te[1] * te[1] + te[2] * te[2];
  2123. var scaleYSq = te[4] * te[4] + te[5] * te[5] + te[6] * te[6];
  2124. var scaleZSq = te[8] * te[8] + te[9] * te[9] + te[10] * te[10];
  2125. return Math.sqrt( Math.max( scaleXSq, Math.max( scaleYSq, scaleZSq ) ) );
  2126. },
  2127. //
  2128. makeTranslation: function ( x, y, z ) {
  2129. this.set(
  2130. 1, 0, 0, x,
  2131. 0, 1, 0, y,
  2132. 0, 0, 1, z,
  2133. 0, 0, 0, 1
  2134. );
  2135. return this;
  2136. },
  2137. makeRotationX: function ( theta ) {
  2138. var c = Math.cos( theta ), s = Math.sin( theta );
  2139. this.set(
  2140. 1, 0, 0, 0,
  2141. 0, c, -s, 0,
  2142. 0, s, c, 0,
  2143. 0, 0, 0, 1
  2144. );
  2145. return this;
  2146. },
  2147. makeRotationY: function ( theta ) {
  2148. var c = Math.cos( theta ), s = Math.sin( theta );
  2149. this.set(
  2150. c, 0, s, 0,
  2151. 0, 1, 0, 0,
  2152. -s, 0, c, 0,
  2153. 0, 0, 0, 1
  2154. );
  2155. return this;
  2156. },
  2157. makeRotationZ: function ( theta ) {
  2158. var c = Math.cos( theta ), s = Math.sin( theta );
  2159. this.set(
  2160. c, -s, 0, 0,
  2161. s, c, 0, 0,
  2162. 0, 0, 1, 0,
  2163. 0, 0, 0, 1
  2164. );
  2165. return this;
  2166. },
  2167. makeRotationAxis: function ( axis, angle ) {
  2168. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  2169. var c = Math.cos( angle );
  2170. var s = Math.sin( angle );
  2171. var t = 1 - c;
  2172. var x = axis.x, y = axis.y, z = axis.z;
  2173. var tx = t * x, ty = t * y;
  2174. this.set(
  2175. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  2176. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  2177. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  2178. 0, 0, 0, 1
  2179. );
  2180. return this;
  2181. },
  2182. makeScale: function ( x, y, z ) {
  2183. this.set(
  2184. x, 0, 0, 0,
  2185. 0, y, 0, 0,
  2186. 0, 0, z, 0,
  2187. 0, 0, 0, 1
  2188. );
  2189. return this;
  2190. },
  2191. makeFrustum: function ( left, right, bottom, top, near, far ) {
  2192. var te = this.elements;
  2193. var x = 2 * near / ( right - left );
  2194. var y = 2 * near / ( top - bottom );
  2195. var a = ( right + left ) / ( right - left );
  2196. var b = ( top + bottom ) / ( top - bottom );
  2197. var c = - ( far + near ) / ( far - near );
  2198. var d = - 2 * far * near / ( far - near );
  2199. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  2200. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  2201. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  2202. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  2203. return this;
  2204. },
  2205. makePerspective: function ( fov, aspect, near, far ) {
  2206. var ymax = near * Math.tan( fov * Math.PI / 360 );
  2207. var ymin = - ymax;
  2208. var xmin = ymin * aspect;
  2209. var xmax = ymax * aspect;
  2210. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  2211. },
  2212. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  2213. var te = this.elements;
  2214. var w = right - left;
  2215. var h = top - bottom;
  2216. var p = far - near;
  2217. var x = ( right + left ) / w;
  2218. var y = ( top + bottom ) / h;
  2219. var z = ( far + near ) / p;
  2220. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  2221. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  2222. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  2223. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  2224. return this;
  2225. },
  2226. clone: function () {
  2227. var te = this.elements;
  2228. return new THREE.Matrix4(
  2229. te[0], te[4], te[8], te[12],
  2230. te[1], te[5], te[9], te[13],
  2231. te[2], te[6], te[10], te[14],
  2232. te[3], te[7], te[11], te[15]
  2233. );
  2234. }
  2235. };
  2236. THREE.Matrix4.__v1 = new THREE.Vector3();
  2237. THREE.Matrix4.__v2 = new THREE.Vector3();
  2238. THREE.Matrix4.__v3 = new THREE.Vector3();
  2239. THREE.Matrix4.__m1 = new THREE.Matrix4();
  2240. THREE.Matrix4.__m2 = new THREE.Matrix4();
  2241. /**
  2242. * https://github.com/mrdoob/eventtarget.js/
  2243. */
  2244. THREE.EventTarget = function () {
  2245. var listeners = {};
  2246. this.addEventListener = function ( type, listener ) {
  2247. if ( listeners[ type ] === undefined ) {
  2248. listeners[ type ] = [];
  2249. }
  2250. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  2251. listeners[ type ].push( listener );
  2252. }
  2253. };
  2254. this.dispatchEvent = function ( event ) {
  2255. var listenerArray = listeners[ event.type ];
  2256. if ( listenerArray !== undefined ) {
  2257. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  2258. listenerArray[ i ]( event );
  2259. }
  2260. }
  2261. };
  2262. this.removeEventListener = function ( type, listener ) {
  2263. var index = listeners[ type ].indexOf( listener );
  2264. if ( index !== - 1 ) {
  2265. listeners[ type ].splice( index, 1 );
  2266. }
  2267. };
  2268. };
  2269. /**
  2270. * @author mrdoob / http://mrdoob.com/
  2271. * @author alteredq / http://alteredqualia.com/
  2272. * @author bhouston / http://exocortex.com
  2273. */
  2274. THREE.Frustum = function ( ) {
  2275. this.planes = [
  2276. new THREE.Plane(),
  2277. new THREE.Plane(),
  2278. new THREE.Plane(),
  2279. new THREE.Plane(),
  2280. new THREE.Plane(),
  2281. new THREE.Plane()
  2282. ];
  2283. };
  2284. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  2285. var planes = this.planes;
  2286. var me = m.elements;
  2287. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  2288. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  2289. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  2290. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  2291. planes[ 0 ].setComponents( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  2292. planes[ 1 ].setComponents( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  2293. planes[ 2 ].setComponents( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  2294. planes[ 3 ].setComponents( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  2295. planes[ 4 ].setComponents( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  2296. planes[ 5 ].setComponents( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  2297. for ( var i = 0; i < 6; i ++ ) {
  2298. planes[ i ].normalize();
  2299. }
  2300. };
  2301. THREE.Frustum.prototype.contains = function ( object ) {
  2302. var planes = this.planes;
  2303. var matrix = object.matrixWorld;
  2304. var matrixPosition = matrix.getPosition();
  2305. var radius = - object.geometry.boundingSphere.radius * matrix.getMaxScaleOnAxis();
  2306. var distance = 0.0;
  2307. for ( var i = 0; i < 6; i ++ ) {
  2308. distance = planes[ i ].distanceToPoint( matrixPosition );
  2309. if ( distance <= radius ) return false;
  2310. }
  2311. return true;
  2312. };
  2313. THREE.Frustum.__v1 = new THREE.Vector3();
  2314. /**
  2315. * @author bhouston / http://exocortex.com
  2316. */
  2317. THREE.Plane = function ( normal, constant ) {
  2318. this.normal = normal || new THREE.Vector3();
  2319. this.constant = constant || 0;
  2320. };
  2321. THREE.Plane.prototype = {
  2322. constructor: THREE.Plane,
  2323. set: function ( normal, constant ) {
  2324. this.normal = normal;
  2325. this.constant = constant;
  2326. return this;
  2327. },
  2328. setComponents: function ( x, y, z, w ) {
  2329. this.normal.set( x, y, z );
  2330. this.constant = w;
  2331. return this;
  2332. },
  2333. setFromNormalAndCoplanarPoint: function ( normal, point ) {
  2334. this.normal = normal;
  2335. this.constant = - point.dot( normal );
  2336. return this;
  2337. },
  2338. setFromCoplanarPoints: function ( a, b, c ) {
  2339. var normal = THREE.Plane.__v1.sub( b, a ).cross(
  2340. THREE.Plane.__v2.sub( c, a ) );
  2341. // Q: should an error be thrown if normal is zero (e.g. degenerate plane)?
  2342. this.setFromNormalAndCoplanarPoint( normal, a );
  2343. return this;
  2344. },
  2345. copy: function ( plane ) {
  2346. this.normal.copy( plane.normal );
  2347. this.constant = plane.constant;
  2348. return this;
  2349. },
  2350. flip: function () {
  2351. this.normal.negate();
  2352. return this;
  2353. },
  2354. normalize: function () {
  2355. // Note: will lead to a divide by zero if the plane is invalid.
  2356. var inverseNormalLength = 1.0 / this.normal.length();
  2357. this.normal.multiplyScalar( inverseNormalLength );
  2358. this.constant *= inverseNormalLength;
  2359. return this;
  2360. },
  2361. distanceToPoint: function ( point ) {
  2362. return this.normal.dot( point ) + this.constant;
  2363. },
  2364. distanceToSphere: function ( sphere ) {
  2365. return this.distanceToPoint( sphere.center ) - sphere.radius;
  2366. },
  2367. projectPoint: function ( point ) {
  2368. return this.orthoPoint( point ).subSelf( point ).negate();
  2369. },
  2370. orthoPoint: function ( point ) {
  2371. var perpendicularMagnitude = this.distanceToPoint( point );
  2372. return new THREE.Vector3().copy( this.normal ).multiplyScalar( perpendicularMagnitude );
  2373. },
  2374. intersectsLine: function ( startPoint, endPoint ) {
  2375. // Note: this tests if a line intersects the plane, not whether it (or its end-points) are coplanar with it.
  2376. var startSign = this.distanceToPoint( startPoint );
  2377. var endSign = this.distanceToPoint( endPoint );
  2378. return ( startSign < 0 && endSign > 0 ) || ( endSign < 0 && startSign > 0 );
  2379. },
  2380. coplanarPoint: function () {
  2381. return new THREE.Vector3().copy( this.normal ).multiplyScalar( - this.constant );
  2382. },
  2383. translate: function ( offset ) {
  2384. this.constant = - offset.dot( this.normal );
  2385. return this;
  2386. },
  2387. equals: function ( plane ) {
  2388. return plane.normal.equals( this.normal ) && ( plane.constant == this.constant );
  2389. },
  2390. clone: function () {
  2391. return new THREE.Plane().copy( this );
  2392. }
  2393. };
  2394. THREE.Plane.__v1 = new THREE.Vector3();
  2395. THREE.Plane.__v2 = new THREE.Vector3();
  2396. /**
  2397. * @author mrdoob / http://mrdoob.com/
  2398. */
  2399. ( function ( THREE ) {
  2400. THREE.Ray = function ( origin, direction, near, far ) {
  2401. this.origin = origin || new THREE.Vector3();
  2402. this.direction = direction || new THREE.Vector3();
  2403. this.near = near || 0;
  2404. this.far = far || Infinity;
  2405. };
  2406. var originCopy = new THREE.Vector3();
  2407. var localOriginCopy = new THREE.Vector3();
  2408. var localDirectionCopy = new THREE.Vector3();
  2409. var vector = new THREE.Vector3();
  2410. var normal = new THREE.Vector3();
  2411. var intersectPoint = new THREE.Vector3();
  2412. var inverseMatrix = new THREE.Matrix4();
  2413. var descSort = function ( a, b ) {
  2414. return a.distance - b.distance;
  2415. };
  2416. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  2417. var distanceFromIntersection = function ( origin, direction, position ) {
  2418. v0.sub( position, origin );
  2419. var dot = v0.dot( direction );
  2420. var intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  2421. var distance = position.distanceTo( intersect );
  2422. return distance;
  2423. };
  2424. // http://www.blackpawn.com/texts/pointinpoly/default.html
  2425. var pointInFace3 = function ( p, a, b, c ) {
  2426. v0.sub( c, a );
  2427. v1.sub( b, a );
  2428. v2.sub( p, a );
  2429. var dot00 = v0.dot( v0 );
  2430. var dot01 = v0.dot( v1 );
  2431. var dot02 = v0.dot( v2 );
  2432. var dot11 = v1.dot( v1 );
  2433. var dot12 = v1.dot( v2 );
  2434. var invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  2435. var u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  2436. var v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  2437. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  2438. };
  2439. var intersectObject = function ( object, ray, intersects ) {
  2440. if ( object instanceof THREE.Particle ) {
  2441. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  2442. if ( distance > object.scale.x ) {
  2443. return intersects;
  2444. }
  2445. intersects.push( {
  2446. distance: distance,
  2447. point: object.position,
  2448. face: null,
  2449. object: object
  2450. } );
  2451. } else if ( object instanceof THREE.Mesh ) {
  2452. // Checking boundingSphere
  2453. var scaledRadius = object.geometry.boundingSphere.radius * object.matrixWorld.getMaxScaleOnAxis();
  2454. // Checking distance to ray
  2455. var distance = distanceFromIntersection( ray.origin, ray.direction, object.matrixWorld.getPosition() );
  2456. if ( distance > scaledRadius) {
  2457. return intersects;
  2458. }
  2459. // Checking faces
  2460. var geometry = object.geometry;
  2461. var vertices = geometry.vertices;
  2462. var isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  2463. var objectMaterials = isFaceMaterial === true ? object.material.materials : null;
  2464. var side = object.material.side;
  2465. var a, b, c, d;
  2466. var precision = ray.precision;
  2467. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  2468. originCopy.copy( ray.origin );
  2469. inverseMatrix.getInverse( object.matrixWorld );
  2470. localOriginCopy.copy( originCopy );
  2471. inverseMatrix.multiplyVector3( localOriginCopy );
  2472. localDirectionCopy.copy( ray.direction );
  2473. inverseMatrix.rotateAxis( localDirectionCopy ).normalize();
  2474. for ( var f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  2475. var face = geometry.faces[ f ];
  2476. var material = isFaceMaterial === true ? objectMaterials[ face.materialIndex ] : object.material;
  2477. if ( material === undefined ) continue;
  2478. side = material.side;
  2479. vector.sub( face.centroid, localOriginCopy );
  2480. var normal = face.normal;
  2481. var dot = localDirectionCopy.dot( normal );
  2482. // bail if ray and plane are parallel
  2483. if ( Math.abs( dot ) < precision ) continue;
  2484. // calc distance to plane
  2485. var scalar = normal.dot( vector ) / dot;
  2486. // if negative distance, then plane is behind ray
  2487. if ( scalar < 0 ) continue;
  2488. if ( side === THREE.DoubleSide || ( side === THREE.FrontSide ? dot < 0 : dot > 0 ) ) {
  2489. intersectPoint.add( localOriginCopy, localDirectionCopy.multiplyScalar( scalar ) );
  2490. if ( face instanceof THREE.Face3 ) {
  2491. a = vertices[ face.a ];
  2492. b = vertices[ face.b ];
  2493. c = vertices[ face.c ];
  2494. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  2495. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  2496. distance = originCopy.distanceTo( point );
  2497. if ( distance < ray.near || distance > ray.far ) continue;
  2498. intersects.push( {
  2499. distance: distance,
  2500. point: point,
  2501. face: face,
  2502. faceIndex: f,
  2503. object: object
  2504. } );
  2505. }
  2506. } else if ( face instanceof THREE.Face4 ) {
  2507. a = vertices[ face.a ];
  2508. b = vertices[ face.b ];
  2509. c = vertices[ face.c ];
  2510. d = vertices[ face.d ];
  2511. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  2512. var point = object.matrixWorld.multiplyVector3( intersectPoint.clone() );
  2513. distance = originCopy.distanceTo( point );
  2514. if ( distance < ray.near || distance > ray.far ) continue;
  2515. intersects.push( {
  2516. distance: distance,
  2517. point: point,
  2518. face: face,
  2519. faceIndex: f,
  2520. object: object
  2521. } );
  2522. }
  2523. }
  2524. }
  2525. }
  2526. }
  2527. };
  2528. var intersectDescendants = function ( object, ray, intersects ) {
  2529. var descendants = object.getDescendants();
  2530. for ( var i = 0, l = descendants.length; i < l; i ++ ) {
  2531. intersectObject( descendants[ i ], ray, intersects );
  2532. }
  2533. };
  2534. //
  2535. THREE.Ray.prototype.precision = 0.0001;
  2536. THREE.Ray.prototype.set = function ( origin, direction ) {
  2537. this.origin = origin;
  2538. this.direction = direction;
  2539. };
  2540. THREE.Ray.prototype.intersectObject = function ( object, recursive ) {
  2541. var intersects = [];
  2542. if ( recursive === true ) {
  2543. intersectDescendants( object, this, intersects );
  2544. }
  2545. intersectObject( object, this, intersects );
  2546. intersects.sort( descSort );
  2547. return intersects;
  2548. };
  2549. THREE.Ray.prototype.intersectObjects = function ( objects, recursive ) {
  2550. var intersects = [];
  2551. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  2552. intersectObject( objects[ i ], this, intersects );
  2553. if ( recursive === true ) {
  2554. intersectDescendants( objects[ i ], this, intersects );
  2555. }
  2556. }
  2557. intersects.sort( descSort );
  2558. return intersects;
  2559. };
  2560. }( THREE ) );
  2561. /**
  2562. * @author mrdoob / http://mrdoob.com/
  2563. */
  2564. THREE.Rectangle = function () {
  2565. var _left = 0;
  2566. var _top = 0;
  2567. var _right = 0;
  2568. var _bottom = 0;
  2569. var _width = 0;
  2570. var _height = 0;
  2571. var _isEmpty = true;
  2572. function resize() {
  2573. _width = _right - _left;
  2574. _height = _bottom - _top;
  2575. }
  2576. this.getX = function () {
  2577. return _left;
  2578. };
  2579. this.getY = function () {
  2580. return _top;
  2581. };
  2582. this.getWidth = function () {
  2583. return _width;
  2584. };
  2585. this.getHeight = function () {
  2586. return _height;
  2587. };
  2588. this.getLeft = function() {
  2589. return _left;
  2590. };
  2591. this.getTop = function() {
  2592. return _top;
  2593. };
  2594. this.getRight = function() {
  2595. return _right;
  2596. };
  2597. this.getBottom = function() {
  2598. return _bottom;
  2599. };
  2600. this.set = function ( left, top, right, bottom ) {
  2601. _isEmpty = false;
  2602. _left = left; _top = top;
  2603. _right = right; _bottom = bottom;
  2604. resize();
  2605. };
  2606. this.addPoint = function ( x, y ) {
  2607. if ( _isEmpty === true ) {
  2608. _isEmpty = false;
  2609. _left = x; _top = y;
  2610. _right = x; _bottom = y;
  2611. resize();
  2612. } else {
  2613. _left = _left < x ? _left : x; // Math.min( _left, x );
  2614. _top = _top < y ? _top : y; // Math.min( _top, y );
  2615. _right = _right > x ? _right : x; // Math.max( _right, x );
  2616. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  2617. resize();
  2618. }
  2619. };
  2620. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  2621. if ( _isEmpty === true ) {
  2622. _isEmpty = false;
  2623. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  2624. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  2625. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  2626. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  2627. resize();
  2628. } else {
  2629. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  2630. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  2631. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  2632. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  2633. resize();
  2634. };
  2635. };
  2636. this.addRectangle = function ( r ) {
  2637. if ( _isEmpty === true ) {
  2638. _isEmpty = false;
  2639. _left = r.getLeft(); _top = r.getTop();
  2640. _right = r.getRight(); _bottom = r.getBottom();
  2641. resize();
  2642. } else {
  2643. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  2644. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  2645. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  2646. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  2647. resize();
  2648. }
  2649. };
  2650. this.inflate = function ( v ) {
  2651. _left -= v; _top -= v;
  2652. _right += v; _bottom += v;
  2653. resize();
  2654. };
  2655. this.minSelf = function ( r ) {
  2656. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  2657. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  2658. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  2659. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  2660. resize();
  2661. };
  2662. this.intersects = function ( r ) {
  2663. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  2664. if ( _right < r.getLeft() ) return false;
  2665. if ( _left > r.getRight() ) return false;
  2666. if ( _bottom < r.getTop() ) return false;
  2667. if ( _top > r.getBottom() ) return false;
  2668. return true;
  2669. };
  2670. this.empty = function () {
  2671. _isEmpty = true;
  2672. _left = 0; _top = 0;
  2673. _right = 0; _bottom = 0;
  2674. resize();
  2675. };
  2676. this.isEmpty = function () {
  2677. return _isEmpty;
  2678. };
  2679. };
  2680. /**
  2681. * @author bhouston / http://exocortex.com
  2682. */
  2683. THREE.Sphere = function ( center, radius ) {
  2684. this.center = center || new THREE.Vector3();
  2685. this.radius = radius || 0;
  2686. };
  2687. THREE.Sphere.prototype = {
  2688. constructor: THREE.Sphere,
  2689. set: function ( center, radius ) {
  2690. this.center = center;
  2691. this.radius = radius;
  2692. return this;
  2693. },
  2694. setFromCenterAndPoints: function ( center, points ) {
  2695. var maxRadiusSq = 0;
  2696. for ( var i = 0, il = points.length; i < il; i ++ ) {
  2697. var radiusSq = center.distanceToSquared( points[ i ] );
  2698. maxRadiusSq = Math.max( maxRadiusSq, radiusSq );
  2699. }
  2700. this.center = center;
  2701. this.radius = Math.sqrt( maxRadiusSq );
  2702. return this;
  2703. },
  2704. copy: function ( sphere ) {
  2705. this.center.copy( sphere.center );
  2706. this.radius = sphere.radius;
  2707. return this;
  2708. },
  2709. empty: function () {
  2710. return ( this.radius <= 0 );
  2711. },
  2712. volume: function () {
  2713. return Math.PI * 4 / 3 * ( this.radius * this.radius * this.radius );
  2714. },
  2715. containsPoint: function ( point ) {
  2716. return ( point.distanceToSquared( this.center ) <= ( this.radius * this.radius ) );
  2717. },
  2718. distanceToPoint: function ( point ) {
  2719. return ( point.distanceTo( this.center ) - this.radius );
  2720. },
  2721. clampPoint: function ( point ) {
  2722. var deltaLengthSq = this.center.distanceToSquared( point );
  2723. var result = new THREE.Vector3().copy( point );
  2724. if ( deltaLengthSq > ( this.radius * this.radius ) ) {
  2725. result.subSelf( this.center ).normalize();
  2726. result.multiplyScalar( this.radius ).addSelf( this.center );
  2727. }
  2728. return result;
  2729. },
  2730. bounds: function () {
  2731. var box = new THREE.Box3( this.center, this.center );
  2732. box.expandByScalar( this.radius );
  2733. return box;
  2734. },
  2735. translate: function ( offset ) {
  2736. this.center.addSelf( this.offset );
  2737. return this;
  2738. },
  2739. scale: function ( factor ) {
  2740. this.radius *= factor;
  2741. return this;
  2742. },
  2743. equals: function ( sphere ) {
  2744. return sphere.center.equals( this.center ) && ( sphere.radius === this.radius );
  2745. },
  2746. clone: function () {
  2747. return new THREE.Sphere3().copy( this );
  2748. }
  2749. };
  2750. /**
  2751. * @author alteredq / http://alteredqualia.com/
  2752. */
  2753. THREE.Math = {
  2754. // Clamp value to range <a, b>
  2755. clamp: function ( x, a, b ) {
  2756. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  2757. },
  2758. // Clamp value to range <a, inf)
  2759. clampBottom: function ( x, a ) {
  2760. return x < a ? a : x;
  2761. },
  2762. // Linear mapping from range <a1, a2> to range <b1, b2>
  2763. mapLinear: function ( x, a1, a2, b1, b2 ) {
  2764. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  2765. },
  2766. // Random float from <0, 1> with 16 bits of randomness
  2767. // (standard Math.random() creates repetitive patterns when applied over larger space)
  2768. random16: function () {
  2769. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  2770. },
  2771. // Random integer from <low, high> interval
  2772. randInt: function ( low, high ) {
  2773. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  2774. },
  2775. // Random float from <low, high> interval
  2776. randFloat: function ( low, high ) {
  2777. return low + Math.random() * ( high - low );
  2778. },
  2779. // Random float from <-range/2, range/2> interval
  2780. randFloatSpread: function ( range ) {
  2781. return range * ( 0.5 - Math.random() );
  2782. },
  2783. sign: function ( x ) {
  2784. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  2785. }
  2786. };
  2787. /**
  2788. * @author mrdoob / http://mrdoob.com/
  2789. * @author mikael emtinger / http://gomo.se/
  2790. * @author alteredq / http://alteredqualia.com/
  2791. */
  2792. THREE.Object3D = function () {
  2793. THREE.Object3DLibrary.push( this );
  2794. this.id = THREE.Object3DIdCount ++;
  2795. this.name = '';
  2796. this.properties = {};
  2797. this.parent = undefined;
  2798. this.children = [];
  2799. this.up = new THREE.Vector3( 0, 1, 0 );
  2800. this.position = new THREE.Vector3();
  2801. this.rotation = new THREE.Vector3();
  2802. this.eulerOrder = THREE.Object3D.defaultEulerOrder;
  2803. this.scale = new THREE.Vector3( 1, 1, 1 );
  2804. this.renderDepth = null;
  2805. this.rotationAutoUpdate = true;
  2806. this.matrix = new THREE.Matrix4();
  2807. this.matrixWorld = new THREE.Matrix4();
  2808. this.matrixRotationWorld = new THREE.Matrix4();
  2809. this.matrixAutoUpdate = true;
  2810. this.matrixWorldNeedsUpdate = true;
  2811. this.quaternion = new THREE.Quaternion();
  2812. this.useQuaternion = false;
  2813. this.boundRadius = 0.0;
  2814. this.boundRadiusScale = 1.0;
  2815. this.visible = true;
  2816. this.castShadow = false;
  2817. this.receiveShadow = false;
  2818. this.frustumCulled = true;
  2819. this._vector = new THREE.Vector3();
  2820. };
  2821. THREE.Object3D.prototype = {
  2822. constructor: THREE.Object3D,
  2823. applyMatrix: function ( matrix ) {
  2824. this.matrix.multiply( matrix, this.matrix );
  2825. this.scale.getScaleFromMatrix( this.matrix );
  2826. var mat = new THREE.Matrix4().extractRotation( this.matrix );
  2827. this.rotation.setEulerFromRotationMatrix( mat, this.eulerOrder );
  2828. this.position.getPositionFromMatrix( this.matrix );
  2829. },
  2830. translate: function ( distance, axis ) {
  2831. this.matrix.rotateAxis( axis );
  2832. this.position.addSelf( axis.multiplyScalar( distance ) );
  2833. },
  2834. translateX: function ( distance ) {
  2835. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  2836. },
  2837. translateY: function ( distance ) {
  2838. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  2839. },
  2840. translateZ: function ( distance ) {
  2841. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  2842. },
  2843. localToWorld: function ( vector ) {
  2844. return this.matrixWorld.multiplyVector3( vector );
  2845. },
  2846. worldToLocal: function ( vector ) {
  2847. return THREE.Object3D.__m1.getInverse( this.matrixWorld ).multiplyVector3( vector );
  2848. },
  2849. lookAt: function ( vector ) {
  2850. // TODO: Add hierarchy support.
  2851. this.matrix.lookAt( vector, this.position, this.up );
  2852. if ( this.rotationAutoUpdate ) {
  2853. if ( this.useQuaternion === false ) {
  2854. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  2855. } else {
  2856. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  2857. }
  2858. }
  2859. },
  2860. add: function ( object ) {
  2861. if ( object === this ) {
  2862. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  2863. return;
  2864. }
  2865. if ( object instanceof THREE.Object3D ) {
  2866. if ( object.parent !== undefined ) {
  2867. object.parent.remove( object );
  2868. }
  2869. object.parent = this;
  2870. this.children.push( object );
  2871. // add to scene
  2872. var scene = this;
  2873. while ( scene.parent !== undefined ) {
  2874. scene = scene.parent;
  2875. }
  2876. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2877. scene.__addObject( object );
  2878. }
  2879. }
  2880. },
  2881. remove: function ( object ) {
  2882. var index = this.children.indexOf( object );
  2883. if ( index !== - 1 ) {
  2884. object.parent = undefined;
  2885. this.children.splice( index, 1 );
  2886. // remove from scene
  2887. var scene = this;
  2888. while ( scene.parent !== undefined ) {
  2889. scene = scene.parent;
  2890. }
  2891. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  2892. scene.__removeObject( object );
  2893. }
  2894. }
  2895. },
  2896. traverse: function ( callback ) {
  2897. callback( this );
  2898. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2899. this.children[ i ].traverse( callback );
  2900. }
  2901. },
  2902. getChildByName: function ( name, recursive ) {
  2903. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2904. var child = this.children[ i ];
  2905. if ( child.name === name ) {
  2906. return child;
  2907. }
  2908. if ( recursive === true ) {
  2909. child = child.getChildByName( name, recursive );
  2910. if ( child !== undefined ) {
  2911. return child;
  2912. }
  2913. }
  2914. }
  2915. return undefined;
  2916. },
  2917. getDescendants: function ( array ) {
  2918. if ( array === undefined ) array = [];
  2919. Array.prototype.push.apply( array, this.children );
  2920. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2921. this.children[ i ].getDescendants( array );
  2922. }
  2923. return array;
  2924. },
  2925. updateMatrix: function () {
  2926. this.matrix.setPosition( this.position );
  2927. if ( this.useQuaternion === false ) {
  2928. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  2929. } else {
  2930. this.matrix.setRotationFromQuaternion( this.quaternion );
  2931. }
  2932. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  2933. this.matrix.scale( this.scale );
  2934. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  2935. }
  2936. this.matrixWorldNeedsUpdate = true;
  2937. },
  2938. updateMatrixWorld: function ( force ) {
  2939. if ( this.matrixAutoUpdate === true ) this.updateMatrix();
  2940. if ( this.matrixWorldNeedsUpdate === true || force === true ) {
  2941. if ( this.parent === undefined ) {
  2942. this.matrixWorld.copy( this.matrix );
  2943. } else {
  2944. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2945. }
  2946. this.matrixWorldNeedsUpdate = false;
  2947. force = true;
  2948. }
  2949. // update children
  2950. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2951. this.children[ i ].updateMatrixWorld( force );
  2952. }
  2953. },
  2954. clone: function ( object ) {
  2955. if ( object === undefined ) object = new THREE.Object3D();
  2956. object.name = this.name;
  2957. object.up.copy( this.up );
  2958. object.position.copy( this.position );
  2959. if ( object.rotation instanceof THREE.Vector3 ) object.rotation.copy( this.rotation ); // because of Sprite madness
  2960. object.eulerOrder = this.eulerOrder;
  2961. object.scale.copy( this.scale );
  2962. object.renderDepth = this.renderDepth;
  2963. object.rotationAutoUpdate = this.rotationAutoUpdate;
  2964. object.matrix.copy( this.matrix );
  2965. object.matrixWorld.copy( this.matrixWorld );
  2966. object.matrixRotationWorld.copy( this.matrixRotationWorld );
  2967. object.matrixAutoUpdate = this.matrixAutoUpdate;
  2968. object.matrixWorldNeedsUpdate = this.matrixWorldNeedsUpdate;
  2969. object.quaternion.copy( this.quaternion );
  2970. object.useQuaternion = this.useQuaternion;
  2971. object.boundRadius = this.boundRadius;
  2972. object.boundRadiusScale = this.boundRadiusScale;
  2973. object.visible = this.visible;
  2974. object.castShadow = this.castShadow;
  2975. object.receiveShadow = this.receiveShadow;
  2976. object.frustumCulled = this.frustumCulled;
  2977. for ( var i = 0; i < this.children.length; i ++ ) {
  2978. var child = this.children[ i ];
  2979. object.add( child.clone() );
  2980. }
  2981. return object;
  2982. },
  2983. deallocate: function () {
  2984. var index = THREE.Object3DLibrary.indexOf( this );
  2985. if ( index !== -1 ) THREE.Object3DLibrary.splice( index, 1 );
  2986. }
  2987. };
  2988. THREE.Object3D.__m1 = new THREE.Matrix4();
  2989. THREE.Object3D.defaultEulerOrder = 'XYZ',
  2990. THREE.Object3DIdCount = 0;
  2991. THREE.Object3DLibrary = [];
  2992. /**
  2993. * @author mrdoob / http://mrdoob.com/
  2994. * @author supereggbert / http://www.paulbrunt.co.uk/
  2995. * @author julianwa / https://github.com/julianwa
  2996. */
  2997. THREE.Projector = function() {
  2998. var _object, _objectCount, _objectPool = [], _objectPoolLength = 0,
  2999. _vertex, _vertexCount, _vertexPool = [], _vertexPoolLength = 0,
  3000. _face, _face3Count, _face3Pool = [], _face3PoolLength = 0,
  3001. _face4Count, _face4Pool = [], _face4PoolLength = 0,
  3002. _line, _lineCount, _linePool = [], _linePoolLength = 0,
  3003. _particle, _particleCount, _particlePool = [], _particlePoolLength = 0,
  3004. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  3005. _vector3 = new THREE.Vector3(),
  3006. _vector4 = new THREE.Vector4(),
  3007. _viewProjectionMatrix = new THREE.Matrix4(),
  3008. _modelViewProjectionMatrix = new THREE.Matrix4(),
  3009. _normalMatrix = new THREE.Matrix3(),
  3010. _frustum = new THREE.Frustum(),
  3011. _clippedVertex1PositionScreen = new THREE.Vector4(),
  3012. _clippedVertex2PositionScreen = new THREE.Vector4(),
  3013. _face3VertexNormals;
  3014. this.projectVector = function ( vector, camera ) {
  3015. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3016. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  3017. _viewProjectionMatrix.multiplyVector3( vector );
  3018. return vector;
  3019. };
  3020. this.unprojectVector = function ( vector, camera ) {
  3021. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  3022. _viewProjectionMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  3023. _viewProjectionMatrix.multiplyVector3( vector );
  3024. return vector;
  3025. };
  3026. this.pickingRay = function ( vector, camera ) {
  3027. var end, ray, t;
  3028. // set two vectors with opposing z values
  3029. vector.z = -1.0;
  3030. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  3031. this.unprojectVector( vector, camera );
  3032. this.unprojectVector( end, camera );
  3033. // find direction from vector to end
  3034. end.subSelf( vector ).normalize();
  3035. return new THREE.Ray( vector, end );
  3036. };
  3037. var projectGraph = function ( root, sortObjects ) {
  3038. _objectCount = 0;
  3039. _renderData.objects.length = 0;
  3040. _renderData.sprites.length = 0;
  3041. _renderData.lights.length = 0;
  3042. var projectObject = function ( parent ) {
  3043. for ( var c = 0, cl = parent.children.length; c < cl; c ++ ) {
  3044. var object = parent.children[ c ];
  3045. if ( object.visible === false ) continue;
  3046. if ( object instanceof THREE.Light ) {
  3047. _renderData.lights.push( object );
  3048. } else if ( object instanceof THREE.Mesh || object instanceof THREE.Line ) {
  3049. if ( object.frustumCulled === false || _frustum.contains( object ) === true ) {
  3050. _object = getNextObjectInPool();
  3051. _object.object = object;
  3052. if ( object.renderDepth !== null ) {
  3053. _object.z = object.renderDepth;
  3054. } else {
  3055. _vector3.copy( object.matrixWorld.getPosition() );
  3056. _viewProjectionMatrix.multiplyVector3( _vector3 );
  3057. _object.z = _vector3.z;
  3058. }
  3059. _renderData.objects.push( _object );
  3060. }
  3061. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  3062. _object = getNextObjectInPool();
  3063. _object.object = object;
  3064. // TODO: Find an elegant and performant solution and remove this dupe code.
  3065. if ( object.renderDepth !== null ) {
  3066. _object.z = object.renderDepth;
  3067. } else {
  3068. _vector3.copy( object.matrixWorld.getPosition() );
  3069. _viewProjectionMatrix.multiplyVector3( _vector3 );
  3070. _object.z = _vector3.z;
  3071. }
  3072. _renderData.sprites.push( _object );
  3073. } else {
  3074. _object = getNextObjectInPool();
  3075. _object.object = object;
  3076. if ( object.renderDepth !== null ) {
  3077. _object.z = object.renderDepth;
  3078. } else {
  3079. _vector3.copy( object.matrixWorld.getPosition() );
  3080. _viewProjectionMatrix.multiplyVector3( _vector3 );
  3081. _object.z = _vector3.z;
  3082. }
  3083. _renderData.objects.push( _object );
  3084. }
  3085. projectObject( object );
  3086. }
  3087. };
  3088. projectObject( root );
  3089. if ( sortObjects === true ) _renderData.objects.sort( painterSort );
  3090. return _renderData;
  3091. };
  3092. this.projectScene = function ( scene, camera, sortObjects, sortElements ) {
  3093. var near = camera.near, far = camera.far, visible = false,
  3094. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object, modelMatrix,
  3095. geometry, vertices, vertex, vertexPositionScreen,
  3096. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  3097. v1, v2, v3, v4, isFaceMaterial, objectMaterials, material, side;
  3098. _face3Count = 0;
  3099. _face4Count = 0;
  3100. _lineCount = 0;
  3101. _particleCount = 0;
  3102. _renderData.elements.length = 0;
  3103. scene.updateMatrixWorld();
  3104. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  3105. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  3106. _viewProjectionMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  3107. _frustum.setFromMatrix( _viewProjectionMatrix );
  3108. _renderData = projectGraph( scene, sortObjects );
  3109. for ( o = 0, ol = _renderData.objects.length; o < ol; o ++ ) {
  3110. object = _renderData.objects[ o ].object;
  3111. modelMatrix = object.matrixWorld;
  3112. _vertexCount = 0;
  3113. if ( object instanceof THREE.Mesh ) {
  3114. geometry = object.geometry;
  3115. vertices = geometry.vertices;
  3116. faces = geometry.faces;
  3117. faceVertexUvs = geometry.faceVertexUvs;
  3118. _normalMatrix.getInverse( modelMatrix );
  3119. _normalMatrix.transpose();
  3120. isFaceMaterial = object.material instanceof THREE.MeshFaceMaterial;
  3121. objectMaterials = isFaceMaterial === true ? object.material : null;
  3122. side = object.material.side;
  3123. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  3124. _vertex = getNextVertexInPool();
  3125. _vertex.positionWorld.copy( vertices[ v ] );
  3126. modelMatrix.multiplyVector3( _vertex.positionWorld );
  3127. _vertex.positionScreen.copy( _vertex.positionWorld );
  3128. _viewProjectionMatrix.multiplyVector4( _vertex.positionScreen );
  3129. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  3130. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  3131. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  3132. }
  3133. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  3134. face = faces[ f ];
  3135. material = isFaceMaterial === true ? objectMaterials.materials[ face.materialIndex ] : object.material;
  3136. if ( material === undefined ) continue;
  3137. side = material.side;
  3138. if ( face instanceof THREE.Face3 ) {
  3139. v1 = _vertexPool[ face.a ];
  3140. v2 = _vertexPool[ face.b ];
  3141. v3 = _vertexPool[ face.c ];
  3142. if ( v1.visible === true && v2.visible === true && v3.visible === true ) {
  3143. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3144. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  3145. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3146. _face = getNextFace3InPool();
  3147. _face.v1.copy( v1 );
  3148. _face.v2.copy( v2 );
  3149. _face.v3.copy( v3 );
  3150. } else {
  3151. continue;
  3152. }
  3153. } else {
  3154. continue;
  3155. }
  3156. } else if ( face instanceof THREE.Face4 ) {
  3157. v1 = _vertexPool[ face.a ];
  3158. v2 = _vertexPool[ face.b ];
  3159. v3 = _vertexPool[ face.c ];
  3160. v4 = _vertexPool[ face.d ];
  3161. if ( v1.visible === true && v2.visible === true && v3.visible === true && v4.visible === true ) {
  3162. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  3163. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  3164. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  3165. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  3166. if ( side === THREE.DoubleSide || visible === ( side === THREE.FrontSide ) ) {
  3167. _face = getNextFace4InPool();
  3168. _face.v1.copy( v1 );
  3169. _face.v2.copy( v2 );
  3170. _face.v3.copy( v3 );
  3171. _face.v4.copy( v4 );
  3172. } else {
  3173. continue;
  3174. }
  3175. } else {
  3176. continue;
  3177. }
  3178. }
  3179. _face.normalWorld.copy( face.normal );
  3180. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) _face.normalWorld.negate();
  3181. _normalMatrix.multiplyVector3( _face.normalWorld ).normalize();
  3182. _face.centroidWorld.copy( face.centroid );
  3183. modelMatrix.multiplyVector3( _face.centroidWorld );
  3184. _face.centroidScreen.copy( _face.centroidWorld );
  3185. _viewProjectionMatrix.multiplyVector3( _face.centroidScreen );
  3186. faceVertexNormals = face.vertexNormals;
  3187. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  3188. normal = _face.vertexNormalsWorld[ n ];
  3189. normal.copy( faceVertexNormals[ n ] );
  3190. if ( visible === false && ( side === THREE.BackSide || side === THREE.DoubleSide ) ) normal.negate();
  3191. _normalMatrix.multiplyVector3( normal ).normalize();
  3192. }
  3193. _face.vertexNormalsLength = faceVertexNormals.length;
  3194. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  3195. uvs = faceVertexUvs[ c ][ f ];
  3196. if ( uvs === undefined ) continue;
  3197. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  3198. _face.uvs[ c ][ u ] = uvs[ u ];
  3199. }
  3200. }
  3201. _face.color = face.color;
  3202. _face.material = material;
  3203. _face.z = _face.centroidScreen.z;
  3204. _renderData.elements.push( _face );
  3205. }
  3206. } else if ( object instanceof THREE.Line ) {
  3207. _modelViewProjectionMatrix.multiply( _viewProjectionMatrix, modelMatrix );
  3208. vertices = object.geometry.vertices;
  3209. v1 = getNextVertexInPool();
  3210. v1.positionScreen.copy( vertices[ 0 ] );
  3211. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  3212. // Handle LineStrip and LinePieces
  3213. var step = object.type === THREE.LinePieces ? 2 : 1;
  3214. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  3215. v1 = getNextVertexInPool();
  3216. v1.positionScreen.copy( vertices[ v ] );
  3217. _modelViewProjectionMatrix.multiplyVector4( v1.positionScreen );
  3218. if ( ( v + 1 ) % step > 0 ) continue;
  3219. v2 = _vertexPool[ _vertexCount - 2 ];
  3220. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  3221. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  3222. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) === true ) {
  3223. // Perform the perspective divide
  3224. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  3225. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  3226. _line = getNextLineInPool();
  3227. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  3228. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  3229. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  3230. _line.material = object.material;
  3231. _renderData.elements.push( _line );
  3232. }
  3233. }
  3234. }
  3235. }
  3236. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  3237. object = _renderData.sprites[ o ].object;
  3238. modelMatrix = object.matrixWorld;
  3239. if ( object instanceof THREE.Particle ) {
  3240. _vector4.set( modelMatrix.elements[12], modelMatrix.elements[13], modelMatrix.elements[14], 1 );
  3241. _viewProjectionMatrix.multiplyVector4( _vector4 );
  3242. _vector4.z /= _vector4.w;
  3243. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  3244. _particle = getNextParticleInPool();
  3245. _particle.object = object;
  3246. _particle.x = _vector4.x / _vector4.w;
  3247. _particle.y = _vector4.y / _vector4.w;
  3248. _particle.z = _vector4.z;
  3249. _particle.rotation = object.rotation.z;
  3250. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  3251. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  3252. _particle.material = object.material;
  3253. _renderData.elements.push( _particle );
  3254. }
  3255. }
  3256. }
  3257. if ( sortElements === true ) _renderData.elements.sort( painterSort );
  3258. return _renderData;
  3259. };
  3260. // Pools
  3261. function getNextObjectInPool() {
  3262. if ( _objectCount === _objectPoolLength ) {
  3263. var object = new THREE.RenderableObject();
  3264. _objectPool.push( object );
  3265. _objectPoolLength ++;
  3266. _objectCount ++;
  3267. return object;
  3268. }
  3269. return _objectPool[ _objectCount ++ ];
  3270. }
  3271. function getNextVertexInPool() {
  3272. if ( _vertexCount === _vertexPoolLength ) {
  3273. var vertex = new THREE.RenderableVertex();
  3274. _vertexPool.push( vertex );
  3275. _vertexPoolLength ++;
  3276. _vertexCount ++;
  3277. return vertex;
  3278. }
  3279. return _vertexPool[ _vertexCount ++ ];
  3280. }
  3281. function getNextFace3InPool() {
  3282. if ( _face3Count === _face3PoolLength ) {
  3283. var face = new THREE.RenderableFace3();
  3284. _face3Pool.push( face );
  3285. _face3PoolLength ++;
  3286. _face3Count ++;
  3287. return face;
  3288. }
  3289. return _face3Pool[ _face3Count ++ ];
  3290. }
  3291. function getNextFace4InPool() {
  3292. if ( _face4Count === _face4PoolLength ) {
  3293. var face = new THREE.RenderableFace4();
  3294. _face4Pool.push( face );
  3295. _face4PoolLength ++;
  3296. _face4Count ++;
  3297. return face;
  3298. }
  3299. return _face4Pool[ _face4Count ++ ];
  3300. }
  3301. function getNextLineInPool() {
  3302. if ( _lineCount === _linePoolLength ) {
  3303. var line = new THREE.RenderableLine();
  3304. _linePool.push( line );
  3305. _linePoolLength ++;
  3306. _lineCount ++
  3307. return line;
  3308. }
  3309. return _linePool[ _lineCount ++ ];
  3310. }
  3311. function getNextParticleInPool() {
  3312. if ( _particleCount === _particlePoolLength ) {
  3313. var particle = new THREE.RenderableParticle();
  3314. _particlePool.push( particle );
  3315. _particlePoolLength ++;
  3316. _particleCount ++
  3317. return particle;
  3318. }
  3319. return _particlePool[ _particleCount ++ ];
  3320. }
  3321. //
  3322. function painterSort( a, b ) {
  3323. return b.z - a.z;
  3324. }
  3325. function clipLine( s1, s2 ) {
  3326. var alpha1 = 0, alpha2 = 1,
  3327. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  3328. // Z = -1 and Z = +1, respectively.
  3329. bc1near = s1.z + s1.w,
  3330. bc2near = s2.z + s2.w,
  3331. bc1far = - s1.z + s1.w,
  3332. bc2far = - s2.z + s2.w;
  3333. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  3334. // Both vertices lie entirely within all clip planes.
  3335. return true;
  3336. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  3337. // Both vertices lie entirely outside one of the clip planes.
  3338. return false;
  3339. } else {
  3340. // The line segment spans at least one clip plane.
  3341. if ( bc1near < 0 ) {
  3342. // v1 lies outside the near plane, v2 inside
  3343. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  3344. } else if ( bc2near < 0 ) {
  3345. // v2 lies outside the near plane, v1 inside
  3346. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  3347. }
  3348. if ( bc1far < 0 ) {
  3349. // v1 lies outside the far plane, v2 inside
  3350. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  3351. } else if ( bc2far < 0 ) {
  3352. // v2 lies outside the far plane, v2 inside
  3353. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  3354. }
  3355. if ( alpha2 < alpha1 ) {
  3356. // The line segment spans two boundaries, but is outside both of them.
  3357. // (This can't happen when we're only clipping against just near/far but good
  3358. // to leave the check here for future usage if other clip planes are added.)
  3359. return false;
  3360. } else {
  3361. // Update the s1 and s2 vertices to match the clipped line segment.
  3362. s1.lerpSelf( s2, alpha1 );
  3363. s2.lerpSelf( s1, 1 - alpha2 );
  3364. return true;
  3365. }
  3366. }
  3367. }
  3368. };
  3369. /**
  3370. * @author mikael emtinger / http://gomo.se/
  3371. * @author alteredq / http://alteredqualia.com/
  3372. * @author WestLangley / http://github.com/WestLangley
  3373. */
  3374. THREE.Quaternion = function( x, y, z, w ) {
  3375. this.x = x || 0;
  3376. this.y = y || 0;
  3377. this.z = z || 0;
  3378. this.w = ( w !== undefined ) ? w : 1;
  3379. };
  3380. THREE.Quaternion.prototype = {
  3381. constructor: THREE.Quaternion,
  3382. set: function ( x, y, z, w ) {
  3383. this.x = x;
  3384. this.y = y;
  3385. this.z = z;
  3386. this.w = w;
  3387. return this;
  3388. },
  3389. copy: function ( q ) {
  3390. this.x = q.x;
  3391. this.y = q.y;
  3392. this.z = q.z;
  3393. this.w = q.w;
  3394. return this;
  3395. },
  3396. setFromEuler: function ( v, order ) {
  3397. // http://www.mathworks.com/matlabcentral/fileexchange/
  3398. // 20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/
  3399. // content/SpinCalc.m
  3400. var c1 = Math.cos( v.x / 2 );
  3401. var c2 = Math.cos( v.y / 2 );
  3402. var c3 = Math.cos( v.z / 2 );
  3403. var s1 = Math.sin( v.x / 2 );
  3404. var s2 = Math.sin( v.y / 2 );
  3405. var s3 = Math.sin( v.z / 2 );
  3406. if ( order === undefined || order === 'XYZ' ) {
  3407. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  3408. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  3409. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  3410. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  3411. } else if ( order === 'YXZ' ) {
  3412. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  3413. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  3414. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  3415. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  3416. } else if ( order === 'ZXY' ) {
  3417. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  3418. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  3419. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  3420. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  3421. } else if ( order === 'ZYX' ) {
  3422. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  3423. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  3424. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  3425. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  3426. } else if ( order === 'YZX' ) {
  3427. this.x = s1 * c2 * c3 + c1 * s2 * s3;
  3428. this.y = c1 * s2 * c3 + s1 * c2 * s3;
  3429. this.z = c1 * c2 * s3 - s1 * s2 * c3;
  3430. this.w = c1 * c2 * c3 - s1 * s2 * s3;
  3431. } else if ( order === 'XZY' ) {
  3432. this.x = s1 * c2 * c3 - c1 * s2 * s3;
  3433. this.y = c1 * s2 * c3 - s1 * c2 * s3;
  3434. this.z = c1 * c2 * s3 + s1 * s2 * c3;
  3435. this.w = c1 * c2 * c3 + s1 * s2 * s3;
  3436. }
  3437. return this;
  3438. },
  3439. setFromAxisAngle: function ( axis, angle ) {
  3440. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  3441. // axis have to be normalized
  3442. var halfAngle = angle / 2,
  3443. s = Math.sin( halfAngle );
  3444. this.x = axis.x * s;
  3445. this.y = axis.y * s;
  3446. this.z = axis.z * s;
  3447. this.w = Math.cos( halfAngle );
  3448. return this;
  3449. },
  3450. setFromRotationMatrix: function ( m ) {
  3451. // http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  3452. // assumes the upper 3x3 of m is a pure rotation matrix (i.e, unscaled)
  3453. var te = m.elements,
  3454. m11 = te[0], m12 = te[4], m13 = te[8],
  3455. m21 = te[1], m22 = te[5], m23 = te[9],
  3456. m31 = te[2], m32 = te[6], m33 = te[10],
  3457. trace = m11 + m22 + m33,
  3458. s;
  3459. if( trace > 0 ) {
  3460. s = 0.5 / Math.sqrt( trace + 1.0 );
  3461. this.w = 0.25 / s;
  3462. this.x = ( m32 - m23 ) * s;
  3463. this.y = ( m13 - m31 ) * s;
  3464. this.z = ( m21 - m12 ) * s;
  3465. } else if ( m11 > m22 && m11 > m33 ) {
  3466. s = 2.0 * Math.sqrt( 1.0 + m11 - m22 - m33 );
  3467. this.w = (m32 - m23 ) / s;
  3468. this.x = 0.25 * s;
  3469. this.y = (m12 + m21 ) / s;
  3470. this.z = (m13 + m31 ) / s;
  3471. } else if (m22 > m33) {
  3472. s = 2.0 * Math.sqrt( 1.0 + m22 - m11 - m33 );
  3473. this.w = (m13 - m31 ) / s;
  3474. this.x = (m12 + m21 ) / s;
  3475. this.y = 0.25 * s;
  3476. this.z = (m23 + m32 ) / s;
  3477. } else {
  3478. s = 2.0 * Math.sqrt( 1.0 + m33 - m11 - m22 );
  3479. this.w = ( m21 - m12 ) / s;
  3480. this.x = ( m13 + m31 ) / s;
  3481. this.y = ( m23 + m32 ) / s;
  3482. this.z = 0.25 * s;
  3483. }
  3484. return this;
  3485. },
  3486. inverse: function () {
  3487. this.conjugate().normalize();
  3488. return this;
  3489. },
  3490. conjugate: function () {
  3491. this.x *= -1;
  3492. this.y *= -1;
  3493. this.z *= -1;
  3494. return this;
  3495. },
  3496. length: function () {
  3497. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3498. },
  3499. normalize: function () {
  3500. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  3501. if ( l === 0 ) {
  3502. this.x = 0;
  3503. this.y = 0;
  3504. this.z = 0;
  3505. this.w = 1;
  3506. } else {
  3507. l = 1 / l;
  3508. this.x = this.x * l;
  3509. this.y = this.y * l;
  3510. this.z = this.z * l;
  3511. this.w = this.w * l;
  3512. }
  3513. return this;
  3514. },
  3515. multiply: function ( a, b ) {
  3516. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  3517. var qax = a.x, qay = a.y, qaz = a.z, qaw = a.w,
  3518. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  3519. this.x = qax * qbw + qay * qbz - qaz * qby + qaw * qbx;
  3520. this.y = -qax * qbz + qay * qbw + qaz * qbx + qaw * qby;
  3521. this.z = qax * qby - qay * qbx + qaz * qbw + qaw * qbz;
  3522. this.w = -qax * qbx - qay * qby - qaz * qbz + qaw * qbw;
  3523. return this;
  3524. },
  3525. multiplySelf: function ( b ) {
  3526. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  3527. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  3528. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  3529. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  3530. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  3531. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  3532. return this;
  3533. },
  3534. multiplyVector3: function ( vector, dest ) {
  3535. if ( !dest ) { dest = vector; }
  3536. var x = vector.x, y = vector.y, z = vector.z,
  3537. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  3538. // calculate quat * vector
  3539. var ix = qw * x + qy * z - qz * y,
  3540. iy = qw * y + qz * x - qx * z,
  3541. iz = qw * z + qx * y - qy * x,
  3542. iw = -qx * x - qy * y - qz * z;
  3543. // calculate result * inverse quat
  3544. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  3545. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  3546. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  3547. return dest;
  3548. },
  3549. slerpSelf: function ( qb, t ) {
  3550. var x = this.x, y = this.y, z = this.z, w = this.w;
  3551. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3552. var cosHalfTheta = w * qb.w + x * qb.x + y * qb.y + z * qb.z;
  3553. if ( cosHalfTheta < 0 ) {
  3554. this.w = -qb.w;
  3555. this.x = -qb.x;
  3556. this.y = -qb.y;
  3557. this.z = -qb.z;
  3558. cosHalfTheta = -cosHalfTheta;
  3559. } else {
  3560. this.copy( qb );
  3561. }
  3562. if ( cosHalfTheta >= 1.0 ) {
  3563. this.w = w;
  3564. this.x = x;
  3565. this.y = y;
  3566. this.z = z;
  3567. return this;
  3568. }
  3569. var halfTheta = Math.acos( cosHalfTheta );
  3570. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  3571. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  3572. this.w = 0.5 * ( w + this.w );
  3573. this.x = 0.5 * ( x + this.x );
  3574. this.y = 0.5 * ( y + this.y );
  3575. this.z = 0.5 * ( z + this.z );
  3576. return this;
  3577. }
  3578. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  3579. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3580. this.w = ( w * ratioA + this.w * ratioB );
  3581. this.x = ( x * ratioA + this.x * ratioB );
  3582. this.y = ( y * ratioA + this.y * ratioB );
  3583. this.z = ( z * ratioA + this.z * ratioB );
  3584. return this;
  3585. },
  3586. clone: function () {
  3587. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  3588. }
  3589. }
  3590. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  3591. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  3592. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  3593. if ( cosHalfTheta < 0 ) {
  3594. qm.w = -qb.w;
  3595. qm.x = -qb.x;
  3596. qm.y = -qb.y;
  3597. qm.z = -qb.z;
  3598. cosHalfTheta = -cosHalfTheta;
  3599. } else {
  3600. qm.copy( qb );
  3601. }
  3602. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  3603. qm.w = qa.w;
  3604. qm.x = qa.x;
  3605. qm.y = qa.y;
  3606. qm.z = qa.z;
  3607. return qm;
  3608. }
  3609. var halfTheta = Math.acos( cosHalfTheta );
  3610. var sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  3611. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  3612. qm.w = 0.5 * ( qa.w + qm.w );
  3613. qm.x = 0.5 * ( qa.x + qm.x );
  3614. qm.y = 0.5 * ( qa.y + qm.y );
  3615. qm.z = 0.5 * ( qa.z + qm.z );
  3616. return qm;
  3617. }
  3618. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta;
  3619. var ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  3620. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  3621. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  3622. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  3623. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  3624. return qm;
  3625. }
  3626. /**
  3627. * @author mrdoob / http://mrdoob.com/
  3628. */
  3629. THREE.Vertex = function ( v ) {
  3630. console.warn( 'THREE.Vertex has been DEPRECATED. Use THREE.Vector3 instead.')
  3631. return v;
  3632. };
  3633. /**
  3634. * @author mrdoob / http://mrdoob.com/
  3635. * @author alteredq / http://alteredqualia.com/
  3636. */
  3637. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  3638. this.a = a;
  3639. this.b = b;
  3640. this.c = c;
  3641. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3642. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3643. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3644. this.vertexColors = color instanceof Array ? color : [];
  3645. this.vertexTangents = [];
  3646. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3647. this.centroid = new THREE.Vector3();
  3648. };
  3649. THREE.Face3.prototype = {
  3650. constructor: THREE.Face3,
  3651. clone: function () {
  3652. var face = new THREE.Face3( this.a, this.b, this.c );
  3653. face.normal.copy( this.normal );
  3654. face.color.copy( this.color );
  3655. face.centroid.copy( this.centroid );
  3656. face.materialIndex = this.materialIndex;
  3657. var i, il;
  3658. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3659. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3660. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3661. return face;
  3662. }
  3663. };
  3664. /**
  3665. * @author mrdoob / http://mrdoob.com/
  3666. * @author alteredq / http://alteredqualia.com/
  3667. */
  3668. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  3669. this.a = a;
  3670. this.b = b;
  3671. this.c = c;
  3672. this.d = d;
  3673. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  3674. this.vertexNormals = normal instanceof Array ? normal : [ ];
  3675. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  3676. this.vertexColors = color instanceof Array ? color : [];
  3677. this.vertexTangents = [];
  3678. this.materialIndex = materialIndex !== undefined ? materialIndex : 0;
  3679. this.centroid = new THREE.Vector3();
  3680. };
  3681. THREE.Face4.prototype = {
  3682. constructor: THREE.Face4,
  3683. clone: function () {
  3684. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  3685. face.normal.copy( this.normal );
  3686. face.color.copy( this.color );
  3687. face.centroid.copy( this.centroid );
  3688. face.materialIndex = this.materialIndex;
  3689. var i, il;
  3690. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  3691. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  3692. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  3693. return face;
  3694. }
  3695. };
  3696. /**
  3697. * @author mrdoob / http://mrdoob.com/
  3698. */
  3699. THREE.UV = function ( u, v ) {
  3700. this.u = u || 0;
  3701. this.v = v || 0;
  3702. };
  3703. THREE.UV.prototype = {
  3704. constructor: THREE.UV,
  3705. set: function ( u, v ) {
  3706. this.u = u;
  3707. this.v = v;
  3708. return this;
  3709. },
  3710. copy: function ( uv ) {
  3711. this.u = uv.u;
  3712. this.v = uv.v;
  3713. return this;
  3714. },
  3715. lerpSelf: function ( uv, alpha ) {
  3716. this.u += ( uv.u - this.u ) * alpha;
  3717. this.v += ( uv.v - this.v ) * alpha;
  3718. return this;
  3719. },
  3720. clone: function () {
  3721. return new THREE.UV( this.u, this.v );
  3722. }
  3723. };
  3724. /**
  3725. * @author mrdoob / http://mrdoob.com/
  3726. * @author kile / http://kile.stravaganza.org/
  3727. * @author alteredq / http://alteredqualia.com/
  3728. * @author mikael emtinger / http://gomo.se/
  3729. * @author zz85 / http://www.lab4games.net/zz85/blog
  3730. * @author bhouston / http://exocortex.com
  3731. */
  3732. THREE.Geometry = function () {
  3733. THREE.GeometryLibrary.push( this );
  3734. this.id = THREE.GeometryIdCount ++;
  3735. this.name = '';
  3736. this.vertices = [];
  3737. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  3738. this.normals = []; // one-to-one vertex normals, used in Ribbon
  3739. this.faces = [];
  3740. this.faceUvs = [[]];
  3741. this.faceVertexUvs = [[]];
  3742. this.morphTargets = [];
  3743. this.morphColors = [];
  3744. this.morphNormals = [];
  3745. this.skinWeights = [];
  3746. this.skinIndices = [];
  3747. this.lineDistances = [];
  3748. this.boundingBox = null;
  3749. this.boundingSphere = null;
  3750. this.hasTangents = false;
  3751. this.dynamic = true; // the intermediate typed arrays will be deleted when set to false
  3752. // update flags
  3753. this.verticesNeedUpdate = false;
  3754. this.elementsNeedUpdate = false;
  3755. this.uvsNeedUpdate = false;
  3756. this.normalsNeedUpdate = false;
  3757. this.tangentsNeedUpdate = false;
  3758. this.colorsNeedUpdate = false;
  3759. this.lineDistancesNeedUpdate = false;
  3760. this.buffersNeedUpdate = false;
  3761. };
  3762. THREE.Geometry.prototype = {
  3763. constructor : THREE.Geometry,
  3764. applyMatrix: function ( matrix ) {
  3765. var normalMatrix = new THREE.Matrix3();
  3766. normalMatrix.getInverse( matrix ).transpose();
  3767. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  3768. var vertex = this.vertices[ i ];
  3769. matrix.multiplyVector3( vertex );
  3770. }
  3771. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  3772. var face = this.faces[ i ];
  3773. normalMatrix.multiplyVector3( face.normal ).normalize();
  3774. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  3775. normalMatrix.multiplyVector3( face.vertexNormals[ j ] ).normalize();
  3776. }
  3777. matrix.multiplyVector3( face.centroid );
  3778. }
  3779. },
  3780. computeCentroids: function () {
  3781. var f, fl, face;
  3782. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3783. face = this.faces[ f ];
  3784. face.centroid.set( 0, 0, 0 );
  3785. if ( face instanceof THREE.Face3 ) {
  3786. face.centroid.addSelf( this.vertices[ face.a ] );
  3787. face.centroid.addSelf( this.vertices[ face.b ] );
  3788. face.centroid.addSelf( this.vertices[ face.c ] );
  3789. face.centroid.divideScalar( 3 );
  3790. } else if ( face instanceof THREE.Face4 ) {
  3791. face.centroid.addSelf( this.vertices[ face.a ] );
  3792. face.centroid.addSelf( this.vertices[ face.b ] );
  3793. face.centroid.addSelf( this.vertices[ face.c ] );
  3794. face.centroid.addSelf( this.vertices[ face.d ] );
  3795. face.centroid.divideScalar( 4 );
  3796. }
  3797. }
  3798. },
  3799. computeFaceNormals: function () {
  3800. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  3801. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  3802. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3803. face = this.faces[ f ];
  3804. vA = this.vertices[ face.a ];
  3805. vB = this.vertices[ face.b ];
  3806. vC = this.vertices[ face.c ];
  3807. cb.sub( vC, vB );
  3808. ab.sub( vA, vB );
  3809. cb.crossSelf( ab );
  3810. cb.normalize();
  3811. face.normal.copy( cb );
  3812. }
  3813. },
  3814. computeVertexNormals: function ( areaWeighted ) {
  3815. var v, vl, f, fl, face, vertices;
  3816. // create internal buffers for reuse when calling this method repeatedly
  3817. // (otherwise memory allocation / deallocation every frame is big resource hog)
  3818. if ( this.__tmpVertices === undefined ) {
  3819. this.__tmpVertices = new Array( this.vertices.length );
  3820. vertices = this.__tmpVertices;
  3821. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3822. vertices[ v ] = new THREE.Vector3();
  3823. }
  3824. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3825. face = this.faces[ f ];
  3826. if ( face instanceof THREE.Face3 ) {
  3827. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3828. } else if ( face instanceof THREE.Face4 ) {
  3829. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  3830. }
  3831. }
  3832. } else {
  3833. vertices = this.__tmpVertices;
  3834. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3835. vertices[ v ].set( 0, 0, 0 );
  3836. }
  3837. }
  3838. if ( areaWeighted ) {
  3839. // vertex normals weighted by triangle areas
  3840. // http://www.iquilezles.org/www/articles/normals/normals.htm
  3841. var vA, vB, vC, vD;
  3842. var cb = new THREE.Vector3(), ab = new THREE.Vector3(),
  3843. db = new THREE.Vector3(), dc = new THREE.Vector3(), bc = new THREE.Vector3();
  3844. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3845. face = this.faces[ f ];
  3846. if ( face instanceof THREE.Face3 ) {
  3847. vA = this.vertices[ face.a ];
  3848. vB = this.vertices[ face.b ];
  3849. vC = this.vertices[ face.c ];
  3850. cb.sub( vC, vB );
  3851. ab.sub( vA, vB );
  3852. cb.crossSelf( ab );
  3853. vertices[ face.a ].addSelf( cb );
  3854. vertices[ face.b ].addSelf( cb );
  3855. vertices[ face.c ].addSelf( cb );
  3856. } else if ( face instanceof THREE.Face4 ) {
  3857. vA = this.vertices[ face.a ];
  3858. vB = this.vertices[ face.b ];
  3859. vC = this.vertices[ face.c ];
  3860. vD = this.vertices[ face.d ];
  3861. // abd
  3862. db.sub( vD, vB );
  3863. ab.sub( vA, vB );
  3864. db.crossSelf( ab );
  3865. vertices[ face.a ].addSelf( db );
  3866. vertices[ face.b ].addSelf( db );
  3867. vertices[ face.d ].addSelf( db );
  3868. // bcd
  3869. dc.sub( vD, vC );
  3870. bc.sub( vB, vC );
  3871. dc.crossSelf( bc );
  3872. vertices[ face.b ].addSelf( dc );
  3873. vertices[ face.c ].addSelf( dc );
  3874. vertices[ face.d ].addSelf( dc );
  3875. }
  3876. }
  3877. } else {
  3878. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3879. face = this.faces[ f ];
  3880. if ( face instanceof THREE.Face3 ) {
  3881. vertices[ face.a ].addSelf( face.normal );
  3882. vertices[ face.b ].addSelf( face.normal );
  3883. vertices[ face.c ].addSelf( face.normal );
  3884. } else if ( face instanceof THREE.Face4 ) {
  3885. vertices[ face.a ].addSelf( face.normal );
  3886. vertices[ face.b ].addSelf( face.normal );
  3887. vertices[ face.c ].addSelf( face.normal );
  3888. vertices[ face.d ].addSelf( face.normal );
  3889. }
  3890. }
  3891. }
  3892. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3893. vertices[ v ].normalize();
  3894. }
  3895. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3896. face = this.faces[ f ];
  3897. if ( face instanceof THREE.Face3 ) {
  3898. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3899. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3900. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3901. } else if ( face instanceof THREE.Face4 ) {
  3902. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  3903. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  3904. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  3905. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  3906. }
  3907. }
  3908. },
  3909. computeMorphNormals: function () {
  3910. var i, il, f, fl, face;
  3911. // save original normals
  3912. // - create temp variables on first access
  3913. // otherwise just copy (for faster repeated calls)
  3914. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3915. face = this.faces[ f ];
  3916. if ( ! face.__originalFaceNormal ) {
  3917. face.__originalFaceNormal = face.normal.clone();
  3918. } else {
  3919. face.__originalFaceNormal.copy( face.normal );
  3920. }
  3921. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  3922. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  3923. if ( ! face.__originalVertexNormals[ i ] ) {
  3924. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  3925. } else {
  3926. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  3927. }
  3928. }
  3929. }
  3930. // use temp geometry to compute face and vertex normals for each morph
  3931. var tmpGeo = new THREE.Geometry();
  3932. tmpGeo.faces = this.faces;
  3933. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  3934. // create on first access
  3935. if ( ! this.morphNormals[ i ] ) {
  3936. this.morphNormals[ i ] = {};
  3937. this.morphNormals[ i ].faceNormals = [];
  3938. this.morphNormals[ i ].vertexNormals = [];
  3939. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  3940. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  3941. var faceNormal, vertexNormals;
  3942. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3943. face = this.faces[ f ];
  3944. faceNormal = new THREE.Vector3();
  3945. if ( face instanceof THREE.Face3 ) {
  3946. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  3947. } else {
  3948. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  3949. }
  3950. dstNormalsFace.push( faceNormal );
  3951. dstNormalsVertex.push( vertexNormals );
  3952. }
  3953. }
  3954. var morphNormals = this.morphNormals[ i ];
  3955. // set vertices to morph target
  3956. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  3957. // compute morph normals
  3958. tmpGeo.computeFaceNormals();
  3959. tmpGeo.computeVertexNormals();
  3960. // store morph normals
  3961. var faceNormal, vertexNormals;
  3962. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3963. face = this.faces[ f ];
  3964. faceNormal = morphNormals.faceNormals[ f ];
  3965. vertexNormals = morphNormals.vertexNormals[ f ];
  3966. faceNormal.copy( face.normal );
  3967. if ( face instanceof THREE.Face3 ) {
  3968. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3969. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3970. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3971. } else {
  3972. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  3973. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  3974. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  3975. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  3976. }
  3977. }
  3978. }
  3979. // restore original normals
  3980. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  3981. face = this.faces[ f ];
  3982. face.normal = face.__originalFaceNormal;
  3983. face.vertexNormals = face.__originalVertexNormals;
  3984. }
  3985. },
  3986. computeTangents: function () {
  3987. // based on http://www.terathon.com/code/tangent.html
  3988. // tangents go to vertices
  3989. var f, fl, v, vl, i, il, vertexIndex,
  3990. face, uv, vA, vB, vC, uvA, uvB, uvC,
  3991. x1, x2, y1, y2, z1, z2,
  3992. s1, s2, t1, t2, r, t, test,
  3993. tan1 = [], tan2 = [],
  3994. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  3995. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  3996. n = new THREE.Vector3(), w;
  3997. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  3998. tan1[ v ] = new THREE.Vector3();
  3999. tan2[ v ] = new THREE.Vector3();
  4000. }
  4001. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  4002. vA = context.vertices[ a ];
  4003. vB = context.vertices[ b ];
  4004. vC = context.vertices[ c ];
  4005. uvA = uv[ ua ];
  4006. uvB = uv[ ub ];
  4007. uvC = uv[ uc ];
  4008. x1 = vB.x - vA.x;
  4009. x2 = vC.x - vA.x;
  4010. y1 = vB.y - vA.y;
  4011. y2 = vC.y - vA.y;
  4012. z1 = vB.z - vA.z;
  4013. z2 = vC.z - vA.z;
  4014. s1 = uvB.u - uvA.u;
  4015. s2 = uvC.u - uvA.u;
  4016. t1 = uvB.v - uvA.v;
  4017. t2 = uvC.v - uvA.v;
  4018. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4019. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  4020. ( t2 * y1 - t1 * y2 ) * r,
  4021. ( t2 * z1 - t1 * z2 ) * r );
  4022. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  4023. ( s1 * y2 - s2 * y1 ) * r,
  4024. ( s1 * z2 - s2 * z1 ) * r );
  4025. tan1[ a ].addSelf( sdir );
  4026. tan1[ b ].addSelf( sdir );
  4027. tan1[ c ].addSelf( sdir );
  4028. tan2[ a ].addSelf( tdir );
  4029. tan2[ b ].addSelf( tdir );
  4030. tan2[ c ].addSelf( tdir );
  4031. }
  4032. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4033. face = this.faces[ f ];
  4034. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  4035. if ( face instanceof THREE.Face3 ) {
  4036. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  4037. } else if ( face instanceof THREE.Face4 ) {
  4038. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  4039. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  4040. }
  4041. }
  4042. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  4043. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  4044. face = this.faces[ f ];
  4045. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  4046. n.copy( face.vertexNormals[ i ] );
  4047. vertexIndex = face[ faceIndex[ i ] ];
  4048. t = tan1[ vertexIndex ];
  4049. // Gram-Schmidt orthogonalize
  4050. tmp.copy( t );
  4051. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4052. // Calculate handedness
  4053. tmp2.cross( face.vertexNormals[ i ], t );
  4054. test = tmp2.dot( tan2[ vertexIndex ] );
  4055. w = (test < 0.0) ? -1.0 : 1.0;
  4056. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  4057. }
  4058. }
  4059. this.hasTangents = true;
  4060. },
  4061. computeLineDistances: function ( ) {
  4062. var d = 0;
  4063. var vertices = this.vertices;
  4064. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4065. if ( i > 0 ) {
  4066. d += vertices[ i ].distanceTo( vertices[ i - 1 ] );
  4067. }
  4068. this.lineDistances[ i ] = d;
  4069. }
  4070. },
  4071. computeBoundingBox: function () {
  4072. this.boundingBox = new THREE.Box3().setFromPoints( this.vertices );
  4073. },
  4074. computeBoundingSphere: function () {
  4075. this.boundingSphere = new THREE.Sphere().setFromCenterAndPoints( new THREE.Vector3(), this.vertices );
  4076. },
  4077. /*
  4078. * Checks for duplicate vertices with hashmap.
  4079. * Duplicated vertices are removed
  4080. * and faces' vertices are updated.
  4081. */
  4082. mergeVertices: function () {
  4083. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  4084. var unique = [], changes = [];
  4085. var v, key;
  4086. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  4087. var precision = Math.pow( 10, precisionPoints );
  4088. var i,il, face;
  4089. var abcd = 'abcd', o, k, j, jl, u;
  4090. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  4091. v = this.vertices[ i ];
  4092. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  4093. if ( verticesMap[ key ] === undefined ) {
  4094. verticesMap[ key ] = i;
  4095. unique.push( this.vertices[ i ] );
  4096. changes[ i ] = unique.length - 1;
  4097. } else {
  4098. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  4099. changes[ i ] = changes[ verticesMap[ key ] ];
  4100. }
  4101. };
  4102. // Start to patch face indices
  4103. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  4104. face = this.faces[ i ];
  4105. if ( face instanceof THREE.Face3 ) {
  4106. face.a = changes[ face.a ];
  4107. face.b = changes[ face.b ];
  4108. face.c = changes[ face.c ];
  4109. } else if ( face instanceof THREE.Face4 ) {
  4110. face.a = changes[ face.a ];
  4111. face.b = changes[ face.b ];
  4112. face.c = changes[ face.c ];
  4113. face.d = changes[ face.d ];
  4114. // check dups in (a, b, c, d) and convert to -> face3
  4115. o = [ face.a, face.b, face.c, face.d ];
  4116. for ( k = 3; k > 0; k -- ) {
  4117. if ( o.indexOf( face[ abcd[ k ] ] ) !== k ) {
  4118. // console.log('faces', face.a, face.b, face.c, face.d, 'dup at', k);
  4119. o.splice( k, 1 );
  4120. this.faces[ i ] = new THREE.Face3( o[0], o[1], o[2], face.normal, face.color, face.materialIndex );
  4121. for ( j = 0, jl = this.faceVertexUvs.length; j < jl; j ++ ) {
  4122. u = this.faceVertexUvs[ j ][ i ];
  4123. if ( u ) u.splice( k, 1 );
  4124. }
  4125. this.faces[ i ].vertexColors = face.vertexColors;
  4126. break;
  4127. }
  4128. }
  4129. }
  4130. }
  4131. // Use unique set of vertices
  4132. var diff = this.vertices.length - unique.length;
  4133. this.vertices = unique;
  4134. return diff;
  4135. },
  4136. clone: function () {
  4137. var geometry = new THREE.Geometry();
  4138. var vertices = this.vertices;
  4139. for ( var i = 0, il = vertices.length; i < il; i ++ ) {
  4140. geometry.vertices.push( vertices[ i ].clone() );
  4141. }
  4142. var faces = this.faces;
  4143. for ( var i = 0, il = faces.length; i < il; i ++ ) {
  4144. geometry.faces.push( faces[ i ].clone() );
  4145. }
  4146. var uvs = this.faceVertexUvs[ 0 ];
  4147. for ( var i = 0, il = uvs.length; i < il; i ++ ) {
  4148. var uv = uvs[ i ], uvCopy = [];
  4149. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  4150. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  4151. }
  4152. geometry.faceVertexUvs[ 0 ].push( uvCopy );
  4153. }
  4154. return geometry;
  4155. },
  4156. deallocate: function () {
  4157. var index = THREE.GeometryLibrary.indexOf( this );
  4158. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  4159. }
  4160. };
  4161. THREE.GeometryIdCount = 0;
  4162. THREE.GeometryLibrary = [];
  4163. /**
  4164. * @author alteredq / http://alteredqualia.com/
  4165. */
  4166. THREE.BufferGeometry = function () {
  4167. THREE.GeometryLibrary.push( this );
  4168. this.id = THREE.GeometryIdCount ++;
  4169. // attributes
  4170. this.attributes = {};
  4171. // attributes typed arrays are kept only if dynamic flag is set
  4172. this.dynamic = false;
  4173. // offsets for chunks when using indexed elements
  4174. this.offsets = [];
  4175. // boundings
  4176. this.boundingBox = null;
  4177. this.boundingSphere = null;
  4178. this.hasTangents = false;
  4179. // for compatibility
  4180. this.morphTargets = [];
  4181. };
  4182. THREE.BufferGeometry.prototype = {
  4183. constructor : THREE.BufferGeometry,
  4184. applyMatrix: function ( matrix ) {
  4185. var positionArray;
  4186. var normalArray;
  4187. if ( this.attributes[ "position" ] ) positionArray = this.attributes[ "position" ].array;
  4188. if ( this.attributes[ "normal" ] ) normalArray = this.attributes[ "normal" ].array;
  4189. if ( positionArray !== undefined ) {
  4190. matrix.multiplyVector3Array( positionArray );
  4191. this.verticesNeedUpdate = true;
  4192. }
  4193. if ( normalArray !== undefined ) {
  4194. var normalMatrix = new THREE.Matrix3();
  4195. normalMatrix.getInverse( matrix ).transpose();
  4196. normalMatrix.multiplyVector3Array( normalArray );
  4197. this.normalizeNormals();
  4198. this.normalsNeedUpdate = true;
  4199. }
  4200. },
  4201. computeBoundingBox: function () {
  4202. if ( ! this.boundingBox ) {
  4203. this.boundingBox = {
  4204. min: new THREE.Vector3( Infinity, Infinity, Infinity ),
  4205. max: new THREE.Vector3( -Infinity, -Infinity, -Infinity )
  4206. };
  4207. }
  4208. var positions = this.attributes[ "position" ].array;
  4209. if ( positions ) {
  4210. var bb = this.boundingBox;
  4211. var x, y, z;
  4212. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4213. x = positions[ i ];
  4214. y = positions[ i + 1 ];
  4215. z = positions[ i + 2 ];
  4216. // bounding box
  4217. if ( x < bb.min.x ) {
  4218. bb.min.x = x;
  4219. } else if ( x > bb.max.x ) {
  4220. bb.max.x = x;
  4221. }
  4222. if ( y < bb.min.y ) {
  4223. bb.min.y = y;
  4224. } else if ( y > bb.max.y ) {
  4225. bb.max.y = y;
  4226. }
  4227. if ( z < bb.min.z ) {
  4228. bb.min.z = z;
  4229. } else if ( z > bb.max.z ) {
  4230. bb.max.z = z;
  4231. }
  4232. }
  4233. }
  4234. if ( positions === undefined || positions.length === 0 ) {
  4235. this.boundingBox.min.set( 0, 0, 0 );
  4236. this.boundingBox.max.set( 0, 0, 0 );
  4237. }
  4238. },
  4239. computeBoundingSphere: function () {
  4240. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  4241. var positions = this.attributes[ "position" ].array;
  4242. if ( positions ) {
  4243. var radiusSq, maxRadiusSq = 0;
  4244. var x, y, z;
  4245. for ( var i = 0, il = positions.length; i < il; i += 3 ) {
  4246. x = positions[ i ];
  4247. y = positions[ i + 1 ];
  4248. z = positions[ i + 2 ];
  4249. radiusSq = x * x + y * y + z * z;
  4250. if ( radiusSq > maxRadiusSq ) maxRadiusSq = radiusSq;
  4251. }
  4252. this.boundingSphere.radius = Math.sqrt( maxRadiusSq );
  4253. }
  4254. },
  4255. computeVertexNormals: function () {
  4256. if ( this.attributes[ "position" ] ) {
  4257. var i, il;
  4258. var j, jl;
  4259. var nVertexElements = this.attributes[ "position" ].array.length;
  4260. if ( this.attributes[ "normal" ] === undefined ) {
  4261. this.attributes[ "normal" ] = {
  4262. itemSize: 3,
  4263. array: new Float32Array( nVertexElements ),
  4264. numItems: nVertexElements
  4265. };
  4266. } else {
  4267. // reset existing normals to zero
  4268. for ( i = 0, il = this.attributes[ "normal" ].array.length; i < il; i ++ ) {
  4269. this.attributes[ "normal" ].array[ i ] = 0;
  4270. }
  4271. }
  4272. var positions = this.attributes[ "position" ].array;
  4273. var normals = this.attributes[ "normal" ].array;
  4274. var vA, vB, vC, x, y, z,
  4275. pA = new THREE.Vector3(),
  4276. pB = new THREE.Vector3(),
  4277. pC = new THREE.Vector3(),
  4278. cb = new THREE.Vector3(),
  4279. ab = new THREE.Vector3();
  4280. // indexed elements
  4281. if ( this.attributes[ "index" ] ) {
  4282. var indices = this.attributes[ "index" ].array;
  4283. var offsets = this.offsets;
  4284. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4285. var start = offsets[ j ].start;
  4286. var count = offsets[ j ].count;
  4287. var index = offsets[ j ].index;
  4288. for ( i = start, il = start + count; i < il; i += 3 ) {
  4289. vA = index + indices[ i ];
  4290. vB = index + indices[ i + 1 ];
  4291. vC = index + indices[ i + 2 ];
  4292. x = positions[ vA * 3 ];
  4293. y = positions[ vA * 3 + 1 ];
  4294. z = positions[ vA * 3 + 2 ];
  4295. pA.set( x, y, z );
  4296. x = positions[ vB * 3 ];
  4297. y = positions[ vB * 3 + 1 ];
  4298. z = positions[ vB * 3 + 2 ];
  4299. pB.set( x, y, z );
  4300. x = positions[ vC * 3 ];
  4301. y = positions[ vC * 3 + 1 ];
  4302. z = positions[ vC * 3 + 2 ];
  4303. pC.set( x, y, z );
  4304. cb.sub( pC, pB );
  4305. ab.sub( pA, pB );
  4306. cb.crossSelf( ab );
  4307. normals[ vA * 3 ] += cb.x;
  4308. normals[ vA * 3 + 1 ] += cb.y;
  4309. normals[ vA * 3 + 2 ] += cb.z;
  4310. normals[ vB * 3 ] += cb.x;
  4311. normals[ vB * 3 + 1 ] += cb.y;
  4312. normals[ vB * 3 + 2 ] += cb.z;
  4313. normals[ vC * 3 ] += cb.x;
  4314. normals[ vC * 3 + 1 ] += cb.y;
  4315. normals[ vC * 3 + 2 ] += cb.z;
  4316. }
  4317. }
  4318. // non-indexed elements (unconnected triangle soup)
  4319. } else {
  4320. for ( i = 0, il = positions.length; i < il; i += 9 ) {
  4321. x = positions[ i ];
  4322. y = positions[ i + 1 ];
  4323. z = positions[ i + 2 ];
  4324. pA.set( x, y, z );
  4325. x = positions[ i + 3 ];
  4326. y = positions[ i + 4 ];
  4327. z = positions[ i + 5 ];
  4328. pB.set( x, y, z );
  4329. x = positions[ i + 6 ];
  4330. y = positions[ i + 7 ];
  4331. z = positions[ i + 8 ];
  4332. pC.set( x, y, z );
  4333. cb.sub( pC, pB );
  4334. ab.sub( pA, pB );
  4335. cb.crossSelf( ab );
  4336. normals[ i ] = cb.x;
  4337. normals[ i + 1 ] = cb.y;
  4338. normals[ i + 2 ] = cb.z;
  4339. normals[ i + 3 ] = cb.x;
  4340. normals[ i + 4 ] = cb.y;
  4341. normals[ i + 5 ] = cb.z;
  4342. normals[ i + 6 ] = cb.x;
  4343. normals[ i + 7 ] = cb.y;
  4344. normals[ i + 8 ] = cb.z;
  4345. }
  4346. }
  4347. this.normalizeNormals();
  4348. this.normalsNeedUpdate = true;
  4349. }
  4350. },
  4351. normalizeNormals: function () {
  4352. var normals = this.attributes[ "normal" ].array;
  4353. var x, y, z, n;
  4354. for ( var i = 0, il = normals.length; i < il; i += 3 ) {
  4355. x = normals[ i ];
  4356. y = normals[ i + 1 ];
  4357. z = normals[ i + 2 ];
  4358. n = 1.0 / Math.sqrt( x * x + y * y + z * z );
  4359. normals[ i ] *= n;
  4360. normals[ i + 1 ] *= n;
  4361. normals[ i + 2 ] *= n;
  4362. }
  4363. },
  4364. computeTangents: function () {
  4365. // based on http://www.terathon.com/code/tangent.html
  4366. // (per vertex tangents)
  4367. if ( this.attributes[ "index" ] === undefined ||
  4368. this.attributes[ "position" ] === undefined ||
  4369. this.attributes[ "normal" ] === undefined ||
  4370. this.attributes[ "uv" ] === undefined ) {
  4371. console.warn( "Missing required attributes (index, position, normal or uv) in BufferGeometry.computeTangents()" );
  4372. return;
  4373. }
  4374. var indices = this.attributes[ "index" ].array;
  4375. var positions = this.attributes[ "position" ].array;
  4376. var normals = this.attributes[ "normal" ].array;
  4377. var uvs = this.attributes[ "uv" ].array;
  4378. var nVertices = positions.length / 3;
  4379. if ( this.attributes[ "tangent" ] === undefined ) {
  4380. var nTangentElements = 4 * nVertices;
  4381. this.attributes[ "tangent" ] = {
  4382. itemSize: 4,
  4383. array: new Float32Array( nTangentElements ),
  4384. numItems: nTangentElements
  4385. };
  4386. }
  4387. var tangents = this.attributes[ "tangent" ].array;
  4388. var tan1 = [], tan2 = [];
  4389. for ( var k = 0; k < nVertices; k ++ ) {
  4390. tan1[ k ] = new THREE.Vector3();
  4391. tan2[ k ] = new THREE.Vector3();
  4392. }
  4393. var xA, yA, zA,
  4394. xB, yB, zB,
  4395. xC, yC, zC,
  4396. uA, vA,
  4397. uB, vB,
  4398. uC, vC,
  4399. x1, x2, y1, y2, z1, z2,
  4400. s1, s2, t1, t2, r;
  4401. var sdir = new THREE.Vector3(), tdir = new THREE.Vector3();
  4402. function handleTriangle( a, b, c ) {
  4403. xA = positions[ a * 3 ];
  4404. yA = positions[ a * 3 + 1 ];
  4405. zA = positions[ a * 3 + 2 ];
  4406. xB = positions[ b * 3 ];
  4407. yB = positions[ b * 3 + 1 ];
  4408. zB = positions[ b * 3 + 2 ];
  4409. xC = positions[ c * 3 ];
  4410. yC = positions[ c * 3 + 1 ];
  4411. zC = positions[ c * 3 + 2 ];
  4412. uA = uvs[ a * 2 ];
  4413. vA = uvs[ a * 2 + 1 ];
  4414. uB = uvs[ b * 2 ];
  4415. vB = uvs[ b * 2 + 1 ];
  4416. uC = uvs[ c * 2 ];
  4417. vC = uvs[ c * 2 + 1 ];
  4418. x1 = xB - xA;
  4419. x2 = xC - xA;
  4420. y1 = yB - yA;
  4421. y2 = yC - yA;
  4422. z1 = zB - zA;
  4423. z2 = zC - zA;
  4424. s1 = uB - uA;
  4425. s2 = uC - uA;
  4426. t1 = vB - vA;
  4427. t2 = vC - vA;
  4428. r = 1.0 / ( s1 * t2 - s2 * t1 );
  4429. sdir.set(
  4430. ( t2 * x1 - t1 * x2 ) * r,
  4431. ( t2 * y1 - t1 * y2 ) * r,
  4432. ( t2 * z1 - t1 * z2 ) * r
  4433. );
  4434. tdir.set(
  4435. ( s1 * x2 - s2 * x1 ) * r,
  4436. ( s1 * y2 - s2 * y1 ) * r,
  4437. ( s1 * z2 - s2 * z1 ) * r
  4438. );
  4439. tan1[ a ].addSelf( sdir );
  4440. tan1[ b ].addSelf( sdir );
  4441. tan1[ c ].addSelf( sdir );
  4442. tan2[ a ].addSelf( tdir );
  4443. tan2[ b ].addSelf( tdir );
  4444. tan2[ c ].addSelf( tdir );
  4445. }
  4446. var i, il;
  4447. var j, jl;
  4448. var iA, iB, iC;
  4449. var offsets = this.offsets;
  4450. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4451. var start = offsets[ j ].start;
  4452. var count = offsets[ j ].count;
  4453. var index = offsets[ j ].index;
  4454. for ( i = start, il = start + count; i < il; i += 3 ) {
  4455. iA = index + indices[ i ];
  4456. iB = index + indices[ i + 1 ];
  4457. iC = index + indices[ i + 2 ];
  4458. handleTriangle( iA, iB, iC );
  4459. }
  4460. }
  4461. var tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3();
  4462. var n = new THREE.Vector3(), n2 = new THREE.Vector3();
  4463. var w, t, test;
  4464. var nx, ny, nz;
  4465. function handleVertex( v ) {
  4466. n.x = normals[ v * 3 ];
  4467. n.y = normals[ v * 3 + 1 ];
  4468. n.z = normals[ v * 3 + 2 ];
  4469. n2.copy( n );
  4470. t = tan1[ v ];
  4471. // Gram-Schmidt orthogonalize
  4472. tmp.copy( t );
  4473. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  4474. // Calculate handedness
  4475. tmp2.cross( n2, t );
  4476. test = tmp2.dot( tan2[ v ] );
  4477. w = ( test < 0.0 ) ? -1.0 : 1.0;
  4478. tangents[ v * 4 ] = tmp.x;
  4479. tangents[ v * 4 + 1 ] = tmp.y;
  4480. tangents[ v * 4 + 2 ] = tmp.z;
  4481. tangents[ v * 4 + 3 ] = w;
  4482. }
  4483. for ( j = 0, jl = offsets.length; j < jl; ++ j ) {
  4484. var start = offsets[ j ].start;
  4485. var count = offsets[ j ].count;
  4486. var index = offsets[ j ].index;
  4487. for ( i = start, il = start + count; i < il; i += 3 ) {
  4488. iA = index + indices[ i ];
  4489. iB = index + indices[ i + 1 ];
  4490. iC = index + indices[ i + 2 ];
  4491. handleVertex( iA );
  4492. handleVertex( iB );
  4493. handleVertex( iC );
  4494. }
  4495. }
  4496. this.hasTangents = true;
  4497. this.tangentsNeedUpdate = true;
  4498. },
  4499. deallocate: function () {
  4500. var index = THREE.GeometryLibrary.indexOf( this );
  4501. if ( index !== -1 ) THREE.GeometryLibrary.splice( index, 1 );
  4502. }
  4503. };
  4504. /**
  4505. * Spline from Tween.js, slightly optimized (and trashed)
  4506. * http://sole.github.com/tween.js/examples/05_spline.html
  4507. *
  4508. * @author mrdoob / http://mrdoob.com/
  4509. * @author alteredq / http://alteredqualia.com/
  4510. */
  4511. THREE.Spline = function ( points ) {
  4512. this.points = points;
  4513. var c = [], v3 = { x: 0, y: 0, z: 0 },
  4514. point, intPoint, weight, w2, w3,
  4515. pa, pb, pc, pd;
  4516. this.initFromArray = function( a ) {
  4517. this.points = [];
  4518. for ( var i = 0; i < a.length; i++ ) {
  4519. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  4520. }
  4521. };
  4522. this.getPoint = function ( k ) {
  4523. point = ( this.points.length - 1 ) * k;
  4524. intPoint = Math.floor( point );
  4525. weight = point - intPoint;
  4526. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  4527. c[ 1 ] = intPoint;
  4528. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  4529. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  4530. pa = this.points[ c[ 0 ] ];
  4531. pb = this.points[ c[ 1 ] ];
  4532. pc = this.points[ c[ 2 ] ];
  4533. pd = this.points[ c[ 3 ] ];
  4534. w2 = weight * weight;
  4535. w3 = weight * w2;
  4536. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  4537. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  4538. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  4539. return v3;
  4540. };
  4541. this.getControlPointsArray = function () {
  4542. var i, p, l = this.points.length,
  4543. coords = [];
  4544. for ( i = 0; i < l; i ++ ) {
  4545. p = this.points[ i ];
  4546. coords[ i ] = [ p.x, p.y, p.z ];
  4547. }
  4548. return coords;
  4549. };
  4550. // approximate length by summing linear segments
  4551. this.getLength = function ( nSubDivisions ) {
  4552. var i, index, nSamples, position,
  4553. point = 0, intPoint = 0, oldIntPoint = 0,
  4554. oldPosition = new THREE.Vector3(),
  4555. tmpVec = new THREE.Vector3(),
  4556. chunkLengths = [],
  4557. totalLength = 0;
  4558. // first point has 0 length
  4559. chunkLengths[ 0 ] = 0;
  4560. if ( !nSubDivisions ) nSubDivisions = 100;
  4561. nSamples = this.points.length * nSubDivisions;
  4562. oldPosition.copy( this.points[ 0 ] );
  4563. for ( i = 1; i < nSamples; i ++ ) {
  4564. index = i / nSamples;
  4565. position = this.getPoint( index );
  4566. tmpVec.copy( position );
  4567. totalLength += tmpVec.distanceTo( oldPosition );
  4568. oldPosition.copy( position );
  4569. point = ( this.points.length - 1 ) * index;
  4570. intPoint = Math.floor( point );
  4571. if ( intPoint != oldIntPoint ) {
  4572. chunkLengths[ intPoint ] = totalLength;
  4573. oldIntPoint = intPoint;
  4574. }
  4575. }
  4576. // last point ends with total length
  4577. chunkLengths[ chunkLengths.length ] = totalLength;
  4578. return { chunks: chunkLengths, total: totalLength };
  4579. };
  4580. this.reparametrizeByArcLength = function ( samplingCoef ) {
  4581. var i, j,
  4582. index, indexCurrent, indexNext,
  4583. linearDistance, realDistance,
  4584. sampling, position,
  4585. newpoints = [],
  4586. tmpVec = new THREE.Vector3(),
  4587. sl = this.getLength();
  4588. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  4589. for ( i = 1; i < this.points.length; i++ ) {
  4590. //tmpVec.copy( this.points[ i - 1 ] );
  4591. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  4592. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  4593. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  4594. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  4595. indexNext = i / ( this.points.length - 1 );
  4596. for ( j = 1; j < sampling - 1; j++ ) {
  4597. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  4598. position = this.getPoint( index );
  4599. newpoints.push( tmpVec.copy( position ).clone() );
  4600. }
  4601. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  4602. }
  4603. this.points = newpoints;
  4604. };
  4605. // Catmull-Rom
  4606. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  4607. var v0 = ( p2 - p0 ) * 0.5,
  4608. v1 = ( p3 - p1 ) * 0.5;
  4609. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  4610. };
  4611. };
  4612. /**
  4613. * @author mrdoob / http://mrdoob.com/
  4614. * @author mikael emtinger / http://gomo.se/
  4615. */
  4616. THREE.Camera = function () {
  4617. THREE.Object3D.call( this );
  4618. this.matrixWorldInverse = new THREE.Matrix4();
  4619. this.projectionMatrix = new THREE.Matrix4();
  4620. this.projectionMatrixInverse = new THREE.Matrix4();
  4621. };
  4622. THREE.Camera.prototype = Object.create( THREE.Object3D.prototype );
  4623. THREE.Camera.prototype.lookAt = function ( vector ) {
  4624. // TODO: Add hierarchy support.
  4625. this.matrix.lookAt( this.position, vector, this.up );
  4626. if ( this.rotationAutoUpdate === true ) {
  4627. if ( this.useQuaternion === false ) {
  4628. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  4629. } else {
  4630. this.quaternion.copy( this.matrix.decompose()[ 1 ] );
  4631. }
  4632. }
  4633. };
  4634. /**
  4635. * @author alteredq / http://alteredqualia.com/
  4636. */
  4637. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  4638. THREE.Camera.call( this );
  4639. this.left = left;
  4640. this.right = right;
  4641. this.top = top;
  4642. this.bottom = bottom;
  4643. this.near = ( near !== undefined ) ? near : 0.1;
  4644. this.far = ( far !== undefined ) ? far : 2000;
  4645. this.updateProjectionMatrix();
  4646. };
  4647. THREE.OrthographicCamera.prototype = Object.create( THREE.Camera.prototype );
  4648. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  4649. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  4650. };
  4651. /**
  4652. * @author mrdoob / http://mrdoob.com/
  4653. * @author greggman / http://games.greggman.com/
  4654. * @author zz85 / http://www.lab4games.net/zz85/blog
  4655. */
  4656. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  4657. THREE.Camera.call( this );
  4658. this.fov = fov !== undefined ? fov : 50;
  4659. this.aspect = aspect !== undefined ? aspect : 1;
  4660. this.near = near !== undefined ? near : 0.1;
  4661. this.far = far !== undefined ? far : 2000;
  4662. this.updateProjectionMatrix();
  4663. };
  4664. THREE.PerspectiveCamera.prototype = Object.create( THREE.Camera.prototype );
  4665. /**
  4666. * Uses Focal Length (in mm) to estimate and set FOV
  4667. * 35mm (fullframe) camera is used if frame size is not specified;
  4668. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  4669. */
  4670. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  4671. if ( frameHeight === undefined ) frameHeight = 24;
  4672. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  4673. this.updateProjectionMatrix();
  4674. }
  4675. /**
  4676. * Sets an offset in a larger frustum. This is useful for multi-window or
  4677. * multi-monitor/multi-machine setups.
  4678. *
  4679. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  4680. * the monitors are in grid like this
  4681. *
  4682. * +---+---+---+
  4683. * | A | B | C |
  4684. * +---+---+---+
  4685. * | D | E | F |
  4686. * +---+---+---+
  4687. *
  4688. * then for each monitor you would call it like this
  4689. *
  4690. * var w = 1920;
  4691. * var h = 1080;
  4692. * var fullWidth = w * 3;
  4693. * var fullHeight = h * 2;
  4694. *
  4695. * --A--
  4696. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  4697. * --B--
  4698. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  4699. * --C--
  4700. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  4701. * --D--
  4702. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  4703. * --E--
  4704. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  4705. * --F--
  4706. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  4707. *
  4708. * Note there is no reason monitors have to be the same size or in a grid.
  4709. */
  4710. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  4711. this.fullWidth = fullWidth;
  4712. this.fullHeight = fullHeight;
  4713. this.x = x;
  4714. this.y = y;
  4715. this.width = width;
  4716. this.height = height;
  4717. this.updateProjectionMatrix();
  4718. };
  4719. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  4720. if ( this.fullWidth ) {
  4721. var aspect = this.fullWidth / this.fullHeight;
  4722. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  4723. var bottom = -top;
  4724. var left = aspect * bottom;
  4725. var right = aspect * top;
  4726. var width = Math.abs( right - left );
  4727. var height = Math.abs( top - bottom );
  4728. this.projectionMatrix.makeFrustum(
  4729. left + this.x * width / this.fullWidth,
  4730. left + ( this.x + this.width ) * width / this.fullWidth,
  4731. top - ( this.y + this.height ) * height / this.fullHeight,
  4732. top - this.y * height / this.fullHeight,
  4733. this.near,
  4734. this.far
  4735. );
  4736. } else {
  4737. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  4738. }
  4739. };
  4740. /**
  4741. * @author mrdoob / http://mrdoob.com/
  4742. * @author alteredq / http://alteredqualia.com/
  4743. */
  4744. THREE.Light = function ( hex ) {
  4745. THREE.Object3D.call( this );
  4746. this.color = new THREE.Color( hex );
  4747. };
  4748. THREE.Light.prototype = Object.create( THREE.Object3D.prototype );
  4749. /**
  4750. * @author mrdoob / http://mrdoob.com/
  4751. */
  4752. THREE.AmbientLight = function ( hex ) {
  4753. THREE.Light.call( this, hex );
  4754. };
  4755. THREE.AmbientLight.prototype = Object.create( THREE.Light.prototype );
  4756. /**
  4757. * @author mrdoob / http://mrdoob.com/
  4758. * @author alteredq / http://alteredqualia.com/
  4759. */
  4760. THREE.DirectionalLight = function ( hex, intensity ) {
  4761. THREE.Light.call( this, hex );
  4762. this.position = new THREE.Vector3( 0, 1, 0 );
  4763. this.target = new THREE.Object3D();
  4764. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4765. this.castShadow = false;
  4766. this.onlyShadow = false;
  4767. //
  4768. this.shadowCameraNear = 50;
  4769. this.shadowCameraFar = 5000;
  4770. this.shadowCameraLeft = -500;
  4771. this.shadowCameraRight = 500;
  4772. this.shadowCameraTop = 500;
  4773. this.shadowCameraBottom = -500;
  4774. this.shadowCameraVisible = false;
  4775. this.shadowBias = 0;
  4776. this.shadowDarkness = 0.5;
  4777. this.shadowMapWidth = 512;
  4778. this.shadowMapHeight = 512;
  4779. //
  4780. this.shadowCascade = false;
  4781. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  4782. this.shadowCascadeCount = 2;
  4783. this.shadowCascadeBias = [ 0, 0, 0 ];
  4784. this.shadowCascadeWidth = [ 512, 512, 512 ];
  4785. this.shadowCascadeHeight = [ 512, 512, 512 ];
  4786. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  4787. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  4788. this.shadowCascadeArray = [];
  4789. //
  4790. this.shadowMap = null;
  4791. this.shadowMapSize = null;
  4792. this.shadowCamera = null;
  4793. this.shadowMatrix = null;
  4794. };
  4795. THREE.DirectionalLight.prototype = Object.create( THREE.Light.prototype );
  4796. /**
  4797. * @author alteredq / http://alteredqualia.com/
  4798. */
  4799. THREE.HemisphereLight = function ( skyColorHex, groundColorHex, intensity ) {
  4800. THREE.Light.call( this, skyColorHex );
  4801. this.groundColor = new THREE.Color( groundColorHex );
  4802. this.position = new THREE.Vector3( 0, 100, 0 );
  4803. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4804. };
  4805. THREE.HemisphereLight.prototype = Object.create( THREE.Light.prototype );
  4806. /**
  4807. * @author mrdoob / http://mrdoob.com/
  4808. */
  4809. THREE.PointLight = function ( hex, intensity, distance ) {
  4810. THREE.Light.call( this, hex );
  4811. this.position = new THREE.Vector3( 0, 0, 0 );
  4812. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4813. this.distance = ( distance !== undefined ) ? distance : 0;
  4814. };
  4815. THREE.PointLight.prototype = Object.create( THREE.Light.prototype );
  4816. /**
  4817. * @author alteredq / http://alteredqualia.com/
  4818. */
  4819. THREE.SpotLight = function ( hex, intensity, distance, angle, exponent ) {
  4820. THREE.Light.call( this, hex );
  4821. this.position = new THREE.Vector3( 0, 1, 0 );
  4822. this.target = new THREE.Object3D();
  4823. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  4824. this.distance = ( distance !== undefined ) ? distance : 0;
  4825. this.angle = ( angle !== undefined ) ? angle : Math.PI / 2;
  4826. this.exponent = ( exponent !== undefined ) ? exponent : 10;
  4827. this.castShadow = false;
  4828. this.onlyShadow = false;
  4829. //
  4830. this.shadowCameraNear = 50;
  4831. this.shadowCameraFar = 5000;
  4832. this.shadowCameraFov = 50;
  4833. this.shadowCameraVisible = false;
  4834. this.shadowBias = 0;
  4835. this.shadowDarkness = 0.5;
  4836. this.shadowMapWidth = 512;
  4837. this.shadowMapHeight = 512;
  4838. //
  4839. this.shadowMap = null;
  4840. this.shadowMapSize = null;
  4841. this.shadowCamera = null;
  4842. this.shadowMatrix = null;
  4843. };
  4844. THREE.SpotLight.prototype = Object.create( THREE.Light.prototype );
  4845. /**
  4846. * @author alteredq / http://alteredqualia.com/
  4847. */
  4848. THREE.Loader = function ( showStatus ) {
  4849. this.showStatus = showStatus;
  4850. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  4851. this.onLoadStart = function () {};
  4852. this.onLoadProgress = function () {};
  4853. this.onLoadComplete = function () {};
  4854. };
  4855. THREE.Loader.prototype = {
  4856. constructor: THREE.Loader,
  4857. crossOrigin: 'anonymous',
  4858. addStatusElement: function () {
  4859. var e = document.createElement( "div" );
  4860. e.style.position = "absolute";
  4861. e.style.right = "0px";
  4862. e.style.top = "0px";
  4863. e.style.fontSize = "0.8em";
  4864. e.style.textAlign = "left";
  4865. e.style.background = "rgba(0,0,0,0.25)";
  4866. e.style.color = "#fff";
  4867. e.style.width = "120px";
  4868. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  4869. e.style.zIndex = 1000;
  4870. e.innerHTML = "Loading ...";
  4871. return e;
  4872. },
  4873. updateProgress: function ( progress ) {
  4874. var message = "Loaded ";
  4875. if ( progress.total ) {
  4876. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  4877. } else {
  4878. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  4879. }
  4880. this.statusDomElement.innerHTML = message;
  4881. },
  4882. extractUrlBase: function ( url ) {
  4883. var parts = url.split( '/' );
  4884. parts.pop();
  4885. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  4886. },
  4887. initMaterials: function ( materials, texturePath ) {
  4888. var array = [];
  4889. for ( var i = 0; i < materials.length; ++ i ) {
  4890. array[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  4891. }
  4892. return array;
  4893. },
  4894. needsTangents: function ( materials ) {
  4895. for( var i = 0, il = materials.length; i < il; i ++ ) {
  4896. var m = materials[ i ];
  4897. if ( m instanceof THREE.ShaderMaterial ) return true;
  4898. }
  4899. return false;
  4900. },
  4901. createMaterial: function ( m, texturePath ) {
  4902. var _this = this;
  4903. function is_pow2( n ) {
  4904. var l = Math.log( n ) / Math.LN2;
  4905. return Math.floor( l ) == l;
  4906. }
  4907. function nearest_pow2( n ) {
  4908. var l = Math.log( n ) / Math.LN2;
  4909. return Math.pow( 2, Math.round( l ) );
  4910. }
  4911. function load_image( where, url ) {
  4912. var image = new Image();
  4913. image.onload = function () {
  4914. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  4915. var width = nearest_pow2( this.width );
  4916. var height = nearest_pow2( this.height );
  4917. where.image.width = width;
  4918. where.image.height = height;
  4919. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  4920. } else {
  4921. where.image = this;
  4922. }
  4923. where.needsUpdate = true;
  4924. };
  4925. image.crossOrigin = _this.crossOrigin;
  4926. image.src = url;
  4927. }
  4928. function create_texture( where, name, sourceFile, repeat, offset, wrap, anisotropy ) {
  4929. var isCompressed = sourceFile.toLowerCase().endsWith( ".dds" );
  4930. var fullPath = texturePath + "/" + sourceFile;
  4931. if ( isCompressed ) {
  4932. var texture = THREE.ImageUtils.loadCompressedTexture( fullPath );
  4933. where[ name ] = texture;
  4934. } else {
  4935. var texture = document.createElement( 'canvas' );
  4936. where[ name ] = new THREE.Texture( texture );
  4937. }
  4938. where[ name ].sourceFile = sourceFile;
  4939. if( repeat ) {
  4940. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  4941. if ( repeat[ 0 ] !== 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  4942. if ( repeat[ 1 ] !== 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  4943. }
  4944. if ( offset ) {
  4945. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  4946. }
  4947. if ( wrap ) {
  4948. var wrapMap = {
  4949. "repeat": THREE.RepeatWrapping,
  4950. "mirror": THREE.MirroredRepeatWrapping
  4951. }
  4952. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  4953. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  4954. }
  4955. if ( anisotropy ) {
  4956. where[ name ].anisotropy = anisotropy;
  4957. }
  4958. if ( ! isCompressed ) {
  4959. load_image( where[ name ], fullPath );
  4960. }
  4961. }
  4962. function rgb2hex( rgb ) {
  4963. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  4964. }
  4965. // defaults
  4966. var mtype = "MeshLambertMaterial";
  4967. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, bumpMap: null, wireframe: false };
  4968. // parameters from model file
  4969. if ( m.shading ) {
  4970. var shading = m.shading.toLowerCase();
  4971. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  4972. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  4973. }
  4974. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  4975. mpars.blending = THREE[ m.blending ];
  4976. }
  4977. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  4978. mpars.transparent = m.transparent;
  4979. }
  4980. if ( m.depthTest !== undefined ) {
  4981. mpars.depthTest = m.depthTest;
  4982. }
  4983. if ( m.depthWrite !== undefined ) {
  4984. mpars.depthWrite = m.depthWrite;
  4985. }
  4986. if ( m.visible !== undefined ) {
  4987. mpars.visible = m.visible;
  4988. }
  4989. if ( m.flipSided !== undefined ) {
  4990. mpars.side = THREE.BackSide;
  4991. }
  4992. if ( m.doubleSided !== undefined ) {
  4993. mpars.side = THREE.DoubleSide;
  4994. }
  4995. if ( m.wireframe !== undefined ) {
  4996. mpars.wireframe = m.wireframe;
  4997. }
  4998. if ( m.vertexColors !== undefined ) {
  4999. if ( m.vertexColors === "face" ) {
  5000. mpars.vertexColors = THREE.FaceColors;
  5001. } else if ( m.vertexColors ) {
  5002. mpars.vertexColors = THREE.VertexColors;
  5003. }
  5004. }
  5005. // colors
  5006. if ( m.colorDiffuse ) {
  5007. mpars.color = rgb2hex( m.colorDiffuse );
  5008. } else if ( m.DbgColor ) {
  5009. mpars.color = m.DbgColor;
  5010. }
  5011. if ( m.colorSpecular ) {
  5012. mpars.specular = rgb2hex( m.colorSpecular );
  5013. }
  5014. if ( m.colorAmbient ) {
  5015. mpars.ambient = rgb2hex( m.colorAmbient );
  5016. }
  5017. // modifiers
  5018. if ( m.transparency ) {
  5019. mpars.opacity = m.transparency;
  5020. }
  5021. if ( m.specularCoef ) {
  5022. mpars.shininess = m.specularCoef;
  5023. }
  5024. // textures
  5025. if ( m.mapDiffuse && texturePath ) {
  5026. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap, m.mapDiffuseAnisotropy );
  5027. }
  5028. if ( m.mapLight && texturePath ) {
  5029. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap, m.mapLightAnisotropy );
  5030. }
  5031. if ( m.mapBump && texturePath ) {
  5032. create_texture( mpars, "bumpMap", m.mapBump, m.mapBumpRepeat, m.mapBumpOffset, m.mapBumpWrap, m.mapBumpAnisotropy );
  5033. }
  5034. if ( m.mapNormal && texturePath ) {
  5035. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap, m.mapNormalAnisotropy );
  5036. }
  5037. if ( m.mapSpecular && texturePath ) {
  5038. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap, m.mapSpecularAnisotropy );
  5039. }
  5040. //
  5041. if ( m.mapBumpScale ) {
  5042. mpars.bumpScale = m.mapBumpScale;
  5043. }
  5044. // special case for normal mapped material
  5045. if ( m.mapNormal ) {
  5046. var shader = THREE.ShaderUtils.lib[ "normal" ];
  5047. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  5048. uniforms[ "tNormal" ].value = mpars.normalMap;
  5049. if ( m.mapNormalFactor ) {
  5050. uniforms[ "uNormalScale" ].value.set( m.mapNormalFactor, m.mapNormalFactor );
  5051. }
  5052. if ( mpars.map ) {
  5053. uniforms[ "tDiffuse" ].value = mpars.map;
  5054. uniforms[ "enableDiffuse" ].value = true;
  5055. }
  5056. if ( mpars.specularMap ) {
  5057. uniforms[ "tSpecular" ].value = mpars.specularMap;
  5058. uniforms[ "enableSpecular" ].value = true;
  5059. }
  5060. if ( mpars.lightMap ) {
  5061. uniforms[ "tAO" ].value = mpars.lightMap;
  5062. uniforms[ "enableAO" ].value = true;
  5063. }
  5064. // for the moment don't handle displacement texture
  5065. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  5066. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  5067. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  5068. uniforms[ "uShininess" ].value = mpars.shininess;
  5069. if ( mpars.opacity !== undefined ) {
  5070. uniforms[ "uOpacity" ].value = mpars.opacity;
  5071. }
  5072. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  5073. var material = new THREE.ShaderMaterial( parameters );
  5074. } else {
  5075. var material = new THREE[ mtype ]( mpars );
  5076. }
  5077. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  5078. return material;
  5079. }
  5080. };
  5081. /**
  5082. * @author alteredq / http://alteredqualia.com/
  5083. */
  5084. THREE.BinaryLoader = function ( showStatus ) {
  5085. THREE.Loader.call( this, showStatus );
  5086. };
  5087. THREE.BinaryLoader.prototype = Object.create( THREE.Loader.prototype );
  5088. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  5089. // - binary models consist of two files: JS and BIN
  5090. // - parameters
  5091. // - url (required)
  5092. // - callback (required)
  5093. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  5094. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  5095. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  5096. // todo: unify load API to for easier SceneLoader use
  5097. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5098. binaryPath = binaryPath && ( typeof binaryPath === "string" ) ? binaryPath : this.extractUrlBase( url );
  5099. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  5100. this.onLoadStart();
  5101. // #1 load JS part via web worker
  5102. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  5103. };
  5104. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  5105. var xhr = new XMLHttpRequest();
  5106. xhr.onreadystatechange = function () {
  5107. if ( xhr.readyState == 4 ) {
  5108. if ( xhr.status == 200 || xhr.status == 0 ) {
  5109. var json = JSON.parse( xhr.responseText );
  5110. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  5111. } else {
  5112. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5113. }
  5114. }
  5115. };
  5116. xhr.open( "GET", url, true );
  5117. xhr.send( null );
  5118. };
  5119. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  5120. var xhr = new XMLHttpRequest(),
  5121. url = binaryPath + "/" + json.buffers;
  5122. var length = 0;
  5123. xhr.onreadystatechange = function () {
  5124. if ( xhr.readyState == 4 ) {
  5125. if ( xhr.status == 200 || xhr.status == 0 ) {
  5126. var buffer = xhr.response;
  5127. if ( buffer === undefined ) buffer = ( new Uint8Array( xhr.responseBody ) ).buffer; // IEWEBGL needs this
  5128. THREE.BinaryLoader.prototype.createBinModel( buffer, callback, texturePath, json.materials );
  5129. } else {
  5130. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5131. }
  5132. } else if ( xhr.readyState == 3 ) {
  5133. if ( callbackProgress ) {
  5134. if ( length == 0 ) {
  5135. length = xhr.getResponseHeader( "Content-Length" );
  5136. }
  5137. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5138. }
  5139. } else if ( xhr.readyState == 2 ) {
  5140. length = xhr.getResponseHeader( "Content-Length" );
  5141. }
  5142. };
  5143. xhr.open( "GET", url, true );
  5144. xhr.responseType = "arraybuffer";
  5145. xhr.send( null );
  5146. };
  5147. // Binary AJAX parser
  5148. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, jsonMaterials ) {
  5149. var Model = function ( texturePath ) {
  5150. var scope = this,
  5151. currentOffset = 0,
  5152. md,
  5153. normals = [],
  5154. uvs = [],
  5155. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  5156. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  5157. tri_size, quad_size,
  5158. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  5159. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  5160. THREE.Geometry.call( this );
  5161. md = parseMetaData( data, currentOffset );
  5162. currentOffset += md.header_bytes;
  5163. /*
  5164. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5165. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  5166. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5167. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  5168. */
  5169. // buffers sizes
  5170. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  5171. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  5172. len_tri_flat = md.ntri_flat * ( tri_size );
  5173. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  5174. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  5175. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  5176. len_quad_flat = md.nquad_flat * ( quad_size );
  5177. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  5178. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  5179. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  5180. // read buffers
  5181. currentOffset += init_vertices( currentOffset );
  5182. currentOffset += init_normals( currentOffset );
  5183. currentOffset += handlePadding( md.nnormals * 3 );
  5184. currentOffset += init_uvs( currentOffset );
  5185. start_tri_flat = currentOffset;
  5186. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  5187. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  5188. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  5189. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  5190. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  5191. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  5192. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  5193. // have to first process faces with uvs
  5194. // so that face and uv indices match
  5195. init_triangles_flat_uv( start_tri_flat_uv );
  5196. init_triangles_smooth_uv( start_tri_smooth_uv );
  5197. init_quads_flat_uv( start_quad_flat_uv );
  5198. init_quads_smooth_uv( start_quad_smooth_uv );
  5199. // now we can process untextured faces
  5200. init_triangles_flat( start_tri_flat );
  5201. init_triangles_smooth( start_tri_smooth );
  5202. init_quads_flat( start_quad_flat );
  5203. init_quads_smooth( start_quad_smooth );
  5204. this.computeCentroids();
  5205. this.computeFaceNormals();
  5206. function handlePadding( n ) {
  5207. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  5208. };
  5209. function parseMetaData( data, offset ) {
  5210. var metaData = {
  5211. 'signature' :parseString( data, offset, 12 ),
  5212. 'header_bytes' :parseUChar8( data, offset + 12 ),
  5213. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  5214. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  5215. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  5216. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  5217. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  5218. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  5219. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  5220. 'nvertices' :parseUInt32( data, offset + 20 ),
  5221. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  5222. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  5223. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  5224. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  5225. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  5226. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  5227. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  5228. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  5229. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  5230. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  5231. };
  5232. /*
  5233. console.log( "signature: " + metaData.signature );
  5234. console.log( "header_bytes: " + metaData.header_bytes );
  5235. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  5236. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  5237. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  5238. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  5239. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  5240. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  5241. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  5242. console.log( "nvertices: " + metaData.nvertices );
  5243. console.log( "nnormals: " + metaData.nnormals );
  5244. console.log( "nuvs: " + metaData.nuvs );
  5245. console.log( "ntri_flat: " + metaData.ntri_flat );
  5246. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  5247. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  5248. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  5249. console.log( "nquad_flat: " + metaData.nquad_flat );
  5250. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  5251. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  5252. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  5253. var total = metaData.header_bytes
  5254. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  5255. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  5256. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  5257. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  5258. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  5259. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  5260. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  5261. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  5262. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  5263. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  5264. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  5265. console.log( "total bytes: " + total );
  5266. */
  5267. return metaData;
  5268. };
  5269. function parseString( data, offset, length ) {
  5270. var charArray = new Uint8Array( data, offset, length );
  5271. var text = "";
  5272. for ( var i = 0; i < length; i ++ ) {
  5273. text += String.fromCharCode( charArray[ offset + i ] );
  5274. }
  5275. return text;
  5276. };
  5277. function parseUChar8( data, offset ) {
  5278. var charArray = new Uint8Array( data, offset, 1 );
  5279. return charArray[ 0 ];
  5280. };
  5281. function parseUInt32( data, offset ) {
  5282. var intArray = new Uint32Array( data, offset, 1 );
  5283. return intArray[ 0 ];
  5284. };
  5285. function init_vertices( start ) {
  5286. var nElements = md.nvertices;
  5287. var coordArray = new Float32Array( data, start, nElements * 3 );
  5288. var i, x, y, z;
  5289. for( i = 0; i < nElements; i ++ ) {
  5290. x = coordArray[ i * 3 ];
  5291. y = coordArray[ i * 3 + 1 ];
  5292. z = coordArray[ i * 3 + 2 ];
  5293. vertex( scope, x, y, z );
  5294. }
  5295. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  5296. };
  5297. function init_normals( start ) {
  5298. var nElements = md.nnormals;
  5299. if ( nElements ) {
  5300. var normalArray = new Int8Array( data, start, nElements * 3 );
  5301. var i, x, y, z;
  5302. for( i = 0; i < nElements; i ++ ) {
  5303. x = normalArray[ i * 3 ];
  5304. y = normalArray[ i * 3 + 1 ];
  5305. z = normalArray[ i * 3 + 2 ];
  5306. normals.push( x/127, y/127, z/127 );
  5307. }
  5308. }
  5309. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  5310. };
  5311. function init_uvs( start ) {
  5312. var nElements = md.nuvs;
  5313. if ( nElements ) {
  5314. var uvArray = new Float32Array( data, start, nElements * 2 );
  5315. var i, u, v;
  5316. for( i = 0; i < nElements; i ++ ) {
  5317. u = uvArray[ i * 2 ];
  5318. v = uvArray[ i * 2 + 1 ];
  5319. uvs.push( u, v );
  5320. }
  5321. }
  5322. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  5323. };
  5324. function init_uvs3( nElements, offset ) {
  5325. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  5326. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  5327. for( i = 0; i < nElements; i ++ ) {
  5328. uva = uvIndexBuffer[ i * 3 ];
  5329. uvb = uvIndexBuffer[ i * 3 + 1 ];
  5330. uvc = uvIndexBuffer[ i * 3 + 2 ];
  5331. u1 = uvs[ uva*2 ];
  5332. v1 = uvs[ uva*2 + 1 ];
  5333. u2 = uvs[ uvb*2 ];
  5334. v2 = uvs[ uvb*2 + 1 ];
  5335. u3 = uvs[ uvc*2 ];
  5336. v3 = uvs[ uvc*2 + 1 ];
  5337. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  5338. }
  5339. };
  5340. function init_uvs4( nElements, offset ) {
  5341. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  5342. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  5343. for( i = 0; i < nElements; i ++ ) {
  5344. uva = uvIndexBuffer[ i * 4 ];
  5345. uvb = uvIndexBuffer[ i * 4 + 1 ];
  5346. uvc = uvIndexBuffer[ i * 4 + 2 ];
  5347. uvd = uvIndexBuffer[ i * 4 + 3 ];
  5348. u1 = uvs[ uva*2 ];
  5349. v1 = uvs[ uva*2 + 1 ];
  5350. u2 = uvs[ uvb*2 ];
  5351. v2 = uvs[ uvb*2 + 1 ];
  5352. u3 = uvs[ uvc*2 ];
  5353. v3 = uvs[ uvc*2 + 1 ];
  5354. u4 = uvs[ uvd*2 ];
  5355. v4 = uvs[ uvd*2 + 1 ];
  5356. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  5357. }
  5358. };
  5359. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  5360. var i, a, b, c, m;
  5361. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5362. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5363. for( i = 0; i < nElements; i ++ ) {
  5364. a = vertexIndexBuffer[ i * 3 ];
  5365. b = vertexIndexBuffer[ i * 3 + 1 ];
  5366. c = vertexIndexBuffer[ i * 3 + 2 ];
  5367. m = materialIndexBuffer[ i ];
  5368. f3( scope, a, b, c, m );
  5369. }
  5370. };
  5371. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  5372. var i, a, b, c, d, m;
  5373. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5374. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5375. for( i = 0; i < nElements; i ++ ) {
  5376. a = vertexIndexBuffer[ i * 4 ];
  5377. b = vertexIndexBuffer[ i * 4 + 1 ];
  5378. c = vertexIndexBuffer[ i * 4 + 2 ];
  5379. d = vertexIndexBuffer[ i * 4 + 3 ];
  5380. m = materialIndexBuffer[ i ];
  5381. f4( scope, a, b, c, d, m );
  5382. }
  5383. };
  5384. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5385. var i, a, b, c, m;
  5386. var na, nb, nc;
  5387. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  5388. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  5389. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5390. for( i = 0; i < nElements; i ++ ) {
  5391. a = vertexIndexBuffer[ i * 3 ];
  5392. b = vertexIndexBuffer[ i * 3 + 1 ];
  5393. c = vertexIndexBuffer[ i * 3 + 2 ];
  5394. na = normalIndexBuffer[ i * 3 ];
  5395. nb = normalIndexBuffer[ i * 3 + 1 ];
  5396. nc = normalIndexBuffer[ i * 3 + 2 ];
  5397. m = materialIndexBuffer[ i ];
  5398. f3n( scope, normals, a, b, c, m, na, nb, nc );
  5399. }
  5400. };
  5401. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  5402. var i, a, b, c, d, m;
  5403. var na, nb, nc, nd;
  5404. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  5405. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  5406. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  5407. for( i = 0; i < nElements; i ++ ) {
  5408. a = vertexIndexBuffer[ i * 4 ];
  5409. b = vertexIndexBuffer[ i * 4 + 1 ];
  5410. c = vertexIndexBuffer[ i * 4 + 2 ];
  5411. d = vertexIndexBuffer[ i * 4 + 3 ];
  5412. na = normalIndexBuffer[ i * 4 ];
  5413. nb = normalIndexBuffer[ i * 4 + 1 ];
  5414. nc = normalIndexBuffer[ i * 4 + 2 ];
  5415. nd = normalIndexBuffer[ i * 4 + 3 ];
  5416. m = materialIndexBuffer[ i ];
  5417. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  5418. }
  5419. };
  5420. function init_triangles_flat( start ) {
  5421. var nElements = md.ntri_flat;
  5422. if ( nElements ) {
  5423. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5424. init_faces3_flat( nElements, start, offsetMaterials );
  5425. }
  5426. };
  5427. function init_triangles_flat_uv( start ) {
  5428. var nElements = md.ntri_flat_uv;
  5429. if ( nElements ) {
  5430. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5431. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5432. init_faces3_flat( nElements, start, offsetMaterials );
  5433. init_uvs3( nElements, offsetUvs );
  5434. }
  5435. };
  5436. function init_triangles_smooth( start ) {
  5437. var nElements = md.ntri_smooth;
  5438. if ( nElements ) {
  5439. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5440. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5441. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5442. }
  5443. };
  5444. function init_triangles_smooth_uv( start ) {
  5445. var nElements = md.ntri_smooth_uv;
  5446. if ( nElements ) {
  5447. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5448. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5449. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  5450. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  5451. init_uvs3( nElements, offsetUvs );
  5452. }
  5453. };
  5454. function init_quads_flat( start ) {
  5455. var nElements = md.nquad_flat;
  5456. if ( nElements ) {
  5457. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5458. init_faces4_flat( nElements, start, offsetMaterials );
  5459. }
  5460. };
  5461. function init_quads_flat_uv( start ) {
  5462. var nElements = md.nquad_flat_uv;
  5463. if ( nElements ) {
  5464. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5465. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5466. init_faces4_flat( nElements, start, offsetMaterials );
  5467. init_uvs4( nElements, offsetUvs );
  5468. }
  5469. };
  5470. function init_quads_smooth( start ) {
  5471. var nElements = md.nquad_smooth;
  5472. if ( nElements ) {
  5473. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5474. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5475. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5476. }
  5477. };
  5478. function init_quads_smooth_uv( start ) {
  5479. var nElements = md.nquad_smooth_uv;
  5480. if ( nElements ) {
  5481. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5482. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5483. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  5484. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  5485. init_uvs4( nElements, offsetUvs );
  5486. }
  5487. };
  5488. };
  5489. function vertex ( scope, x, y, z ) {
  5490. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  5491. };
  5492. function f3 ( scope, a, b, c, mi ) {
  5493. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  5494. };
  5495. function f4 ( scope, a, b, c, d, mi ) {
  5496. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  5497. };
  5498. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  5499. var nax = normals[ na*3 ],
  5500. nay = normals[ na*3 + 1 ],
  5501. naz = normals[ na*3 + 2 ],
  5502. nbx = normals[ nb*3 ],
  5503. nby = normals[ nb*3 + 1 ],
  5504. nbz = normals[ nb*3 + 2 ],
  5505. ncx = normals[ nc*3 ],
  5506. ncy = normals[ nc*3 + 1 ],
  5507. ncz = normals[ nc*3 + 2 ];
  5508. scope.faces.push( new THREE.Face3( a, b, c,
  5509. [new THREE.Vector3( nax, nay, naz ),
  5510. new THREE.Vector3( nbx, nby, nbz ),
  5511. new THREE.Vector3( ncx, ncy, ncz )],
  5512. null,
  5513. mi ) );
  5514. };
  5515. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  5516. var nax = normals[ na*3 ],
  5517. nay = normals[ na*3 + 1 ],
  5518. naz = normals[ na*3 + 2 ],
  5519. nbx = normals[ nb*3 ],
  5520. nby = normals[ nb*3 + 1 ],
  5521. nbz = normals[ nb*3 + 2 ],
  5522. ncx = normals[ nc*3 ],
  5523. ncy = normals[ nc*3 + 1 ],
  5524. ncz = normals[ nc*3 + 2 ],
  5525. ndx = normals[ nd*3 ],
  5526. ndy = normals[ nd*3 + 1 ],
  5527. ndz = normals[ nd*3 + 2 ];
  5528. scope.faces.push( new THREE.Face4( a, b, c, d,
  5529. [new THREE.Vector3( nax, nay, naz ),
  5530. new THREE.Vector3( nbx, nby, nbz ),
  5531. new THREE.Vector3( ncx, ncy, ncz ),
  5532. new THREE.Vector3( ndx, ndy, ndz )],
  5533. null,
  5534. mi ) );
  5535. };
  5536. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  5537. where.push( [
  5538. new THREE.UV( u1, v1 ),
  5539. new THREE.UV( u2, v2 ),
  5540. new THREE.UV( u3, v3 )
  5541. ] );
  5542. };
  5543. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  5544. where.push( [
  5545. new THREE.UV( u1, v1 ),
  5546. new THREE.UV( u2, v2 ),
  5547. new THREE.UV( u3, v3 ),
  5548. new THREE.UV( u4, v4 )
  5549. ] );
  5550. };
  5551. Model.prototype = Object.create( THREE.Geometry.prototype );
  5552. var geometry = new Model( texturePath );
  5553. var materials = this.initMaterials( jsonMaterials, texturePath );
  5554. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5555. callback( geometry, materials );
  5556. };
  5557. /**
  5558. * @author mrdoob / http://mrdoob.com/
  5559. */
  5560. THREE.ImageLoader = function () {
  5561. THREE.EventTarget.call( this );
  5562. this.crossOrigin = null;
  5563. };
  5564. THREE.ImageLoader.prototype = {
  5565. constructor: THREE.ImageLoader,
  5566. load: function ( url, image ) {
  5567. var scope = this;
  5568. if ( image === undefined ) image = new Image();
  5569. image.addEventListener( 'load', function () {
  5570. scope.dispatchEvent( { type: 'load', content: image } );
  5571. }, false );
  5572. image.addEventListener( 'error', function () {
  5573. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  5574. }, false );
  5575. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  5576. image.src = url;
  5577. }
  5578. }
  5579. /**
  5580. * @author mrdoob / http://mrdoob.com/
  5581. * @author alteredq / http://alteredqualia.com/
  5582. */
  5583. THREE.JSONLoader = function ( showStatus ) {
  5584. THREE.Loader.call( this, showStatus );
  5585. this.withCredentials = false;
  5586. };
  5587. THREE.JSONLoader.prototype = Object.create( THREE.Loader.prototype );
  5588. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  5589. var scope = this;
  5590. // todo: unify load API to for easier SceneLoader use
  5591. texturePath = texturePath && ( typeof texturePath === "string" ) ? texturePath : this.extractUrlBase( url );
  5592. this.onLoadStart();
  5593. this.loadAjaxJSON( this, url, callback, texturePath );
  5594. };
  5595. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  5596. var xhr = new XMLHttpRequest();
  5597. var length = 0;
  5598. xhr.withCredentials = this.withCredentials;
  5599. xhr.onreadystatechange = function () {
  5600. if ( xhr.readyState === xhr.DONE ) {
  5601. if ( xhr.status === 200 || xhr.status === 0 ) {
  5602. if ( xhr.responseText ) {
  5603. var json = JSON.parse( xhr.responseText );
  5604. context.createModel( json, callback, texturePath );
  5605. } else {
  5606. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  5607. }
  5608. // in context of more complex asset initialization
  5609. // do not block on single failed file
  5610. // maybe should go even one more level up
  5611. context.onLoadComplete();
  5612. } else {
  5613. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5614. }
  5615. } else if ( xhr.readyState === xhr.LOADING ) {
  5616. if ( callbackProgress ) {
  5617. if ( length === 0 ) {
  5618. length = xhr.getResponseHeader( "Content-Length" );
  5619. }
  5620. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  5621. }
  5622. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  5623. length = xhr.getResponseHeader( "Content-Length" );
  5624. }
  5625. };
  5626. xhr.open( "GET", url, true );
  5627. xhr.send( null );
  5628. };
  5629. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  5630. var scope = this,
  5631. geometry = new THREE.Geometry(),
  5632. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  5633. parseModel( scale );
  5634. parseSkin();
  5635. parseMorphing( scale );
  5636. geometry.computeCentroids();
  5637. geometry.computeFaceNormals();
  5638. function parseModel( scale ) {
  5639. function isBitSet( value, position ) {
  5640. return value & ( 1 << position );
  5641. }
  5642. var i, j, fi,
  5643. offset, zLength, nVertices,
  5644. colorIndex, normalIndex, uvIndex, materialIndex,
  5645. type,
  5646. isQuad,
  5647. hasMaterial,
  5648. hasFaceUv, hasFaceVertexUv,
  5649. hasFaceNormal, hasFaceVertexNormal,
  5650. hasFaceColor, hasFaceVertexColor,
  5651. vertex, face, color, normal,
  5652. uvLayer, uvs, u, v,
  5653. faces = json.faces,
  5654. vertices = json.vertices,
  5655. normals = json.normals,
  5656. colors = json.colors,
  5657. nUvLayers = 0;
  5658. // disregard empty arrays
  5659. for ( i = 0; i < json.uvs.length; i++ ) {
  5660. if ( json.uvs[ i ].length ) nUvLayers ++;
  5661. }
  5662. for ( i = 0; i < nUvLayers; i++ ) {
  5663. geometry.faceUvs[ i ] = [];
  5664. geometry.faceVertexUvs[ i ] = [];
  5665. }
  5666. offset = 0;
  5667. zLength = vertices.length;
  5668. while ( offset < zLength ) {
  5669. vertex = new THREE.Vector3();
  5670. vertex.x = vertices[ offset ++ ] * scale;
  5671. vertex.y = vertices[ offset ++ ] * scale;
  5672. vertex.z = vertices[ offset ++ ] * scale;
  5673. geometry.vertices.push( vertex );
  5674. }
  5675. offset = 0;
  5676. zLength = faces.length;
  5677. while ( offset < zLength ) {
  5678. type = faces[ offset ++ ];
  5679. isQuad = isBitSet( type, 0 );
  5680. hasMaterial = isBitSet( type, 1 );
  5681. hasFaceUv = isBitSet( type, 2 );
  5682. hasFaceVertexUv = isBitSet( type, 3 );
  5683. hasFaceNormal = isBitSet( type, 4 );
  5684. hasFaceVertexNormal = isBitSet( type, 5 );
  5685. hasFaceColor = isBitSet( type, 6 );
  5686. hasFaceVertexColor = isBitSet( type, 7 );
  5687. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  5688. if ( isQuad ) {
  5689. face = new THREE.Face4();
  5690. face.a = faces[ offset ++ ];
  5691. face.b = faces[ offset ++ ];
  5692. face.c = faces[ offset ++ ];
  5693. face.d = faces[ offset ++ ];
  5694. nVertices = 4;
  5695. } else {
  5696. face = new THREE.Face3();
  5697. face.a = faces[ offset ++ ];
  5698. face.b = faces[ offset ++ ];
  5699. face.c = faces[ offset ++ ];
  5700. nVertices = 3;
  5701. }
  5702. if ( hasMaterial ) {
  5703. materialIndex = faces[ offset ++ ];
  5704. face.materialIndex = materialIndex;
  5705. }
  5706. // to get face <=> uv index correspondence
  5707. fi = geometry.faces.length;
  5708. if ( hasFaceUv ) {
  5709. for ( i = 0; i < nUvLayers; i++ ) {
  5710. uvLayer = json.uvs[ i ];
  5711. uvIndex = faces[ offset ++ ];
  5712. u = uvLayer[ uvIndex * 2 ];
  5713. v = uvLayer[ uvIndex * 2 + 1 ];
  5714. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  5715. }
  5716. }
  5717. if ( hasFaceVertexUv ) {
  5718. for ( i = 0; i < nUvLayers; i++ ) {
  5719. uvLayer = json.uvs[ i ];
  5720. uvs = [];
  5721. for ( j = 0; j < nVertices; j ++ ) {
  5722. uvIndex = faces[ offset ++ ];
  5723. u = uvLayer[ uvIndex * 2 ];
  5724. v = uvLayer[ uvIndex * 2 + 1 ];
  5725. uvs[ j ] = new THREE.UV( u, v );
  5726. }
  5727. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  5728. }
  5729. }
  5730. if ( hasFaceNormal ) {
  5731. normalIndex = faces[ offset ++ ] * 3;
  5732. normal = new THREE.Vector3();
  5733. normal.x = normals[ normalIndex ++ ];
  5734. normal.y = normals[ normalIndex ++ ];
  5735. normal.z = normals[ normalIndex ];
  5736. face.normal = normal;
  5737. }
  5738. if ( hasFaceVertexNormal ) {
  5739. for ( i = 0; i < nVertices; i++ ) {
  5740. normalIndex = faces[ offset ++ ] * 3;
  5741. normal = new THREE.Vector3();
  5742. normal.x = normals[ normalIndex ++ ];
  5743. normal.y = normals[ normalIndex ++ ];
  5744. normal.z = normals[ normalIndex ];
  5745. face.vertexNormals.push( normal );
  5746. }
  5747. }
  5748. if ( hasFaceColor ) {
  5749. colorIndex = faces[ offset ++ ];
  5750. color = new THREE.Color( colors[ colorIndex ] );
  5751. face.color = color;
  5752. }
  5753. if ( hasFaceVertexColor ) {
  5754. for ( i = 0; i < nVertices; i++ ) {
  5755. colorIndex = faces[ offset ++ ];
  5756. color = new THREE.Color( colors[ colorIndex ] );
  5757. face.vertexColors.push( color );
  5758. }
  5759. }
  5760. geometry.faces.push( face );
  5761. }
  5762. };
  5763. function parseSkin() {
  5764. var i, l, x, y, z, w, a, b, c, d;
  5765. if ( json.skinWeights ) {
  5766. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  5767. x = json.skinWeights[ i ];
  5768. y = json.skinWeights[ i + 1 ];
  5769. z = 0;
  5770. w = 0;
  5771. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  5772. }
  5773. }
  5774. if ( json.skinIndices ) {
  5775. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  5776. a = json.skinIndices[ i ];
  5777. b = json.skinIndices[ i + 1 ];
  5778. c = 0;
  5779. d = 0;
  5780. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  5781. }
  5782. }
  5783. geometry.bones = json.bones;
  5784. geometry.animation = json.animation;
  5785. };
  5786. function parseMorphing( scale ) {
  5787. if ( json.morphTargets !== undefined ) {
  5788. var i, l, v, vl, dstVertices, srcVertices;
  5789. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  5790. geometry.morphTargets[ i ] = {};
  5791. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  5792. geometry.morphTargets[ i ].vertices = [];
  5793. dstVertices = geometry.morphTargets[ i ].vertices;
  5794. srcVertices = json.morphTargets [ i ].vertices;
  5795. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  5796. var vertex = new THREE.Vector3();
  5797. vertex.x = srcVertices[ v ] * scale;
  5798. vertex.y = srcVertices[ v + 1 ] * scale;
  5799. vertex.z = srcVertices[ v + 2 ] * scale;
  5800. dstVertices.push( vertex );
  5801. }
  5802. }
  5803. }
  5804. if ( json.morphColors !== undefined ) {
  5805. var i, l, c, cl, dstColors, srcColors, color;
  5806. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  5807. geometry.morphColors[ i ] = {};
  5808. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  5809. geometry.morphColors[ i ].colors = [];
  5810. dstColors = geometry.morphColors[ i ].colors;
  5811. srcColors = json.morphColors [ i ].colors;
  5812. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  5813. color = new THREE.Color( 0xffaa00 );
  5814. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  5815. dstColors.push( color );
  5816. }
  5817. }
  5818. }
  5819. };
  5820. var materials = this.initMaterials( json.materials, texturePath );
  5821. if ( this.needsTangents( materials ) ) geometry.computeTangents();
  5822. callback( geometry, materials );
  5823. };
  5824. /**
  5825. * @author mrdoob / http://mrdoob.com/
  5826. */
  5827. THREE.LoadingMonitor = function () {
  5828. THREE.EventTarget.call( this );
  5829. var scope = this;
  5830. var loaded = 0;
  5831. var total = 0;
  5832. var onLoad = function ( event ) {
  5833. loaded ++;
  5834. scope.dispatchEvent( { type: 'progress', loaded: loaded, total: total } );
  5835. if ( loaded === total ) {
  5836. scope.dispatchEvent( { type: 'load' } );
  5837. }
  5838. };
  5839. this.add = function ( loader ) {
  5840. total ++;
  5841. loader.addEventListener( 'load', onLoad, false );
  5842. };
  5843. };
  5844. /**
  5845. * @author alteredq / http://alteredqualia.com/
  5846. */
  5847. THREE.SceneLoader = function () {
  5848. this.onLoadStart = function () {};
  5849. this.onLoadProgress = function() {};
  5850. this.onLoadComplete = function () {};
  5851. this.callbackSync = function () {};
  5852. this.callbackProgress = function () {};
  5853. this.geometryHandlerMap = {};
  5854. this.hierarchyHandlerMap = {};
  5855. this.addGeometryHandler( "ascii", THREE.JSONLoader );
  5856. this.addGeometryHandler( "binary", THREE.BinaryLoader );
  5857. };
  5858. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  5859. THREE.SceneLoader.prototype.load = function ( url, callbackFinished ) {
  5860. var scope = this;
  5861. var xhr = new XMLHttpRequest();
  5862. xhr.onreadystatechange = function () {
  5863. if ( xhr.readyState === 4 ) {
  5864. if ( xhr.status === 200 || xhr.status === 0 ) {
  5865. var json = JSON.parse( xhr.responseText );
  5866. scope.parse( json, callbackFinished, url );
  5867. } else {
  5868. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  5869. }
  5870. }
  5871. };
  5872. xhr.open( "GET", url, true );
  5873. xhr.send( null );
  5874. };
  5875. THREE.SceneLoader.prototype.addGeometryHandler = function ( typeID, loaderClass ) {
  5876. this.geometryHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5877. };
  5878. THREE.SceneLoader.prototype.addHierarchyHandler = function ( typeID, loaderClass ) {
  5879. this.hierarchyHandlerMap[ typeID ] = { "loaderClass": loaderClass };
  5880. };
  5881. THREE.SceneLoader.prototype.parse = function ( json, callbackFinished, url ) {
  5882. var scope = this;
  5883. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  5884. var geometry, material, camera, fog,
  5885. texture, images, color,
  5886. light, hex, intensity,
  5887. counter_models, counter_textures,
  5888. total_models, total_textures,
  5889. result;
  5890. var target_array = [];
  5891. var data = json;
  5892. // async geometry loaders
  5893. for ( var typeID in this.geometryHandlerMap ) {
  5894. var loaderClass = this.geometryHandlerMap[ typeID ][ "loaderClass" ];
  5895. this.geometryHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5896. }
  5897. // async hierachy loaders
  5898. for ( var typeID in this.hierarchyHandlerMap ) {
  5899. var loaderClass = this.hierarchyHandlerMap[ typeID ][ "loaderClass" ];
  5900. this.hierarchyHandlerMap[ typeID ][ "loaderObject" ] = new loaderClass();
  5901. }
  5902. counter_models = 0;
  5903. counter_textures = 0;
  5904. result = {
  5905. scene: new THREE.Scene(),
  5906. geometries: {},
  5907. face_materials: {},
  5908. materials: {},
  5909. textures: {},
  5910. objects: {},
  5911. cameras: {},
  5912. lights: {},
  5913. fogs: {},
  5914. empties: {}
  5915. };
  5916. if ( data.transform ) {
  5917. var position = data.transform.position,
  5918. rotation = data.transform.rotation,
  5919. scale = data.transform.scale;
  5920. if ( position )
  5921. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  5922. if ( rotation )
  5923. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  5924. if ( scale )
  5925. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  5926. if ( position || rotation || scale ) {
  5927. result.scene.updateMatrix();
  5928. result.scene.updateMatrixWorld();
  5929. }
  5930. }
  5931. function get_url( source_url, url_type ) {
  5932. if ( url_type == "relativeToHTML" ) {
  5933. return source_url;
  5934. } else {
  5935. return urlBase + "/" + source_url;
  5936. }
  5937. };
  5938. // toplevel loader function, delegates to handle_children
  5939. function handle_objects() {
  5940. handle_children( result.scene, data.objects );
  5941. }
  5942. // handle all the children from the loaded json and attach them to given parent
  5943. function handle_children( parent, children ) {
  5944. var mat, dst, pos, rot, scl, quat;
  5945. for ( var objID in children ) {
  5946. // check by id if child has already been handled,
  5947. // if not, create new object
  5948. if ( result.objects[ objID ] === undefined ) {
  5949. var objJSON = children[ objID ];
  5950. var object = null;
  5951. // meshes
  5952. if ( objJSON.type && ( objJSON.type in scope.hierarchyHandlerMap ) && objJSON.loading === undefined ) {
  5953. var reservedTypes = { "type": 1, "url": 1, "material": 1,
  5954. "position": 1, "rotation": 1, "scale" : 1,
  5955. "visible": 1, "children": 1, "properties": 1,
  5956. "skin": 1, "morph": 1, "mirroredLoop": 1, "duration": 1 };
  5957. var loaderParameters = {};
  5958. for ( var parType in objJSON ) {
  5959. if ( ! ( parType in reservedTypes ) ) {
  5960. loaderParameters[ parType ] = objJSON[ parType ];
  5961. }
  5962. }
  5963. material = result.materials[ objJSON.material ];
  5964. objJSON.loading = true;
  5965. var loader = scope.hierarchyHandlerMap[ objJSON.type ][ "loaderObject" ];
  5966. // OBJLoader
  5967. if ( loader.addEventListener ) {
  5968. loader.addEventListener( 'load', create_callback_hierachy( objID, parent, material, objJSON ) );
  5969. loader.load( get_url( objJSON.url, data.urlBaseType ) );
  5970. } else {
  5971. // ColladaLoader
  5972. if ( loader.options ) {
  5973. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ) );
  5974. // UTF8Loader
  5975. } else {
  5976. loader.load( get_url( objJSON.url, data.urlBaseType ), create_callback_hierachy( objID, parent, material, objJSON ), loaderParameters );
  5977. }
  5978. }
  5979. } else if ( objJSON.geometry !== undefined ) {
  5980. geometry = result.geometries[ objJSON.geometry ];
  5981. // geometry already loaded
  5982. if ( geometry ) {
  5983. var needsTangents = false;
  5984. material = result.materials[ objJSON.material ];
  5985. needsTangents = material instanceof THREE.ShaderMaterial;
  5986. pos = objJSON.position;
  5987. rot = objJSON.rotation;
  5988. scl = objJSON.scale;
  5989. mat = objJSON.matrix;
  5990. quat = objJSON.quaternion;
  5991. // turn off quaternions, for the moment
  5992. quat = 0;
  5993. // use materials from the model file
  5994. // if there is no material specified in the object
  5995. if ( ! objJSON.material ) {
  5996. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  5997. }
  5998. // use materials from the model file
  5999. // if there is just empty face material
  6000. // (must create new material as each model has its own face material)
  6001. if ( ( material instanceof THREE.MeshFaceMaterial ) && material.materials.length === 0 ) {
  6002. material = new THREE.MeshFaceMaterial( result.face_materials[ objJSON.geometry ] );
  6003. }
  6004. if ( material instanceof THREE.MeshFaceMaterial ) {
  6005. for ( var i = 0; i < material.materials.length; i ++ ) {
  6006. needsTangents = needsTangents || ( material.materials[ i ] instanceof THREE.ShaderMaterial );
  6007. }
  6008. }
  6009. if ( needsTangents ) {
  6010. geometry.computeTangents();
  6011. }
  6012. if ( objJSON.skin ) {
  6013. object = new THREE.SkinnedMesh( geometry, material );
  6014. } else if ( objJSON.morph ) {
  6015. object = new THREE.MorphAnimMesh( geometry, material );
  6016. if ( objJSON.duration !== undefined ) {
  6017. object.duration = objJSON.duration;
  6018. }
  6019. if ( objJSON.time !== undefined ) {
  6020. object.time = objJSON.time;
  6021. }
  6022. if ( objJSON.mirroredLoop !== undefined ) {
  6023. object.mirroredLoop = objJSON.mirroredLoop;
  6024. }
  6025. if ( material.morphNormals ) {
  6026. geometry.computeMorphNormals();
  6027. }
  6028. } else {
  6029. object = new THREE.Mesh( geometry, material );
  6030. }
  6031. object.name = objID;
  6032. if ( mat ) {
  6033. object.matrixAutoUpdate = false;
  6034. object.matrix.set(
  6035. mat[0], mat[1], mat[2], mat[3],
  6036. mat[4], mat[5], mat[6], mat[7],
  6037. mat[8], mat[9], mat[10], mat[11],
  6038. mat[12], mat[13], mat[14], mat[15]
  6039. );
  6040. } else {
  6041. object.position.set( pos[0], pos[1], pos[2] );
  6042. if ( quat ) {
  6043. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6044. object.useQuaternion = true;
  6045. } else {
  6046. object.rotation.set( rot[0], rot[1], rot[2] );
  6047. }
  6048. object.scale.set( scl[0], scl[1], scl[2] );
  6049. }
  6050. object.visible = objJSON.visible;
  6051. object.castShadow = objJSON.castShadow;
  6052. object.receiveShadow = objJSON.receiveShadow;
  6053. parent.add( object );
  6054. result.objects[ objID ] = object;
  6055. }
  6056. // lights
  6057. } else if ( objJSON.type === "DirectionalLight" || objJSON.type === "PointLight" || objJSON.type === "AmbientLight" ) {
  6058. hex = ( objJSON.color !== undefined ) ? objJSON.color : 0xffffff;
  6059. intensity = ( objJSON.intensity !== undefined ) ? objJSON.intensity : 1;
  6060. if ( objJSON.type === "DirectionalLight" ) {
  6061. pos = objJSON.direction;
  6062. light = new THREE.DirectionalLight( hex, intensity );
  6063. light.position.set( pos[0], pos[1], pos[2] );
  6064. if ( objJSON.target ) {
  6065. target_array.push( { "object": light, "targetName" : objJSON.target } );
  6066. // kill existing default target
  6067. // otherwise it gets added to scene when parent gets added
  6068. light.target = null;
  6069. }
  6070. } else if ( objJSON.type === "PointLight" ) {
  6071. pos = objJSON.position;
  6072. dst = objJSON.distance;
  6073. light = new THREE.PointLight( hex, intensity, dst );
  6074. light.position.set( pos[0], pos[1], pos[2] );
  6075. } else if ( objJSON.type === "AmbientLight" ) {
  6076. light = new THREE.AmbientLight( hex );
  6077. }
  6078. parent.add( light );
  6079. light.name = objID;
  6080. result.lights[ objID ] = light;
  6081. result.objects[ objID ] = light;
  6082. // cameras
  6083. } else if ( objJSON.type === "PerspectiveCamera" || objJSON.type === "OrthographicCamera" ) {
  6084. if ( objJSON.type === "PerspectiveCamera" ) {
  6085. camera = new THREE.PerspectiveCamera( objJSON.fov, objJSON.aspect, objJSON.near, objJSON.far );
  6086. } else if ( objJSON.type === "OrthographicCamera" ) {
  6087. camera = new THREE.OrthographicCamera( objJSON.left, objJSON.right, objJSON.top, objJSON.bottom, objJSON.near, objJSON.far );
  6088. }
  6089. pos = objJSON.position;
  6090. camera.position.set( pos[0], pos[1], pos[2] );
  6091. parent.add( camera );
  6092. camera.name = objID;
  6093. result.cameras[ objID ] = camera;
  6094. result.objects[ objID ] = camera;
  6095. // pure Object3D
  6096. } else {
  6097. pos = objJSON.position;
  6098. rot = objJSON.rotation;
  6099. scl = objJSON.scale;
  6100. quat = objJSON.quaternion;
  6101. // turn off quaternions, for the moment
  6102. quat = 0;
  6103. object = new THREE.Object3D();
  6104. object.name = objID;
  6105. object.position.set( pos[0], pos[1], pos[2] );
  6106. if ( quat ) {
  6107. object.quaternion.set( quat[0], quat[1], quat[2], quat[3] );
  6108. object.useQuaternion = true;
  6109. } else {
  6110. object.rotation.set( rot[0], rot[1], rot[2] );
  6111. }
  6112. object.scale.set( scl[0], scl[1], scl[2] );
  6113. object.visible = ( objJSON.visible !== undefined ) ? objJSON.visible : false;
  6114. parent.add( object );
  6115. result.objects[ objID ] = object;
  6116. result.empties[ objID ] = object;
  6117. }
  6118. if ( object ) {
  6119. if ( objJSON.properties !== undefined ) {
  6120. for ( var key in objJSON.properties ) {
  6121. var value = objJSON.properties[ key ];
  6122. object.properties[ key ] = value;
  6123. }
  6124. }
  6125. if ( objJSON.children !== undefined ) {
  6126. handle_children( object, objJSON.children );
  6127. }
  6128. }
  6129. }
  6130. }
  6131. };
  6132. function handle_mesh( geo, mat, id ) {
  6133. result.geometries[ id ] = geo;
  6134. result.face_materials[ id ] = mat;
  6135. handle_objects();
  6136. };
  6137. function handle_hierarchy( node, id, parent, material, obj ) {
  6138. var p = obj.position;
  6139. var r = obj.rotation;
  6140. var q = obj.quaternion;
  6141. var s = obj.scale;
  6142. node.position.set( p[0], p[1], p[2] );
  6143. if ( q ) {
  6144. node.quaternion.set( q[0], q[1], q[2], q[3] );
  6145. node.useQuaternion = true;
  6146. } else {
  6147. node.rotation.set( r[0], r[1], r[2] );
  6148. }
  6149. node.scale.set( s[0], s[1], s[2] );
  6150. if ( material ) {
  6151. node.traverse( function ( child ) {
  6152. child.material = material;
  6153. } );
  6154. }
  6155. parent.add( node );
  6156. result.objects[ id ] = node;
  6157. handle_objects();
  6158. };
  6159. function create_callback_geometry( id ) {
  6160. return function( geo, mat ) {
  6161. handle_mesh( geo, mat, id );
  6162. counter_models -= 1;
  6163. scope.onLoadComplete();
  6164. async_callback_gate();
  6165. }
  6166. };
  6167. function create_callback_hierachy( id, parent, material, obj ) {
  6168. return function( event ) {
  6169. var result;
  6170. // loaders which use EventTarget
  6171. if ( event.content ) {
  6172. result = event.content;
  6173. // ColladaLoader
  6174. } else if ( event.dae ) {
  6175. result = event.scene;
  6176. // UTF8Loader
  6177. } else {
  6178. result = event;
  6179. }
  6180. handle_hierarchy( result, id, parent, material, obj );
  6181. counter_models -= 1;
  6182. scope.onLoadComplete();
  6183. async_callback_gate();
  6184. }
  6185. };
  6186. function create_callback_embed( id ) {
  6187. return function( geo, mat ) {
  6188. result.geometries[ id ] = geo;
  6189. result.face_materials[ id ] = mat;
  6190. }
  6191. };
  6192. function async_callback_gate() {
  6193. var progress = {
  6194. totalModels : total_models,
  6195. totalTextures : total_textures,
  6196. loadedModels : total_models - counter_models,
  6197. loadedTextures : total_textures - counter_textures
  6198. };
  6199. scope.callbackProgress( progress, result );
  6200. scope.onLoadProgress();
  6201. if ( counter_models === 0 && counter_textures === 0 ) {
  6202. finalize();
  6203. callbackFinished( result );
  6204. }
  6205. };
  6206. function finalize() {
  6207. // take care of targets which could be asynchronously loaded objects
  6208. for ( var i = 0; i < target_array.length; i ++ ) {
  6209. var ta = target_array[ i ];
  6210. var target = result.objects[ ta.targetName ];
  6211. if ( target ) {
  6212. ta.object.target = target;
  6213. } else {
  6214. // if there was error and target of specified name doesn't exist in the scene file
  6215. // create instead dummy target
  6216. // (target must be added to scene explicitly as parent is already added)
  6217. ta.object.target = new THREE.Object3D();
  6218. result.scene.add( ta.object.target );
  6219. }
  6220. ta.object.target.properties.targetInverse = ta.object;
  6221. }
  6222. };
  6223. var callbackTexture = function ( count ) {
  6224. counter_textures -= count;
  6225. async_callback_gate();
  6226. scope.onLoadComplete();
  6227. };
  6228. // must use this instead of just directly calling callbackTexture
  6229. // because of closure in the calling context loop
  6230. var generateTextureCallback = function ( count ) {
  6231. return function() {
  6232. callbackTexture( count );
  6233. };
  6234. };
  6235. // first go synchronous elements
  6236. // fogs
  6237. var fogID, fogJSON;
  6238. for ( fogID in data.fogs ) {
  6239. fogJSON = data.fogs[ fogID ];
  6240. if ( fogJSON.type === "linear" ) {
  6241. fog = new THREE.Fog( 0x000000, fogJSON.near, fogJSON.far );
  6242. } else if ( fogJSON.type === "exp2" ) {
  6243. fog = new THREE.FogExp2( 0x000000, fogJSON.density );
  6244. }
  6245. color = fogJSON.color;
  6246. fog.color.setRGB( color[0], color[1], color[2] );
  6247. result.fogs[ fogID ] = fog;
  6248. }
  6249. // now come potentially asynchronous elements
  6250. // geometries
  6251. // count how many geometries will be loaded asynchronously
  6252. var geoID, geoJSON;
  6253. for ( geoID in data.geometries ) {
  6254. geoJSON = data.geometries[ geoID ];
  6255. if ( geoJSON.type in this.geometryHandlerMap ) {
  6256. counter_models += 1;
  6257. scope.onLoadStart();
  6258. }
  6259. }
  6260. // count how many hierarchies will be loaded asynchronously
  6261. var objID, objJSON;
  6262. for ( objID in data.objects ) {
  6263. objJSON = data.objects[ objID ];
  6264. if ( objJSON.type && ( objJSON.type in this.hierarchyHandlerMap ) ) {
  6265. counter_models += 1;
  6266. scope.onLoadStart();
  6267. }
  6268. }
  6269. total_models = counter_models;
  6270. for ( geoID in data.geometries ) {
  6271. geoJSON = data.geometries[ geoID ];
  6272. if ( geoJSON.type === "cube" ) {
  6273. geometry = new THREE.CubeGeometry( geoJSON.width, geoJSON.height, geoJSON.depth, geoJSON.widthSegments, geoJSON.heightSegments, geoJSON.depthSegments );
  6274. result.geometries[ geoID ] = geometry;
  6275. } else if ( geoJSON.type === "plane" ) {
  6276. geometry = new THREE.PlaneGeometry( geoJSON.width, geoJSON.height, geoJSON.widthSegments, geoJSON.heightSegments );
  6277. result.geometries[ geoID ] = geometry;
  6278. } else if ( geoJSON.type === "sphere" ) {
  6279. geometry = new THREE.SphereGeometry( geoJSON.radius, geoJSON.widthSegments, geoJSON.heightSegments );
  6280. result.geometries[ geoID ] = geometry;
  6281. } else if ( geoJSON.type === "cylinder" ) {
  6282. geometry = new THREE.CylinderGeometry( geoJSON.topRad, geoJSON.botRad, geoJSON.height, geoJSON.radSegs, geoJSON.heightSegs );
  6283. result.geometries[ geoID ] = geometry;
  6284. } else if ( geoJSON.type === "torus" ) {
  6285. geometry = new THREE.TorusGeometry( geoJSON.radius, geoJSON.tube, geoJSON.segmentsR, geoJSON.segmentsT );
  6286. result.geometries[ geoID ] = geometry;
  6287. } else if ( geoJSON.type === "icosahedron" ) {
  6288. geometry = new THREE.IcosahedronGeometry( geoJSON.radius, geoJSON.subdivisions );
  6289. result.geometries[ geoID ] = geometry;
  6290. } else if ( geoJSON.type in this.geometryHandlerMap ) {
  6291. var loaderParameters = {};
  6292. for ( var parType in geoJSON ) {
  6293. if ( parType !== "type" && parType !== "url" ) {
  6294. loaderParameters[ parType ] = geoJSON[ parType ];
  6295. }
  6296. }
  6297. var loader = this.geometryHandlerMap[ geoJSON.type ][ "loaderObject" ];
  6298. loader.load( get_url( geoJSON.url, data.urlBaseType ), create_callback_geometry( geoID ), loaderParameters );
  6299. } else if ( geoJSON.type === "embedded" ) {
  6300. var modelJson = data.embeds[ geoJSON.id ],
  6301. texture_path = "";
  6302. // pass metadata along to jsonLoader so it knows the format version
  6303. modelJson.metadata = data.metadata;
  6304. if ( modelJson ) {
  6305. var jsonLoader = this.geometryHandlerMap[ "ascii" ][ "loaderObject" ];
  6306. jsonLoader.createModel( modelJson, create_callback_embed( geoID ), texture_path );
  6307. }
  6308. }
  6309. }
  6310. // textures
  6311. // count how many textures will be loaded asynchronously
  6312. var textureID, textureJSON;
  6313. for ( textureID in data.textures ) {
  6314. textureJSON = data.textures[ textureID ];
  6315. if ( textureJSON.url instanceof Array ) {
  6316. counter_textures += textureJSON.url.length;
  6317. for( var n = 0; n < textureJSON.url.length; n ++ ) {
  6318. scope.onLoadStart();
  6319. }
  6320. } else {
  6321. counter_textures += 1;
  6322. scope.onLoadStart();
  6323. }
  6324. }
  6325. total_textures = counter_textures;
  6326. for ( textureID in data.textures ) {
  6327. textureJSON = data.textures[ textureID ];
  6328. if ( textureJSON.mapping !== undefined && THREE[ textureJSON.mapping ] !== undefined ) {
  6329. textureJSON.mapping = new THREE[ textureJSON.mapping ]();
  6330. }
  6331. if ( textureJSON.url instanceof Array ) {
  6332. var count = textureJSON.url.length;
  6333. var url_array = [];
  6334. for( var i = 0; i < count; i ++ ) {
  6335. url_array[ i ] = get_url( textureJSON.url[ i ], data.urlBaseType );
  6336. }
  6337. var isCompressed = url_array[ 0 ].endsWith( ".dds" );
  6338. if ( isCompressed ) {
  6339. texture = THREE.ImageUtils.loadCompressedTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6340. } else {
  6341. texture = THREE.ImageUtils.loadTextureCube( url_array, textureJSON.mapping, generateTextureCallback( count ) );
  6342. }
  6343. } else {
  6344. var isCompressed = textureJSON.url.toLowerCase().endsWith( ".dds" );
  6345. var fullUrl = get_url( textureJSON.url, data.urlBaseType );
  6346. var textureCallback = generateTextureCallback( 1 );
  6347. if ( isCompressed ) {
  6348. texture = THREE.ImageUtils.loadCompressedTexture( fullUrl, textureJSON.mapping, textureCallback );
  6349. } else {
  6350. texture = THREE.ImageUtils.loadTexture( fullUrl, textureJSON.mapping, textureCallback );
  6351. }
  6352. if ( THREE[ textureJSON.minFilter ] !== undefined )
  6353. texture.minFilter = THREE[ textureJSON.minFilter ];
  6354. if ( THREE[ textureJSON.magFilter ] !== undefined )
  6355. texture.magFilter = THREE[ textureJSON.magFilter ];
  6356. if ( textureJSON.anisotropy ) texture.anisotropy = textureJSON.anisotropy;
  6357. if ( textureJSON.repeat ) {
  6358. texture.repeat.set( textureJSON.repeat[ 0 ], textureJSON.repeat[ 1 ] );
  6359. if ( textureJSON.repeat[ 0 ] !== 1 ) texture.wrapS = THREE.RepeatWrapping;
  6360. if ( textureJSON.repeat[ 1 ] !== 1 ) texture.wrapT = THREE.RepeatWrapping;
  6361. }
  6362. if ( textureJSON.offset ) {
  6363. texture.offset.set( textureJSON.offset[ 0 ], textureJSON.offset[ 1 ] );
  6364. }
  6365. // handle wrap after repeat so that default repeat can be overriden
  6366. if ( textureJSON.wrap ) {
  6367. var wrapMap = {
  6368. "repeat" : THREE.RepeatWrapping,
  6369. "mirror" : THREE.MirroredRepeatWrapping
  6370. }
  6371. if ( wrapMap[ textureJSON.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ textureJSON.wrap[ 0 ] ];
  6372. if ( wrapMap[ textureJSON.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ textureJSON.wrap[ 1 ] ];
  6373. }
  6374. }
  6375. result.textures[ textureID ] = texture;
  6376. }
  6377. // materials
  6378. var matID, matJSON;
  6379. var parID;
  6380. for ( matID in data.materials ) {
  6381. matJSON = data.materials[ matID ];
  6382. for ( parID in matJSON.parameters ) {
  6383. if ( parID === "envMap" || parID === "map" || parID === "lightMap" || parID === "bumpMap" ) {
  6384. matJSON.parameters[ parID ] = result.textures[ matJSON.parameters[ parID ] ];
  6385. } else if ( parID === "shading" ) {
  6386. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] === "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  6387. } else if ( parID === "side" ) {
  6388. if ( matJSON.parameters[ parID ] == "double" ) {
  6389. matJSON.parameters[ parID ] = THREE.DoubleSide;
  6390. } else if ( matJSON.parameters[ parID ] == "back" ) {
  6391. matJSON.parameters[ parID ] = THREE.BackSide;
  6392. } else {
  6393. matJSON.parameters[ parID ] = THREE.FrontSide;
  6394. }
  6395. } else if ( parID === "blending" ) {
  6396. matJSON.parameters[ parID ] = matJSON.parameters[ parID ] in THREE ? THREE[ matJSON.parameters[ parID ] ] : THREE.NormalBlending;
  6397. } else if ( parID === "combine" ) {
  6398. matJSON.parameters[ parID ] = ( matJSON.parameters[ parID ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  6399. } else if ( parID === "vertexColors" ) {
  6400. if ( matJSON.parameters[ parID ] == "face" ) {
  6401. matJSON.parameters[ parID ] = THREE.FaceColors;
  6402. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  6403. } else if ( matJSON.parameters[ parID ] ) {
  6404. matJSON.parameters[ parID ] = THREE.VertexColors;
  6405. }
  6406. } else if ( parID === "wrapRGB" ) {
  6407. var v3 = matJSON.parameters[ parID ];
  6408. matJSON.parameters[ parID ] = new THREE.Vector3( v3[ 0 ], v3[ 1 ], v3[ 2 ] );
  6409. }
  6410. }
  6411. if ( matJSON.parameters.opacity !== undefined && matJSON.parameters.opacity < 1.0 ) {
  6412. matJSON.parameters.transparent = true;
  6413. }
  6414. if ( matJSON.parameters.normalMap ) {
  6415. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6416. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6417. var diffuse = matJSON.parameters.color;
  6418. var specular = matJSON.parameters.specular;
  6419. var ambient = matJSON.parameters.ambient;
  6420. var shininess = matJSON.parameters.shininess;
  6421. uniforms[ "tNormal" ].value = result.textures[ matJSON.parameters.normalMap ];
  6422. if ( matJSON.parameters.normalScale ) {
  6423. uniforms[ "uNormalScale" ].value.set( matJSON.parameters.normalScale[ 0 ], matJSON.parameters.normalScale[ 1 ] );
  6424. }
  6425. if ( matJSON.parameters.map ) {
  6426. uniforms[ "tDiffuse" ].value = matJSON.parameters.map;
  6427. uniforms[ "enableDiffuse" ].value = true;
  6428. }
  6429. if ( matJSON.parameters.envMap ) {
  6430. uniforms[ "tCube" ].value = matJSON.parameters.envMap;
  6431. uniforms[ "enableReflection" ].value = true;
  6432. uniforms[ "uReflectivity" ].value = matJSON.parameters.reflectivity;
  6433. }
  6434. if ( matJSON.parameters.lightMap ) {
  6435. uniforms[ "tAO" ].value = matJSON.parameters.lightMap;
  6436. uniforms[ "enableAO" ].value = true;
  6437. }
  6438. if ( matJSON.parameters.specularMap ) {
  6439. uniforms[ "tSpecular" ].value = result.textures[ matJSON.parameters.specularMap ];
  6440. uniforms[ "enableSpecular" ].value = true;
  6441. }
  6442. if ( matJSON.parameters.displacementMap ) {
  6443. uniforms[ "tDisplacement" ].value = result.textures[ matJSON.parameters.displacementMap ];
  6444. uniforms[ "enableDisplacement" ].value = true;
  6445. uniforms[ "uDisplacementBias" ].value = matJSON.parameters.displacementBias;
  6446. uniforms[ "uDisplacementScale" ].value = matJSON.parameters.displacementScale;
  6447. }
  6448. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  6449. uniforms[ "uSpecularColor" ].value.setHex( specular );
  6450. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  6451. uniforms[ "uShininess" ].value = shininess;
  6452. if ( matJSON.parameters.opacity ) {
  6453. uniforms[ "uOpacity" ].value = matJSON.parameters.opacity;
  6454. }
  6455. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6456. material = new THREE.ShaderMaterial( parameters );
  6457. } else {
  6458. material = new THREE[ matJSON.type ]( matJSON.parameters );
  6459. }
  6460. result.materials[ matID ] = material;
  6461. }
  6462. // second pass through all materials to initialize MeshFaceMaterials
  6463. // that could be referring to other materials out of order
  6464. for ( matID in data.materials ) {
  6465. matJSON = data.materials[ matID ];
  6466. if ( matJSON.parameters.materials ) {
  6467. var materialArray = [];
  6468. for ( var i = 0; i < matJSON.parameters.materials.length; i ++ ) {
  6469. var label = matJSON.parameters.materials[ i ];
  6470. materialArray.push( result.materials[ label ] );
  6471. }
  6472. result.materials[ matID ].materials = materialArray;
  6473. }
  6474. }
  6475. // objects ( synchronous init of procedural primitives )
  6476. handle_objects();
  6477. // defaults
  6478. if ( result.cameras && data.defaults.camera ) {
  6479. result.currentCamera = result.cameras[ data.defaults.camera ];
  6480. }
  6481. if ( result.fogs && data.defaults.fog ) {
  6482. result.scene.fog = result.fogs[ data.defaults.fog ];
  6483. }
  6484. color = data.defaults.bgcolor;
  6485. result.bgColor = new THREE.Color();
  6486. result.bgColor.setRGB( color[0], color[1], color[2] );
  6487. result.bgColorAlpha = data.defaults.bgalpha;
  6488. // synchronous callback
  6489. scope.callbackSync( result );
  6490. // just in case there are no async elements
  6491. async_callback_gate();
  6492. };
  6493. /**
  6494. * @author mrdoob / http://mrdoob.com/
  6495. */
  6496. THREE.TextureLoader = function () {
  6497. THREE.EventTarget.call( this );
  6498. this.crossOrigin = null;
  6499. };
  6500. THREE.TextureLoader.prototype = {
  6501. constructor: THREE.TextureLoader,
  6502. load: function ( url ) {
  6503. var scope = this;
  6504. var image = new Image();
  6505. image.addEventListener( 'load', function () {
  6506. var texture = new THREE.Texture( image );
  6507. texture.needsUpdate = true;
  6508. scope.dispatchEvent( { type: 'load', content: texture } );
  6509. }, false );
  6510. image.addEventListener( 'error', function () {
  6511. scope.dispatchEvent( { type: 'error', message: 'Couldn\'t load URL [' + url + ']' } );
  6512. }, false );
  6513. if ( scope.crossOrigin ) image.crossOrigin = scope.crossOrigin;
  6514. image.src = url;
  6515. }
  6516. }
  6517. /**
  6518. * @author mrdoob / http://mrdoob.com/
  6519. * @author alteredq / http://alteredqualia.com/
  6520. */
  6521. THREE.Material = function () {
  6522. THREE.MaterialLibrary.push( this );
  6523. this.id = THREE.MaterialIdCount ++;
  6524. this.name = '';
  6525. this.side = THREE.FrontSide;
  6526. this.opacity = 1;
  6527. this.transparent = false;
  6528. this.blending = THREE.NormalBlending;
  6529. this.blendSrc = THREE.SrcAlphaFactor;
  6530. this.blendDst = THREE.OneMinusSrcAlphaFactor;
  6531. this.blendEquation = THREE.AddEquation;
  6532. this.depthTest = true;
  6533. this.depthWrite = true;
  6534. this.polygonOffset = false;
  6535. this.polygonOffsetFactor = 0;
  6536. this.polygonOffsetUnits = 0;
  6537. this.alphaTest = 0;
  6538. this.overdraw = false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  6539. this.visible = true;
  6540. this.needsUpdate = true;
  6541. };
  6542. THREE.Material.prototype.setValues = function ( values ) {
  6543. if ( values === undefined ) return;
  6544. for ( var key in values ) {
  6545. var newValue = values[ key ];
  6546. if ( newValue === undefined ) {
  6547. console.warn( 'THREE.Material: \'' + key + '\' parameter is undefined.' );
  6548. continue;
  6549. }
  6550. if ( key in this ) {
  6551. var currentValue = this[ key ];
  6552. if ( currentValue instanceof THREE.Color && newValue instanceof THREE.Color ) {
  6553. currentValue.copy( newValue );
  6554. } else if ( currentValue instanceof THREE.Color ) {
  6555. currentValue.set( newValue );
  6556. } else if ( currentValue instanceof THREE.Vector3 && newValue instanceof THREE.Vector3 ) {
  6557. currentValue.copy( newValue );
  6558. } else {
  6559. this[ key ] = newValue;
  6560. }
  6561. }
  6562. }
  6563. };
  6564. THREE.Material.prototype.clone = function ( material ) {
  6565. if ( material === undefined ) material = new THREE.Material();
  6566. material.name = this.name;
  6567. material.side = this.side;
  6568. material.opacity = this.opacity;
  6569. material.transparent = this.transparent;
  6570. material.blending = this.blending;
  6571. material.blendSrc = this.blendSrc;
  6572. material.blendDst = this.blendDst;
  6573. material.blendEquation = this.blendEquation;
  6574. material.depthTest = this.depthTest;
  6575. material.depthWrite = this.depthWrite;
  6576. material.polygonOffset = this.polygonOffset;
  6577. material.polygonOffsetFactor = this.polygonOffsetFactor;
  6578. material.polygonOffsetUnits = this.polygonOffsetUnits;
  6579. material.alphaTest = this.alphaTest;
  6580. material.overdraw = this.overdraw;
  6581. material.visible = this.visible;
  6582. return material;
  6583. };
  6584. THREE.Material.prototype.deallocate = function () {
  6585. var index = THREE.MaterialLibrary.indexOf( this );
  6586. if ( index !== -1 ) THREE.MaterialLibrary.splice( index, 1 );
  6587. };
  6588. THREE.MaterialIdCount = 0;
  6589. THREE.MaterialLibrary = [];
  6590. /**
  6591. * @author mrdoob / http://mrdoob.com/
  6592. * @author alteredq / http://alteredqualia.com/
  6593. *
  6594. * parameters = {
  6595. * color: <hex>,
  6596. * opacity: <float>,
  6597. *
  6598. * blending: THREE.NormalBlending,
  6599. * depthTest: <bool>,
  6600. * depthWrite: <bool>,
  6601. *
  6602. * linewidth: <float>,
  6603. * linecap: "round",
  6604. * linejoin: "round",
  6605. *
  6606. * vertexColors: <bool>
  6607. *
  6608. * fog: <bool>
  6609. * }
  6610. */
  6611. THREE.LineBasicMaterial = function ( parameters ) {
  6612. THREE.Material.call( this );
  6613. this.color = new THREE.Color( 0xffffff );
  6614. this.linewidth = 1;
  6615. this.linecap = 'round';
  6616. this.linejoin = 'round';
  6617. this.vertexColors = false;
  6618. this.fog = true;
  6619. this.setValues( parameters );
  6620. };
  6621. THREE.LineBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6622. THREE.LineBasicMaterial.prototype.clone = function () {
  6623. var material = new THREE.LineBasicMaterial();
  6624. THREE.Material.prototype.clone.call( this, material );
  6625. material.color.copy( this.color );
  6626. material.linewidth = this.linewidth;
  6627. material.linecap = this.linecap;
  6628. material.linejoin = this.linejoin;
  6629. material.vertexColors = this.vertexColors;
  6630. material.fog = this.fog;
  6631. return material;
  6632. };
  6633. /**
  6634. * @author alteredq / http://alteredqualia.com/
  6635. *
  6636. * parameters = {
  6637. * color: <hex>,
  6638. * opacity: <float>,
  6639. *
  6640. * blending: THREE.NormalBlending,
  6641. * depthTest: <bool>,
  6642. * depthWrite: <bool>,
  6643. *
  6644. * linewidth: <float>,
  6645. *
  6646. * scale: <float>,
  6647. * dashSize: <float>,
  6648. * gapSize: <float>,
  6649. *
  6650. * vertexColors: <bool>
  6651. *
  6652. * fog: <bool>
  6653. * }
  6654. */
  6655. THREE.LineDashedMaterial = function ( parameters ) {
  6656. THREE.Material.call( this );
  6657. this.color = new THREE.Color( 0xffffff );
  6658. this.linewidth = 1;
  6659. this.scale = 1;
  6660. this.dashSize = 3;
  6661. this.gapSize = 1;
  6662. this.vertexColors = false;
  6663. this.fog = true;
  6664. this.setValues( parameters );
  6665. };
  6666. THREE.LineDashedMaterial.prototype = Object.create( THREE.Material.prototype );
  6667. THREE.LineDashedMaterial.prototype.clone = function () {
  6668. var material = new THREE.LineDashedMaterial();
  6669. THREE.Material.prototype.clone.call( this, material );
  6670. material.color.copy( this.color );
  6671. material.linewidth = this.linewidth;
  6672. material.scale = this.scale;
  6673. material.dashSize = this.dashSize;
  6674. material.gapSize = this.gapSize;
  6675. material.vertexColors = this.vertexColors;
  6676. material.fog = this.fog;
  6677. return material;
  6678. };
  6679. /**
  6680. * @author mrdoob / http://mrdoob.com/
  6681. * @author alteredq / http://alteredqualia.com/
  6682. *
  6683. * parameters = {
  6684. * color: <hex>,
  6685. * opacity: <float>,
  6686. * map: new THREE.Texture( <Image> ),
  6687. *
  6688. * lightMap: new THREE.Texture( <Image> ),
  6689. *
  6690. * specularMap: new THREE.Texture( <Image> ),
  6691. *
  6692. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6693. * combine: THREE.Multiply,
  6694. * reflectivity: <float>,
  6695. * refractionRatio: <float>,
  6696. *
  6697. * shading: THREE.SmoothShading,
  6698. * blending: THREE.NormalBlending,
  6699. * depthTest: <bool>,
  6700. * depthWrite: <bool>,
  6701. *
  6702. * wireframe: <boolean>,
  6703. * wireframeLinewidth: <float>,
  6704. *
  6705. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6706. *
  6707. * skinning: <bool>,
  6708. * morphTargets: <bool>,
  6709. *
  6710. * fog: <bool>
  6711. * }
  6712. */
  6713. THREE.MeshBasicMaterial = function ( parameters ) {
  6714. THREE.Material.call( this );
  6715. this.color = new THREE.Color( 0xffffff ); // emissive
  6716. this.map = null;
  6717. this.lightMap = null;
  6718. this.specularMap = null;
  6719. this.envMap = null;
  6720. this.combine = THREE.MultiplyOperation;
  6721. this.reflectivity = 1;
  6722. this.refractionRatio = 0.98;
  6723. this.fog = true;
  6724. this.shading = THREE.SmoothShading;
  6725. this.wireframe = false;
  6726. this.wireframeLinewidth = 1;
  6727. this.wireframeLinecap = 'round';
  6728. this.wireframeLinejoin = 'round';
  6729. this.vertexColors = THREE.NoColors;
  6730. this.skinning = false;
  6731. this.morphTargets = false;
  6732. this.setValues( parameters );
  6733. };
  6734. THREE.MeshBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  6735. THREE.MeshBasicMaterial.prototype.clone = function () {
  6736. var material = new THREE.MeshBasicMaterial();
  6737. THREE.Material.prototype.clone.call( this, material );
  6738. material.color.copy( this.color );
  6739. material.map = this.map;
  6740. material.lightMap = this.lightMap;
  6741. material.specularMap = this.specularMap;
  6742. material.envMap = this.envMap;
  6743. material.combine = this.combine;
  6744. material.reflectivity = this.reflectivity;
  6745. material.refractionRatio = this.refractionRatio;
  6746. material.fog = this.fog;
  6747. material.shading = this.shading;
  6748. material.wireframe = this.wireframe;
  6749. material.wireframeLinewidth = this.wireframeLinewidth;
  6750. material.wireframeLinecap = this.wireframeLinecap;
  6751. material.wireframeLinejoin = this.wireframeLinejoin;
  6752. material.vertexColors = this.vertexColors;
  6753. material.skinning = this.skinning;
  6754. material.morphTargets = this.morphTargets;
  6755. return material;
  6756. };
  6757. /**
  6758. * @author mrdoob / http://mrdoob.com/
  6759. * @author alteredq / http://alteredqualia.com/
  6760. *
  6761. * parameters = {
  6762. * color: <hex>,
  6763. * ambient: <hex>,
  6764. * emissive: <hex>,
  6765. * opacity: <float>,
  6766. *
  6767. * map: new THREE.Texture( <Image> ),
  6768. *
  6769. * lightMap: new THREE.Texture( <Image> ),
  6770. *
  6771. * specularMap: new THREE.Texture( <Image> ),
  6772. *
  6773. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6774. * combine: THREE.Multiply,
  6775. * reflectivity: <float>,
  6776. * refractionRatio: <float>,
  6777. *
  6778. * shading: THREE.SmoothShading,
  6779. * blending: THREE.NormalBlending,
  6780. * depthTest: <bool>,
  6781. * depthWrite: <bool>,
  6782. *
  6783. * wireframe: <boolean>,
  6784. * wireframeLinewidth: <float>,
  6785. *
  6786. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6787. *
  6788. * skinning: <bool>,
  6789. * morphTargets: <bool>,
  6790. * morphNormals: <bool>,
  6791. *
  6792. * fog: <bool>
  6793. * }
  6794. */
  6795. THREE.MeshLambertMaterial = function ( parameters ) {
  6796. THREE.Material.call( this );
  6797. this.color = new THREE.Color( 0xffffff ); // diffuse
  6798. this.ambient = new THREE.Color( 0xffffff );
  6799. this.emissive = new THREE.Color( 0x000000 );
  6800. this.wrapAround = false;
  6801. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6802. this.map = null;
  6803. this.lightMap = null;
  6804. this.specularMap = null;
  6805. this.envMap = null;
  6806. this.combine = THREE.MultiplyOperation;
  6807. this.reflectivity = 1;
  6808. this.refractionRatio = 0.98;
  6809. this.fog = true;
  6810. this.shading = THREE.SmoothShading;
  6811. this.wireframe = false;
  6812. this.wireframeLinewidth = 1;
  6813. this.wireframeLinecap = 'round';
  6814. this.wireframeLinejoin = 'round';
  6815. this.vertexColors = THREE.NoColors;
  6816. this.skinning = false;
  6817. this.morphTargets = false;
  6818. this.morphNormals = false;
  6819. this.setValues( parameters );
  6820. };
  6821. THREE.MeshLambertMaterial.prototype = Object.create( THREE.Material.prototype );
  6822. THREE.MeshLambertMaterial.prototype.clone = function () {
  6823. var material = new THREE.MeshLambertMaterial();
  6824. THREE.Material.prototype.clone.call( this, material );
  6825. material.color.copy( this.color );
  6826. material.ambient.copy( this.ambient );
  6827. material.emissive.copy( this.emissive );
  6828. material.wrapAround = this.wrapAround;
  6829. material.wrapRGB.copy( this.wrapRGB );
  6830. material.map = this.map;
  6831. material.lightMap = this.lightMap;
  6832. material.specularMap = this.specularMap;
  6833. material.envMap = this.envMap;
  6834. material.combine = this.combine;
  6835. material.reflectivity = this.reflectivity;
  6836. material.refractionRatio = this.refractionRatio;
  6837. material.fog = this.fog;
  6838. material.shading = this.shading;
  6839. material.wireframe = this.wireframe;
  6840. material.wireframeLinewidth = this.wireframeLinewidth;
  6841. material.wireframeLinecap = this.wireframeLinecap;
  6842. material.wireframeLinejoin = this.wireframeLinejoin;
  6843. material.vertexColors = this.vertexColors;
  6844. material.skinning = this.skinning;
  6845. material.morphTargets = this.morphTargets;
  6846. material.morphNormals = this.morphNormals;
  6847. return material;
  6848. };
  6849. /**
  6850. * @author mrdoob / http://mrdoob.com/
  6851. * @author alteredq / http://alteredqualia.com/
  6852. *
  6853. * parameters = {
  6854. * color: <hex>,
  6855. * ambient: <hex>,
  6856. * emissive: <hex>,
  6857. * specular: <hex>,
  6858. * shininess: <float>,
  6859. * opacity: <float>,
  6860. *
  6861. * map: new THREE.Texture( <Image> ),
  6862. *
  6863. * lightMap: new THREE.Texture( <Image> ),
  6864. *
  6865. * bumpMap: new THREE.Texture( <Image> ),
  6866. * bumpScale: <float>,
  6867. *
  6868. * normalMap: new THREE.Texture( <Image> ),
  6869. * normalScale: <Vector2>,
  6870. *
  6871. * specularMap: new THREE.Texture( <Image> ),
  6872. *
  6873. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  6874. * combine: THREE.Multiply,
  6875. * reflectivity: <float>,
  6876. * refractionRatio: <float>,
  6877. *
  6878. * shading: THREE.SmoothShading,
  6879. * blending: THREE.NormalBlending,
  6880. * depthTest: <bool>,
  6881. * depthWrite: <bool>,
  6882. *
  6883. * wireframe: <boolean>,
  6884. * wireframeLinewidth: <float>,
  6885. *
  6886. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  6887. *
  6888. * skinning: <bool>,
  6889. * morphTargets: <bool>,
  6890. * morphNormals: <bool>,
  6891. *
  6892. * fog: <bool>
  6893. * }
  6894. */
  6895. THREE.MeshPhongMaterial = function ( parameters ) {
  6896. THREE.Material.call( this );
  6897. this.color = new THREE.Color( 0xffffff ); // diffuse
  6898. this.ambient = new THREE.Color( 0xffffff );
  6899. this.emissive = new THREE.Color( 0x000000 );
  6900. this.specular = new THREE.Color( 0x111111 );
  6901. this.shininess = 30;
  6902. this.metal = false;
  6903. this.perPixel = true;
  6904. this.wrapAround = false;
  6905. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  6906. this.map = null;
  6907. this.lightMap = null;
  6908. this.bumpMap = null;
  6909. this.bumpScale = 1;
  6910. this.normalMap = null;
  6911. this.normalScale = new THREE.Vector2( 1, 1 );
  6912. this.specularMap = null;
  6913. this.envMap = null;
  6914. this.combine = THREE.MultiplyOperation;
  6915. this.reflectivity = 1;
  6916. this.refractionRatio = 0.98;
  6917. this.fog = true;
  6918. this.shading = THREE.SmoothShading;
  6919. this.wireframe = false;
  6920. this.wireframeLinewidth = 1;
  6921. this.wireframeLinecap = 'round';
  6922. this.wireframeLinejoin = 'round';
  6923. this.vertexColors = THREE.NoColors;
  6924. this.skinning = false;
  6925. this.morphTargets = false;
  6926. this.morphNormals = false;
  6927. this.setValues( parameters );
  6928. };
  6929. THREE.MeshPhongMaterial.prototype = Object.create( THREE.Material.prototype );
  6930. THREE.MeshPhongMaterial.prototype.clone = function () {
  6931. var material = new THREE.MeshPhongMaterial();
  6932. THREE.Material.prototype.clone.call( this, material );
  6933. material.color.copy( this.color );
  6934. material.ambient.copy( this.ambient );
  6935. material.emissive.copy( this.emissive );
  6936. material.specular.copy( this.specular );
  6937. material.shininess = this.shininess;
  6938. material.metal = this.metal;
  6939. material.perPixel = this.perPixel;
  6940. material.wrapAround = this.wrapAround;
  6941. material.wrapRGB.copy( this.wrapRGB );
  6942. material.map = this.map;
  6943. material.lightMap = this.lightMap;
  6944. material.bumpMap = this.bumpMap;
  6945. material.bumpScale = this.bumpScale;
  6946. material.normalMap = this.normalMap;
  6947. material.normalScale.copy( this.normalScale );
  6948. material.specularMap = this.specularMap;
  6949. material.envMap = this.envMap;
  6950. material.combine = this.combine;
  6951. material.reflectivity = this.reflectivity;
  6952. material.refractionRatio = this.refractionRatio;
  6953. material.fog = this.fog;
  6954. material.shading = this.shading;
  6955. material.wireframe = this.wireframe;
  6956. material.wireframeLinewidth = this.wireframeLinewidth;
  6957. material.wireframeLinecap = this.wireframeLinecap;
  6958. material.wireframeLinejoin = this.wireframeLinejoin;
  6959. material.vertexColors = this.vertexColors;
  6960. material.skinning = this.skinning;
  6961. material.morphTargets = this.morphTargets;
  6962. material.morphNormals = this.morphNormals;
  6963. return material;
  6964. };
  6965. /**
  6966. * @author mrdoob / http://mrdoob.com/
  6967. * @author alteredq / http://alteredqualia.com/
  6968. *
  6969. * parameters = {
  6970. * opacity: <float>,
  6971. *
  6972. * blending: THREE.NormalBlending,
  6973. * depthTest: <bool>,
  6974. * depthWrite: <bool>,
  6975. *
  6976. * wireframe: <boolean>,
  6977. * wireframeLinewidth: <float>
  6978. * }
  6979. */
  6980. THREE.MeshDepthMaterial = function ( parameters ) {
  6981. THREE.Material.call( this );
  6982. this.wireframe = false;
  6983. this.wireframeLinewidth = 1;
  6984. this.setValues( parameters );
  6985. };
  6986. THREE.MeshDepthMaterial.prototype = Object.create( THREE.Material.prototype );
  6987. THREE.MeshDepthMaterial.prototype.clone = function () {
  6988. var material = new THREE.LineBasicMaterial();
  6989. THREE.Material.prototype.clone.call( this, material );
  6990. material.wireframe = this.wireframe;
  6991. material.wireframeLinewidth = this.wireframeLinewidth;
  6992. return material;
  6993. };
  6994. /**
  6995. * @author mrdoob / http://mrdoob.com/
  6996. *
  6997. * parameters = {
  6998. * opacity: <float>,
  6999. *
  7000. * shading: THREE.FlatShading,
  7001. * blending: THREE.NormalBlending,
  7002. * depthTest: <bool>,
  7003. * depthWrite: <bool>,
  7004. *
  7005. * wireframe: <boolean>,
  7006. * wireframeLinewidth: <float>
  7007. * }
  7008. */
  7009. THREE.MeshNormalMaterial = function ( parameters ) {
  7010. THREE.Material.call( this, parameters );
  7011. this.shading = THREE.FlatShading;
  7012. this.wireframe = false;
  7013. this.wireframeLinewidth = 1;
  7014. this.setValues( parameters );
  7015. };
  7016. THREE.MeshNormalMaterial.prototype = Object.create( THREE.Material.prototype );
  7017. THREE.MeshNormalMaterial.prototype.clone = function () {
  7018. var material = new THREE.MeshNormalMaterial();
  7019. THREE.Material.prototype.clone.call( this, material );
  7020. material.shading = this.shading;
  7021. material.wireframe = this.wireframe;
  7022. material.wireframeLinewidth = this.wireframeLinewidth;
  7023. return material;
  7024. };
  7025. /**
  7026. * @author mrdoob / http://mrdoob.com/
  7027. */
  7028. THREE.MeshFaceMaterial = function ( materials ) {
  7029. this.materials = materials instanceof Array ? materials : [];
  7030. };
  7031. THREE.MeshFaceMaterial.prototype.clone = function () {
  7032. return new THREE.MeshFaceMaterial( this.materials.slice( 0 ) );
  7033. };
  7034. /**
  7035. * @author mrdoob / http://mrdoob.com/
  7036. * @author alteredq / http://alteredqualia.com/
  7037. *
  7038. * parameters = {
  7039. * color: <hex>,
  7040. * opacity: <float>,
  7041. * map: new THREE.Texture( <Image> ),
  7042. *
  7043. * size: <float>,
  7044. *
  7045. * blending: THREE.NormalBlending,
  7046. * depthTest: <bool>,
  7047. * depthWrite: <bool>,
  7048. *
  7049. * vertexColors: <bool>,
  7050. *
  7051. * fog: <bool>
  7052. * }
  7053. */
  7054. THREE.ParticleBasicMaterial = function ( parameters ) {
  7055. THREE.Material.call( this );
  7056. this.color = new THREE.Color( 0xffffff );
  7057. this.map = null;
  7058. this.size = 1;
  7059. this.sizeAttenuation = true;
  7060. this.vertexColors = false;
  7061. this.fog = true;
  7062. this.setValues( parameters );
  7063. };
  7064. THREE.ParticleBasicMaterial.prototype = Object.create( THREE.Material.prototype );
  7065. THREE.ParticleBasicMaterial.prototype.clone = function () {
  7066. var material = new THREE.ParticleBasicMaterial();
  7067. THREE.Material.prototype.clone.call( this, material );
  7068. material.color.copy( this.color );
  7069. material.map = this.map;
  7070. material.size = this.size;
  7071. material.sizeAttenuation = this.sizeAttenuation;
  7072. material.vertexColors = this.vertexColors;
  7073. material.fog = this.fog;
  7074. return material;
  7075. };
  7076. /**
  7077. * @author mrdoob / http://mrdoob.com/
  7078. *
  7079. * parameters = {
  7080. * color: <hex>,
  7081. * program: <function>,
  7082. * opacity: <float>,
  7083. * blending: THREE.NormalBlending
  7084. * }
  7085. */
  7086. THREE.ParticleCanvasMaterial = function ( parameters ) {
  7087. THREE.Material.call( this );
  7088. this.color = new THREE.Color( 0xffffff );
  7089. this.program = function ( context, color ) {};
  7090. this.setValues( parameters );
  7091. };
  7092. THREE.ParticleCanvasMaterial.prototype = Object.create( THREE.Material.prototype );
  7093. THREE.ParticleCanvasMaterial.prototype.clone = function () {
  7094. var material = new THREE.ParticleCanvasMaterial();
  7095. THREE.Material.prototype.clone.call( this, material );
  7096. material.color.copy( this.color );
  7097. material.program = this.program;
  7098. return material;
  7099. };
  7100. /**
  7101. * @author mrdoob / http://mrdoob.com/
  7102. */
  7103. THREE.ParticleDOMMaterial = function ( element ) {
  7104. this.element = element;
  7105. };
  7106. THREE.ParticleDOMMaterial.prototype.clone = function(){
  7107. return new THREE.ParticleDOMMaterial( this.element );
  7108. };
  7109. /**
  7110. * @author alteredq / http://alteredqualia.com/
  7111. *
  7112. * parameters = {
  7113. * fragmentShader: <string>,
  7114. * vertexShader: <string>,
  7115. *
  7116. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  7117. *
  7118. * defines: { "label" : "value" },
  7119. *
  7120. * shading: THREE.SmoothShading,
  7121. * blending: THREE.NormalBlending,
  7122. * depthTest: <bool>,
  7123. * depthWrite: <bool>,
  7124. *
  7125. * wireframe: <boolean>,
  7126. * wireframeLinewidth: <float>,
  7127. *
  7128. * lights: <bool>,
  7129. *
  7130. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  7131. *
  7132. * skinning: <bool>,
  7133. * morphTargets: <bool>,
  7134. * morphNormals: <bool>,
  7135. *
  7136. * fog: <bool>
  7137. * }
  7138. */
  7139. THREE.ShaderMaterial = function ( parameters ) {
  7140. THREE.Material.call( this );
  7141. this.fragmentShader = "void main() {}";
  7142. this.vertexShader = "void main() {}";
  7143. this.uniforms = {};
  7144. this.defines = {};
  7145. this.attributes = null;
  7146. this.shading = THREE.SmoothShading;
  7147. this.wireframe = false;
  7148. this.wireframeLinewidth = 1;
  7149. this.fog = false; // set to use scene fog
  7150. this.lights = false; // set to use scene lights
  7151. this.vertexColors = THREE.NoColors; // set to use "color" attribute stream
  7152. this.skinning = false; // set to use skinning attribute streams
  7153. this.morphTargets = false; // set to use morph targets
  7154. this.morphNormals = false; // set to use morph normals
  7155. this.setValues( parameters );
  7156. };
  7157. THREE.ShaderMaterial.prototype = Object.create( THREE.Material.prototype );
  7158. THREE.ShaderMaterial.prototype.clone = function () {
  7159. var material = new THREE.ShaderMaterial();
  7160. THREE.Material.prototype.clone.call( this, material );
  7161. material.fragmentShader = this.fragmentShader;
  7162. material.vertexShader = this.vertexShader;
  7163. material.uniforms = THREE.UniformsUtils.clone( this.uniforms );
  7164. material.attributes = this.attributes;
  7165. material.defines = this.defines;
  7166. material.shading = this.shading;
  7167. material.wireframe = this.wireframe;
  7168. material.wireframeLinewidth = this.wireframeLinewidth;
  7169. material.fog = this.fog;
  7170. material.lights = this.lights;
  7171. material.vertexColors = this.vertexColors;
  7172. material.skinning = this.skinning;
  7173. material.morphTargets = this.morphTargets;
  7174. material.morphNormals = this.morphNormals;
  7175. return material;
  7176. };
  7177. /**
  7178. * @author alteredq / http://alteredqualia.com/
  7179. *
  7180. * parameters = {
  7181. * color: <hex>,
  7182. * opacity: <float>,
  7183. * map: new THREE.Texture( <Image> ),
  7184. *
  7185. * blending: THREE.NormalBlending,
  7186. * depthTest: <bool>,
  7187. * depthWrite: <bool>,
  7188. *
  7189. * useScreenCoordinates: <bool>,
  7190. * sizeAttenuation: <bool>,
  7191. * scaleByViewport: <bool>,
  7192. * alignment: THREE.SpriteAlignment.center,
  7193. *
  7194. * uvOffset: new THREE.Vector2(),
  7195. * uvScale: new THREE.Vector2(),
  7196. *
  7197. * fog: <bool>
  7198. * }
  7199. */
  7200. THREE.SpriteMaterial = function ( parameters ) {
  7201. THREE.Material.call( this );
  7202. // defaults
  7203. this.color = new THREE.Color( 0xffffff );
  7204. this.map = new THREE.Texture();
  7205. this.useScreenCoordinates = true;
  7206. this.depthTest = !this.useScreenCoordinates;
  7207. this.sizeAttenuation = !this.useScreenCoordinates;
  7208. this.scaleByViewport = !this.sizeAttenuation;
  7209. this.alignment = THREE.SpriteAlignment.center.clone();
  7210. this.fog = false;
  7211. this.uvOffset = new THREE.Vector2( 0, 0 );
  7212. this.uvScale = new THREE.Vector2( 1, 1 );
  7213. // set parameters
  7214. this.setValues( parameters );
  7215. // override coupled defaults if not specified explicitly by parameters
  7216. parameters = parameters || {};
  7217. if ( parameters.depthTest === undefined ) this.depthTest = !this.useScreenCoordinates;
  7218. if ( parameters.sizeAttenuation === undefined ) this.sizeAttenuation = !this.useScreenCoordinates;
  7219. if ( parameters.scaleByViewport === undefined ) this.scaleByViewport = !this.sizeAttenuation;
  7220. };
  7221. THREE.SpriteMaterial.prototype = Object.create( THREE.Material.prototype );
  7222. THREE.SpriteMaterial.prototype.clone = function () {
  7223. var material = new THREE.SpriteMaterial();
  7224. THREE.Material.prototype.clone.call( this, material );
  7225. material.color.copy( this.color );
  7226. material.map = this.map;
  7227. material.useScreenCoordinates = this.useScreenCoordinates;
  7228. material.sizeAttenuation = this.sizeAttenuation;
  7229. material.scaleByViewport = this.scaleByViewport;
  7230. material.alignment.copy( this.alignment );
  7231. material.uvOffset.copy( this.uvOffset );
  7232. material.uvScale.copy( this.uvScale );
  7233. material.fog = this.fog;
  7234. return material;
  7235. };
  7236. // Alignment enums
  7237. THREE.SpriteAlignment = {};
  7238. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  7239. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  7240. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  7241. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  7242. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  7243. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  7244. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  7245. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  7246. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  7247. /**
  7248. * @author mrdoob / http://mrdoob.com/
  7249. * @author alteredq / http://alteredqualia.com/
  7250. * @author szimek / https://github.com/szimek/
  7251. */
  7252. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy ) {
  7253. THREE.TextureLibrary.push( this );
  7254. this.id = THREE.TextureIdCount ++;
  7255. this.name = '';
  7256. this.image = image;
  7257. this.mipmaps = [];
  7258. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  7259. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  7260. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  7261. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  7262. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  7263. this.anisotropy = anisotropy !== undefined ? anisotropy : 1;
  7264. this.format = format !== undefined ? format : THREE.RGBAFormat;
  7265. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  7266. this.offset = new THREE.Vector2( 0, 0 );
  7267. this.repeat = new THREE.Vector2( 1, 1 );
  7268. this.generateMipmaps = true;
  7269. this.premultiplyAlpha = false;
  7270. this.flipY = true;
  7271. this.unpackAlignment = 4; // valid values: 1, 2, 4, 8 (see http://www.khronos.org/opengles/sdk/docs/man/xhtml/glPixelStorei.xml)
  7272. this.needsUpdate = false;
  7273. this.onUpdate = null;
  7274. };
  7275. THREE.Texture.prototype = {
  7276. constructor: THREE.Texture,
  7277. clone: function ( texture ) {
  7278. if ( texture === undefined ) texture = new THREE.Texture();
  7279. texture.image = this.image;
  7280. texture.mipmaps = this.mipmaps.slice(0);
  7281. texture.mapping = this.mapping;
  7282. texture.wrapS = this.wrapS;
  7283. texture.wrapT = this.wrapT;
  7284. texture.magFilter = this.magFilter;
  7285. texture.minFilter = this.minFilter;
  7286. texture.anisotropy = this.anisotropy;
  7287. texture.format = this.format;
  7288. texture.type = this.type;
  7289. texture.offset.copy( this.offset );
  7290. texture.repeat.copy( this.repeat );
  7291. texture.generateMipmaps = this.generateMipmaps;
  7292. texture.premultiplyAlpha = this.premultiplyAlpha;
  7293. texture.flipY = this.flipY;
  7294. texture.unpackAlignment = this.unpackAlignment;
  7295. return texture;
  7296. },
  7297. deallocate: function () {
  7298. var index = THREE.TextureLibrary.indexOf( this );
  7299. if ( index !== -1 ) THREE.TextureLibrary.splice( index, 1 );
  7300. }
  7301. };
  7302. THREE.TextureIdCount = 0;
  7303. THREE.TextureLibrary = [];
  7304. /**
  7305. * @author alteredq / http://alteredqualia.com/
  7306. */
  7307. THREE.CompressedTexture = function ( mipmaps, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7308. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7309. this.image = { width: width, height: height };
  7310. this.mipmaps = mipmaps;
  7311. this.generateMipmaps = false; // WebGL currently can't generate mipmaps for compressed textures, they must be embedded in DDS file
  7312. };
  7313. THREE.CompressedTexture.prototype = Object.create( THREE.Texture.prototype );
  7314. THREE.CompressedTexture.prototype.clone = function () {
  7315. var texture = new THREE.CompressedTexture();
  7316. THREE.Texture.prototype.clone.call( this, texture );
  7317. return texture;
  7318. };
  7319. /**
  7320. * @author alteredq / http://alteredqualia.com/
  7321. */
  7322. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter, anisotropy ) {
  7323. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy );
  7324. this.image = { data: data, width: width, height: height };
  7325. };
  7326. THREE.DataTexture.prototype = Object.create( THREE.Texture.prototype );
  7327. THREE.DataTexture.prototype.clone = function () {
  7328. var texture = new THREE.DataTexture();
  7329. THREE.Texture.prototype.clone.call( this, texture );
  7330. return texture;
  7331. };
  7332. /**
  7333. * @author mrdoob / http://mrdoob.com/
  7334. */
  7335. THREE.Particle = function ( material ) {
  7336. THREE.Object3D.call( this );
  7337. this.material = material;
  7338. };
  7339. THREE.Particle.prototype = Object.create( THREE.Object3D.prototype );
  7340. THREE.Particle.prototype.clone = function ( object ) {
  7341. if ( object === undefined ) object = new THREE.Particle( this.material );
  7342. THREE.Object3D.prototype.clone.call( this, object );
  7343. return object;
  7344. };
  7345. /**
  7346. * @author alteredq / http://alteredqualia.com/
  7347. */
  7348. THREE.ParticleSystem = function ( geometry, material ) {
  7349. THREE.Object3D.call( this );
  7350. this.geometry = geometry;
  7351. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  7352. this.sortParticles = false;
  7353. if ( this.geometry ) {
  7354. // calc bound radius
  7355. if( this.geometry.boundingSphere === null ) {
  7356. this.geometry.computeBoundingSphere();
  7357. }
  7358. this.boundRadius = geometry.boundingSphere.radius;
  7359. }
  7360. this.frustumCulled = false;
  7361. };
  7362. THREE.ParticleSystem.prototype = Object.create( THREE.Object3D.prototype );
  7363. THREE.ParticleSystem.prototype.clone = function ( object ) {
  7364. if ( object === undefined ) object = new THREE.ParticleSystem( this.geometry, this.material );
  7365. object.sortParticles = this.sortParticles;
  7366. THREE.Object3D.prototype.clone.call( this, object );
  7367. return object;
  7368. };
  7369. /**
  7370. * @author mrdoob / http://mrdoob.com/
  7371. */
  7372. THREE.Line = function ( geometry, material, type ) {
  7373. THREE.Object3D.call( this );
  7374. this.geometry = geometry;
  7375. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  7376. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  7377. if ( this.geometry ) {
  7378. if ( ! this.geometry.boundingSphere ) {
  7379. this.geometry.computeBoundingSphere();
  7380. }
  7381. }
  7382. };
  7383. THREE.LineStrip = 0;
  7384. THREE.LinePieces = 1;
  7385. THREE.Line.prototype = Object.create( THREE.Object3D.prototype );
  7386. THREE.Line.prototype.clone = function ( object ) {
  7387. if ( object === undefined ) object = new THREE.Line( this.geometry, this.material, this.type );
  7388. THREE.Object3D.prototype.clone.call( this, object );
  7389. return object;
  7390. };
  7391. /**
  7392. * @author mrdoob / http://mrdoob.com/
  7393. * @author alteredq / http://alteredqualia.com/
  7394. * @author mikael emtinger / http://gomo.se/
  7395. */
  7396. THREE.Mesh = function ( geometry, material ) {
  7397. THREE.Object3D.call( this );
  7398. this.geometry = geometry;
  7399. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  7400. if ( this.geometry ) {
  7401. // calc bound radius
  7402. if ( this.geometry.boundingSphere === null ) {
  7403. this.geometry.computeBoundingSphere();
  7404. }
  7405. this.boundRadius = geometry.boundingSphere.radius;
  7406. // setup morph targets
  7407. if ( this.geometry.morphTargets.length ) {
  7408. this.morphTargetBase = -1;
  7409. this.morphTargetForcedOrder = [];
  7410. this.morphTargetInfluences = [];
  7411. this.morphTargetDictionary = {};
  7412. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  7413. this.morphTargetInfluences.push( 0 );
  7414. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  7415. }
  7416. }
  7417. }
  7418. }
  7419. THREE.Mesh.prototype = Object.create( THREE.Object3D.prototype );
  7420. THREE.Mesh.prototype.getMorphTargetIndexByName = function ( name ) {
  7421. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  7422. return this.morphTargetDictionary[ name ];
  7423. }
  7424. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  7425. return 0;
  7426. };
  7427. THREE.Mesh.prototype.clone = function ( object ) {
  7428. if ( object === undefined ) object = new THREE.Mesh( this.geometry, this.material );
  7429. THREE.Object3D.prototype.clone.call( this, object );
  7430. return object;
  7431. };
  7432. /**
  7433. * @author mikael emtinger / http://gomo.se/
  7434. * @author alteredq / http://alteredqualia.com/
  7435. */
  7436. THREE.Bone = function( belongsToSkin ) {
  7437. THREE.Object3D.call( this );
  7438. this.skin = belongsToSkin;
  7439. this.skinMatrix = new THREE.Matrix4();
  7440. };
  7441. THREE.Bone.prototype = Object.create( THREE.Object3D.prototype );
  7442. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  7443. // update local
  7444. if ( this.matrixAutoUpdate ) {
  7445. forceUpdate |= this.updateMatrix();
  7446. }
  7447. // update skin matrix
  7448. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  7449. if( parentSkinMatrix ) {
  7450. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  7451. } else {
  7452. this.skinMatrix.copy( this.matrix );
  7453. }
  7454. this.matrixWorldNeedsUpdate = false;
  7455. forceUpdate = true;
  7456. }
  7457. // update children
  7458. var child, i, l = this.children.length;
  7459. for ( i = 0; i < l; i ++ ) {
  7460. this.children[ i ].update( this.skinMatrix, forceUpdate );
  7461. }
  7462. };
  7463. /**
  7464. * @author mikael emtinger / http://gomo.se/
  7465. * @author alteredq / http://alteredqualia.com/
  7466. */
  7467. THREE.SkinnedMesh = function ( geometry, material, useVertexTexture ) {
  7468. THREE.Mesh.call( this, geometry, material );
  7469. //
  7470. this.useVertexTexture = useVertexTexture !== undefined ? useVertexTexture : true;
  7471. // init bones
  7472. this.identityMatrix = new THREE.Matrix4();
  7473. this.bones = [];
  7474. this.boneMatrices = [];
  7475. var b, bone, gbone, p, q, s;
  7476. if ( this.geometry && this.geometry.bones !== undefined ) {
  7477. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  7478. gbone = this.geometry.bones[ b ];
  7479. p = gbone.pos;
  7480. q = gbone.rotq;
  7481. s = gbone.scl;
  7482. bone = this.addBone();
  7483. bone.name = gbone.name;
  7484. bone.position.set( p[0], p[1], p[2] );
  7485. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  7486. bone.useQuaternion = true;
  7487. if ( s !== undefined ) {
  7488. bone.scale.set( s[0], s[1], s[2] );
  7489. } else {
  7490. bone.scale.set( 1, 1, 1 );
  7491. }
  7492. }
  7493. for ( b = 0; b < this.bones.length; b ++ ) {
  7494. gbone = this.geometry.bones[ b ];
  7495. bone = this.bones[ b ];
  7496. if ( gbone.parent === -1 ) {
  7497. this.add( bone );
  7498. } else {
  7499. this.bones[ gbone.parent ].add( bone );
  7500. }
  7501. }
  7502. //
  7503. var nBones = this.bones.length;
  7504. if ( this.useVertexTexture ) {
  7505. // layout (1 matrix = 4 pixels)
  7506. // RGBA RGBA RGBA RGBA (=> column1, column2, column3, column4)
  7507. // with 8x8 pixel texture max 16 bones (8 * 8 / 4)
  7508. // 16x16 pixel texture max 64 bones (16 * 16 / 4)
  7509. // 32x32 pixel texture max 256 bones (32 * 32 / 4)
  7510. // 64x64 pixel texture max 1024 bones (64 * 64 / 4)
  7511. var size;
  7512. if ( nBones > 256 )
  7513. size = 64;
  7514. else if ( nBones > 64 )
  7515. size = 32;
  7516. else if ( nBones > 16 )
  7517. size = 16;
  7518. else
  7519. size = 8;
  7520. this.boneTextureWidth = size;
  7521. this.boneTextureHeight = size;
  7522. this.boneMatrices = new Float32Array( this.boneTextureWidth * this.boneTextureHeight * 4 ); // 4 floats per RGBA pixel
  7523. this.boneTexture = new THREE.DataTexture( this.boneMatrices, this.boneTextureWidth, this.boneTextureHeight, THREE.RGBAFormat, THREE.FloatType );
  7524. this.boneTexture.minFilter = THREE.NearestFilter;
  7525. this.boneTexture.magFilter = THREE.NearestFilter;
  7526. this.boneTexture.generateMipmaps = false;
  7527. this.boneTexture.flipY = false;
  7528. } else {
  7529. this.boneMatrices = new Float32Array( 16 * nBones );
  7530. }
  7531. this.pose();
  7532. }
  7533. };
  7534. THREE.SkinnedMesh.prototype = Object.create( THREE.Mesh.prototype );
  7535. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  7536. if ( bone === undefined ) {
  7537. bone = new THREE.Bone( this );
  7538. }
  7539. this.bones.push( bone );
  7540. return bone;
  7541. };
  7542. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  7543. this.matrixAutoUpdate && this.updateMatrix();
  7544. // update matrixWorld
  7545. if ( this.matrixWorldNeedsUpdate || force ) {
  7546. if ( this.parent ) {
  7547. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  7548. } else {
  7549. this.matrixWorld.copy( this.matrix );
  7550. }
  7551. this.matrixWorldNeedsUpdate = false;
  7552. force = true;
  7553. }
  7554. // update children
  7555. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  7556. var child = this.children[ i ];
  7557. if ( child instanceof THREE.Bone ) {
  7558. child.update( this.identityMatrix, false );
  7559. } else {
  7560. child.updateMatrixWorld( true );
  7561. }
  7562. }
  7563. // make a snapshot of the bones' rest position
  7564. if ( this.boneInverses == undefined ) {
  7565. this.boneInverses = [];
  7566. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7567. var inverse = new THREE.Matrix4();
  7568. inverse.getInverse( this.bones[ b ].skinMatrix );
  7569. this.boneInverses.push( inverse );
  7570. }
  7571. }
  7572. // flatten bone matrices to array
  7573. for ( var b = 0, bl = this.bones.length; b < bl; b ++ ) {
  7574. // compute the offset between the current and the original transform;
  7575. //TODO: we could get rid of this multiplication step if the skinMatrix
  7576. // was already representing the offset; however, this requires some
  7577. // major changes to the animation system
  7578. THREE.SkinnedMesh.offsetMatrix.multiply( this.bones[ b ].skinMatrix, this.boneInverses[ b ] );
  7579. THREE.SkinnedMesh.offsetMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  7580. }
  7581. if ( this.useVertexTexture ) {
  7582. this.boneTexture.needsUpdate = true;
  7583. }
  7584. };
  7585. THREE.SkinnedMesh.prototype.pose = function() {
  7586. this.updateMatrixWorld( true );
  7587. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  7588. // normalize weights
  7589. var sw = this.geometry.skinWeights[ i ];
  7590. var scale = 1.0 / sw.lengthManhattan();
  7591. if ( scale !== Infinity ) {
  7592. sw.multiplyScalar( scale );
  7593. } else {
  7594. sw.set( 1 ); // this will be normalized by the shader anyway
  7595. }
  7596. }
  7597. };
  7598. THREE.SkinnedMesh.prototype.clone = function ( object ) {
  7599. if ( object === undefined ) object = new THREE.SkinnedMesh( this.geometry, this.material, this.useVertexTexture );
  7600. THREE.Mesh.prototype.clone.call( this, object );
  7601. return object;
  7602. };
  7603. THREE.SkinnedMesh.offsetMatrix = new THREE.Matrix4();
  7604. /**
  7605. * @author alteredq / http://alteredqualia.com/
  7606. */
  7607. THREE.MorphAnimMesh = function ( geometry, material ) {
  7608. THREE.Mesh.call( this, geometry, material );
  7609. // API
  7610. this.duration = 1000; // milliseconds
  7611. this.mirroredLoop = false;
  7612. this.time = 0;
  7613. // internals
  7614. this.lastKeyframe = 0;
  7615. this.currentKeyframe = 0;
  7616. this.direction = 1;
  7617. this.directionBackwards = false;
  7618. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  7619. };
  7620. THREE.MorphAnimMesh.prototype = Object.create( THREE.Mesh.prototype );
  7621. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  7622. this.startKeyframe = start;
  7623. this.endKeyframe = end;
  7624. this.length = this.endKeyframe - this.startKeyframe + 1;
  7625. };
  7626. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  7627. this.direction = 1;
  7628. this.directionBackwards = false;
  7629. };
  7630. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  7631. this.direction = -1;
  7632. this.directionBackwards = true;
  7633. };
  7634. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  7635. var geometry = this.geometry;
  7636. if ( ! geometry.animations ) geometry.animations = {};
  7637. var firstAnimation, animations = geometry.animations;
  7638. var pattern = /([a-z]+)(\d+)/;
  7639. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  7640. var morph = geometry.morphTargets[ i ];
  7641. var parts = morph.name.match( pattern );
  7642. if ( parts && parts.length > 1 ) {
  7643. var label = parts[ 1 ];
  7644. var num = parts[ 2 ];
  7645. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  7646. var animation = animations[ label ];
  7647. if ( i < animation.start ) animation.start = i;
  7648. if ( i > animation.end ) animation.end = i;
  7649. if ( ! firstAnimation ) firstAnimation = label;
  7650. }
  7651. }
  7652. geometry.firstAnimation = firstAnimation;
  7653. };
  7654. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  7655. if ( ! this.geometry.animations ) this.geometry.animations = {};
  7656. this.geometry.animations[ label ] = { start: start, end: end };
  7657. };
  7658. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  7659. var animation = this.geometry.animations[ label ];
  7660. if ( animation ) {
  7661. this.setFrameRange( animation.start, animation.end );
  7662. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  7663. this.time = 0;
  7664. } else {
  7665. console.warn( "animation[" + label + "] undefined" );
  7666. }
  7667. };
  7668. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  7669. var frameTime = this.duration / this.length;
  7670. this.time += this.direction * delta;
  7671. if ( this.mirroredLoop ) {
  7672. if ( this.time > this.duration || this.time < 0 ) {
  7673. this.direction *= -1;
  7674. if ( this.time > this.duration ) {
  7675. this.time = this.duration;
  7676. this.directionBackwards = true;
  7677. }
  7678. if ( this.time < 0 ) {
  7679. this.time = 0;
  7680. this.directionBackwards = false;
  7681. }
  7682. }
  7683. } else {
  7684. this.time = this.time % this.duration;
  7685. if ( this.time < 0 ) this.time += this.duration;
  7686. }
  7687. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  7688. if ( keyframe !== this.currentKeyframe ) {
  7689. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  7690. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  7691. this.morphTargetInfluences[ keyframe ] = 0;
  7692. this.lastKeyframe = this.currentKeyframe;
  7693. this.currentKeyframe = keyframe;
  7694. }
  7695. var mix = ( this.time % frameTime ) / frameTime;
  7696. if ( this.directionBackwards ) {
  7697. mix = 1 - mix;
  7698. }
  7699. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  7700. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  7701. };
  7702. THREE.MorphAnimMesh.prototype.clone = function ( object ) {
  7703. if ( object === undefined ) object = new THREE.MorphAnimMesh( this.geometry, this.material );
  7704. object.duration = this.duration;
  7705. object.mirroredLoop = this.mirroredLoop;
  7706. object.time = this.time;
  7707. object.lastKeyframe = this.lastKeyframe;
  7708. object.currentKeyframe = this.currentKeyframe;
  7709. object.direction = this.direction;
  7710. object.directionBackwards = this.directionBackwards;
  7711. THREE.Mesh.prototype.clone.call( this, object );
  7712. return object;
  7713. };
  7714. /**
  7715. * @author alteredq / http://alteredqualia.com/
  7716. */
  7717. THREE.Ribbon = function ( geometry, material ) {
  7718. THREE.Object3D.call( this );
  7719. this.geometry = geometry;
  7720. this.material = material;
  7721. };
  7722. THREE.Ribbon.prototype = Object.create( THREE.Object3D.prototype );
  7723. THREE.Ribbon.prototype.clone = function ( object ) {
  7724. if ( object === undefined ) object = new THREE.Ribbon( this.geometry, this.material );
  7725. THREE.Object3D.prototype.clone.call( this, object );
  7726. return object;
  7727. };
  7728. /**
  7729. * @author mikael emtinger / http://gomo.se/
  7730. * @author alteredq / http://alteredqualia.com/
  7731. * @author mrdoob / http://mrdoob.com/
  7732. */
  7733. THREE.LOD = function () {
  7734. THREE.Object3D.call( this );
  7735. this.LODs = [];
  7736. };
  7737. THREE.LOD.prototype = Object.create( THREE.Object3D.prototype );
  7738. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  7739. if ( visibleAtDistance === undefined ) {
  7740. visibleAtDistance = 0;
  7741. }
  7742. visibleAtDistance = Math.abs( visibleAtDistance );
  7743. for ( var l = 0; l < this.LODs.length; l ++ ) {
  7744. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  7745. break;
  7746. }
  7747. }
  7748. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  7749. this.add( object3D );
  7750. };
  7751. THREE.LOD.prototype.update = function ( camera ) {
  7752. if ( this.LODs.length > 1 ) {
  7753. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  7754. var inverse = camera.matrixWorldInverse;
  7755. 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] );
  7756. this.LODs[ 0 ].object3D.visible = true;
  7757. for ( var l = 1; l < this.LODs.length; l ++ ) {
  7758. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  7759. this.LODs[ l - 1 ].object3D.visible = false;
  7760. this.LODs[ l ].object3D.visible = true;
  7761. } else {
  7762. break;
  7763. }
  7764. }
  7765. for( ; l < this.LODs.length; l ++ ) {
  7766. this.LODs[ l ].object3D.visible = false;
  7767. }
  7768. }
  7769. };
  7770. THREE.LOD.prototype.clone = function () {
  7771. // TODO
  7772. };
  7773. /**
  7774. * @author mikael emtinger / http://gomo.se/
  7775. * @author alteredq / http://alteredqualia.com/
  7776. */
  7777. THREE.Sprite = function ( material ) {
  7778. THREE.Object3D.call( this );
  7779. this.material = ( material !== undefined ) ? material : new THREE.SpriteMaterial();
  7780. this.rotation3d = this.rotation;
  7781. this.rotation = 0;
  7782. };
  7783. THREE.Sprite.prototype = Object.create( THREE.Object3D.prototype );
  7784. /*
  7785. * Custom update matrix
  7786. */
  7787. THREE.Sprite.prototype.updateMatrix = function () {
  7788. this.matrix.setPosition( this.position );
  7789. this.rotation3d.set( 0, 0, this.rotation );
  7790. this.matrix.setRotationFromEuler( this.rotation3d );
  7791. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  7792. this.matrix.scale( this.scale );
  7793. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  7794. }
  7795. this.matrixWorldNeedsUpdate = true;
  7796. };
  7797. THREE.Sprite.prototype.clone = function ( object ) {
  7798. if ( object === undefined ) object = new THREE.Sprite( this.material );
  7799. THREE.Object3D.prototype.clone.call( this, object );
  7800. return object;
  7801. };
  7802. /**
  7803. * @author mrdoob / http://mrdoob.com/
  7804. */
  7805. THREE.Scene = function () {
  7806. THREE.Object3D.call( this );
  7807. this.fog = null;
  7808. this.overrideMaterial = null;
  7809. this.matrixAutoUpdate = false;
  7810. this.__objects = [];
  7811. this.__lights = [];
  7812. this.__objectsAdded = [];
  7813. this.__objectsRemoved = [];
  7814. };
  7815. THREE.Scene.prototype = Object.create( THREE.Object3D.prototype );
  7816. THREE.Scene.prototype.__addObject = function ( object ) {
  7817. if ( object instanceof THREE.Light ) {
  7818. if ( this.__lights.indexOf( object ) === - 1 ) {
  7819. this.__lights.push( object );
  7820. }
  7821. if ( object.target && object.target.parent === undefined ) {
  7822. this.add( object.target );
  7823. }
  7824. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  7825. if ( this.__objects.indexOf( object ) === - 1 ) {
  7826. this.__objects.push( object );
  7827. this.__objectsAdded.push( object );
  7828. // check if previously removed
  7829. var i = this.__objectsRemoved.indexOf( object );
  7830. if ( i !== -1 ) {
  7831. this.__objectsRemoved.splice( i, 1 );
  7832. }
  7833. }
  7834. }
  7835. for ( var c = 0; c < object.children.length; c ++ ) {
  7836. this.__addObject( object.children[ c ] );
  7837. }
  7838. };
  7839. THREE.Scene.prototype.__removeObject = function ( object ) {
  7840. if ( object instanceof THREE.Light ) {
  7841. var i = this.__lights.indexOf( object );
  7842. if ( i !== -1 ) {
  7843. this.__lights.splice( i, 1 );
  7844. }
  7845. } else if ( !( object instanceof THREE.Camera ) ) {
  7846. var i = this.__objects.indexOf( object );
  7847. if( i !== -1 ) {
  7848. this.__objects.splice( i, 1 );
  7849. this.__objectsRemoved.push( object );
  7850. // check if previously added
  7851. var ai = this.__objectsAdded.indexOf( object );
  7852. if ( ai !== -1 ) {
  7853. this.__objectsAdded.splice( ai, 1 );
  7854. }
  7855. }
  7856. }
  7857. for ( var c = 0; c < object.children.length; c ++ ) {
  7858. this.__removeObject( object.children[ c ] );
  7859. }
  7860. };
  7861. /**
  7862. * @author mrdoob / http://mrdoob.com/
  7863. * @author alteredq / http://alteredqualia.com/
  7864. */
  7865. THREE.Fog = function ( hex, near, far ) {
  7866. this.name = '';
  7867. this.color = new THREE.Color( hex );
  7868. this.near = ( near !== undefined ) ? near : 1;
  7869. this.far = ( far !== undefined ) ? far : 1000;
  7870. };
  7871. THREE.Fog.prototype.clone = function () {
  7872. return new THREE.Fog( this.color.getHex(), this.near, this.far );
  7873. };
  7874. /**
  7875. * @author mrdoob / http://mrdoob.com/
  7876. * @author alteredq / http://alteredqualia.com/
  7877. */
  7878. THREE.FogExp2 = function ( hex, density ) {
  7879. this.name = '';
  7880. this.color = new THREE.Color( hex );
  7881. this.density = ( density !== undefined ) ? density : 0.00025;
  7882. };
  7883. THREE.FogExp2.prototype.clone = function () {
  7884. return new THREE.FogExp2( this.color.getHex(), this.density );
  7885. };
  7886. /**
  7887. * @author mrdoob / http://mrdoob.com/
  7888. */
  7889. THREE.CanvasRenderer = function ( parameters ) {
  7890. console.log( 'THREE.CanvasRenderer', THREE.REVISION );
  7891. parameters = parameters || {};
  7892. var _this = this,
  7893. _renderData, _elements, _lights,
  7894. _projector = new THREE.Projector(),
  7895. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  7896. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  7897. _context = _canvas.getContext( '2d' ),
  7898. _clearColor = new THREE.Color( 0x000000 ),
  7899. _clearOpacity = 0,
  7900. _contextGlobalAlpha = 1,
  7901. _contextGlobalCompositeOperation = 0,
  7902. _contextStrokeStyle = null,
  7903. _contextFillStyle = null,
  7904. _contextLineWidth = null,
  7905. _contextLineCap = null,
  7906. _contextLineJoin = null,
  7907. _v1, _v2, _v3, _v4,
  7908. _v5 = new THREE.RenderableVertex(),
  7909. _v6 = new THREE.RenderableVertex(),
  7910. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  7911. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  7912. _color = new THREE.Color(),
  7913. _color1 = new THREE.Color(),
  7914. _color2 = new THREE.Color(),
  7915. _color3 = new THREE.Color(),
  7916. _color4 = new THREE.Color(),
  7917. _diffuseColor = new THREE.Color(),
  7918. _emissiveColor = new THREE.Color(),
  7919. _patterns = {}, _imagedatas = {},
  7920. _near, _far,
  7921. _image, _uvs,
  7922. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  7923. _clipRect = new THREE.Rectangle(),
  7924. _clearRect = new THREE.Rectangle(),
  7925. _bboxRect = new THREE.Rectangle(),
  7926. _enableLighting = false,
  7927. _ambientLight = new THREE.Color(),
  7928. _directionalLights = new THREE.Color(),
  7929. _pointLights = new THREE.Color(),
  7930. _pi2 = Math.PI * 2,
  7931. _vector3 = new THREE.Vector3(), // Needed for PointLight
  7932. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  7933. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  7934. _pixelMap = document.createElement( 'canvas' );
  7935. _pixelMap.width = _pixelMap.height = 2;
  7936. _pixelMapContext = _pixelMap.getContext( '2d' );
  7937. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  7938. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  7939. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  7940. _pixelMapData = _pixelMapImage.data;
  7941. _gradientMap = document.createElement( 'canvas' );
  7942. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  7943. _gradientMapContext = _gradientMap.getContext( '2d' );
  7944. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  7945. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  7946. _gradientMapQuality --; // Fix UVs
  7947. this.domElement = _canvas;
  7948. this.autoClear = true;
  7949. this.sortObjects = true;
  7950. this.sortElements = true;
  7951. this.info = {
  7952. render: {
  7953. vertices: 0,
  7954. faces: 0
  7955. }
  7956. }
  7957. this.setSize = function ( width, height ) {
  7958. _canvasWidth = width;
  7959. _canvasHeight = height;
  7960. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  7961. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  7962. _canvas.width = _canvasWidth;
  7963. _canvas.height = _canvasHeight;
  7964. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7965. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7966. _contextGlobalAlpha = 1;
  7967. _contextGlobalCompositeOperation = 0;
  7968. _contextStrokeStyle = null;
  7969. _contextFillStyle = null;
  7970. _contextLineWidth = null;
  7971. _contextLineCap = null;
  7972. _contextLineJoin = null;
  7973. };
  7974. this.setClearColor = function ( color, opacity ) {
  7975. _clearColor.copy( color );
  7976. _clearOpacity = opacity !== undefined ? opacity : 1;
  7977. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7978. };
  7979. this.setClearColorHex = function ( hex, opacity ) {
  7980. _clearColor.setHex( hex );
  7981. _clearOpacity = opacity !== undefined ? opacity : 1;
  7982. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  7983. };
  7984. this.getMaxAnisotropy = function () {
  7985. return 0;
  7986. };
  7987. this.clear = function () {
  7988. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  7989. if ( _clearRect.isEmpty() === false ) {
  7990. _clearRect.minSelf( _clipRect );
  7991. _clearRect.inflate( 2 );
  7992. if ( _clearOpacity < 1 ) {
  7993. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  7994. }
  7995. if ( _clearOpacity > 0 ) {
  7996. setBlending( THREE.NormalBlending );
  7997. setOpacity( 1 );
  7998. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  7999. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  8000. }
  8001. _clearRect.empty();
  8002. }
  8003. };
  8004. this.render = function ( scene, camera ) {
  8005. if ( camera instanceof THREE.Camera === false ) {
  8006. console.error( 'THREE.CanvasRenderer.render: camera is not an instance of THREE.Camera.' );
  8007. return;
  8008. }
  8009. var e, el, element, material;
  8010. this.autoClear === true
  8011. ? this.clear()
  8012. : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  8013. _this.info.render.vertices = 0;
  8014. _this.info.render.faces = 0;
  8015. _renderData = _projector.projectScene( scene, camera, this.sortObjects, this.sortElements );
  8016. _elements = _renderData.elements;
  8017. _lights = _renderData.lights;
  8018. /* DEBUG
  8019. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  8020. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  8021. */
  8022. _enableLighting = _lights.length > 0;
  8023. if ( _enableLighting === true ) {
  8024. calculateLights();
  8025. }
  8026. for ( e = 0, el = _elements.length; e < el; e++ ) {
  8027. element = _elements[ e ];
  8028. material = element.material;
  8029. if ( material === undefined || material.visible === false ) continue;
  8030. _bboxRect.empty();
  8031. if ( element instanceof THREE.RenderableParticle ) {
  8032. _v1 = element;
  8033. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  8034. renderParticle( _v1, element, material, scene );
  8035. } else if ( element instanceof THREE.RenderableLine ) {
  8036. _v1 = element.v1; _v2 = element.v2;
  8037. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8038. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8039. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  8040. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  8041. if ( _clipRect.intersects( _bboxRect ) === true ) {
  8042. renderLine( _v1, _v2, element, material, scene );
  8043. }
  8044. } else if ( element instanceof THREE.RenderableFace3 ) {
  8045. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  8046. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8047. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8048. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8049. if ( material.overdraw === true ) {
  8050. expand( _v1.positionScreen, _v2.positionScreen );
  8051. expand( _v2.positionScreen, _v3.positionScreen );
  8052. expand( _v3.positionScreen, _v1.positionScreen );
  8053. }
  8054. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  8055. _v2.positionScreen.x, _v2.positionScreen.y,
  8056. _v3.positionScreen.x, _v3.positionScreen.y );
  8057. if ( _clipRect.intersects( _bboxRect ) === true ) {
  8058. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  8059. }
  8060. } else if ( element instanceof THREE.RenderableFace4 ) {
  8061. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  8062. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  8063. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  8064. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  8065. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  8066. _v5.positionScreen.copy( _v2.positionScreen );
  8067. _v6.positionScreen.copy( _v4.positionScreen );
  8068. if ( material.overdraw === true ) {
  8069. expand( _v1.positionScreen, _v2.positionScreen );
  8070. expand( _v2.positionScreen, _v4.positionScreen );
  8071. expand( _v4.positionScreen, _v1.positionScreen );
  8072. expand( _v3.positionScreen, _v5.positionScreen );
  8073. expand( _v3.positionScreen, _v6.positionScreen );
  8074. }
  8075. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  8076. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  8077. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  8078. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  8079. if ( _clipRect.intersects( _bboxRect ) === true ) {
  8080. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  8081. }
  8082. }
  8083. /* DEBUG
  8084. _context.lineWidth = 1;
  8085. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  8086. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  8087. */
  8088. _clearRect.addRectangle( _bboxRect );
  8089. }
  8090. /* DEBUG
  8091. _context.lineWidth = 1;
  8092. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  8093. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  8094. */
  8095. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  8096. //
  8097. function calculateLights() {
  8098. _ambientLight.setRGB( 0, 0, 0 );
  8099. _directionalLights.setRGB( 0, 0, 0 );
  8100. _pointLights.setRGB( 0, 0, 0 );
  8101. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8102. var light = _lights[ l ];
  8103. var lightColor = light.color;
  8104. if ( light instanceof THREE.AmbientLight ) {
  8105. _ambientLight.r += lightColor.r;
  8106. _ambientLight.g += lightColor.g;
  8107. _ambientLight.b += lightColor.b;
  8108. } else if ( light instanceof THREE.DirectionalLight ) {
  8109. // for particles
  8110. _directionalLights.r += lightColor.r;
  8111. _directionalLights.g += lightColor.g;
  8112. _directionalLights.b += lightColor.b;
  8113. } else if ( light instanceof THREE.PointLight ) {
  8114. // for particles
  8115. _pointLights.r += lightColor.r;
  8116. _pointLights.g += lightColor.g;
  8117. _pointLights.b += lightColor.b;
  8118. }
  8119. }
  8120. }
  8121. function calculateLight( position, normal, color ) {
  8122. for ( var l = 0, ll = _lights.length; l < ll; l ++ ) {
  8123. var light = _lights[ l ];
  8124. var lightColor = light.color;
  8125. if ( light instanceof THREE.DirectionalLight ) {
  8126. var lightPosition = light.matrixWorld.getPosition().normalize();
  8127. var amount = normal.dot( lightPosition );
  8128. if ( amount <= 0 ) continue;
  8129. amount *= light.intensity;
  8130. color.r += lightColor.r * amount;
  8131. color.g += lightColor.g * amount;
  8132. color.b += lightColor.b * amount;
  8133. } else if ( light instanceof THREE.PointLight ) {
  8134. var lightPosition = light.matrixWorld.getPosition();
  8135. var amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  8136. if ( amount <= 0 ) continue;
  8137. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  8138. if ( amount == 0 ) continue;
  8139. amount *= light.intensity;
  8140. color.r += lightColor.r * amount;
  8141. color.g += lightColor.g * amount;
  8142. color.b += lightColor.b * amount;
  8143. }
  8144. }
  8145. }
  8146. function renderParticle( v1, element, material, scene ) {
  8147. setOpacity( material.opacity );
  8148. setBlending( material.blending );
  8149. var width, height, scaleX, scaleY,
  8150. bitmap, bitmapWidth, bitmapHeight;
  8151. if ( material instanceof THREE.ParticleBasicMaterial ) {
  8152. if ( material.map === null ) {
  8153. scaleX = element.object.scale.x;
  8154. scaleY = element.object.scale.y;
  8155. // TODO: Be able to disable this
  8156. scaleX *= element.scale.x * _canvasWidthHalf;
  8157. scaleY *= element.scale.y * _canvasHeightHalf;
  8158. _bboxRect.set( v1.x - scaleX, v1.y - scaleY, v1.x + scaleX, v1.y + scaleY );
  8159. if ( _clipRect.intersects( _bboxRect ) === false ) {
  8160. return;
  8161. }
  8162. setFillStyle( material.color.getStyle() );
  8163. _context.save();
  8164. _context.translate( v1.x, v1.y );
  8165. _context.rotate( - element.rotation );
  8166. _context.scale( scaleX, scaleY );
  8167. _context.fillRect( -1, -1, 2, 2 );
  8168. _context.restore();
  8169. } else {
  8170. bitmap = material.map.image;
  8171. bitmapWidth = bitmap.width >> 1;
  8172. bitmapHeight = bitmap.height >> 1;
  8173. scaleX = element.scale.x * _canvasWidthHalf;
  8174. scaleY = element.scale.y * _canvasHeightHalf;
  8175. width = scaleX * bitmapWidth;
  8176. height = scaleY * bitmapHeight;
  8177. // TODO: Rotations break this...
  8178. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  8179. if ( _clipRect.intersects( _bboxRect ) === false ) {
  8180. return;
  8181. }
  8182. _context.save();
  8183. _context.translate( v1.x, v1.y );
  8184. _context.rotate( - element.rotation );
  8185. _context.scale( scaleX, - scaleY );
  8186. _context.translate( - bitmapWidth, - bitmapHeight );
  8187. _context.drawImage( bitmap, 0, 0 );
  8188. _context.restore();
  8189. }
  8190. /* DEBUG
  8191. setStrokeStyle( 'rgb(255,255,0)' );
  8192. _context.beginPath();
  8193. _context.moveTo( v1.x - 10, v1.y );
  8194. _context.lineTo( v1.x + 10, v1.y );
  8195. _context.moveTo( v1.x, v1.y - 10 );
  8196. _context.lineTo( v1.x, v1.y + 10 );
  8197. _context.stroke();
  8198. */
  8199. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  8200. width = element.scale.x * _canvasWidthHalf;
  8201. height = element.scale.y * _canvasHeightHalf;
  8202. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  8203. if ( _clipRect.intersects( _bboxRect ) === false ) {
  8204. return;
  8205. }
  8206. setStrokeStyle( material.color.getStyle() );
  8207. setFillStyle( material.color.getStyle() );
  8208. _context.save();
  8209. _context.translate( v1.x, v1.y );
  8210. _context.rotate( - element.rotation );
  8211. _context.scale( width, height );
  8212. material.program( _context );
  8213. _context.restore();
  8214. }
  8215. }
  8216. function renderLine( v1, v2, element, material, scene ) {
  8217. setOpacity( material.opacity );
  8218. setBlending( material.blending );
  8219. _context.beginPath();
  8220. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  8221. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  8222. if ( material instanceof THREE.LineBasicMaterial ) {
  8223. setLineWidth( material.linewidth );
  8224. setLineCap( material.linecap );
  8225. setLineJoin( material.linejoin );
  8226. setStrokeStyle( material.color.getStyle() );
  8227. _context.stroke();
  8228. _bboxRect.inflate( material.linewidth * 2 );
  8229. }
  8230. }
  8231. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  8232. _this.info.render.vertices += 3;
  8233. _this.info.render.faces ++;
  8234. setOpacity( material.opacity );
  8235. setBlending( material.blending );
  8236. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8237. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8238. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8239. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  8240. if ( ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) && material.map === null && material.map === null ) {
  8241. _diffuseColor.copy( material.color );
  8242. _emissiveColor.copy( material.emissive );
  8243. if ( material.vertexColors === THREE.FaceColors ) {
  8244. _diffuseColor.r *= element.color.r;
  8245. _diffuseColor.g *= element.color.g;
  8246. _diffuseColor.b *= element.color.b;
  8247. }
  8248. if ( _enableLighting === true ) {
  8249. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 3 ) {
  8250. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  8251. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  8252. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  8253. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  8254. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  8255. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  8256. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8257. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8258. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8259. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8260. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8261. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8262. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8263. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8264. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8265. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8266. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8267. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8268. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8269. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8270. } else {
  8271. _color.r = _ambientLight.r;
  8272. _color.g = _ambientLight.g;
  8273. _color.b = _ambientLight.b;
  8274. calculateLight( element.centroidWorld, element.normalWorld, _color );
  8275. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8276. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8277. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8278. material.wireframe === true
  8279. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8280. : fillPath( _color );
  8281. }
  8282. } else {
  8283. material.wireframe === true
  8284. ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8285. : fillPath( material.color );
  8286. }
  8287. } else if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8288. if ( material.map !== null ) {
  8289. if ( material.map.mapping instanceof THREE.UVMapping ) {
  8290. _uvs = element.uvs[ 0 ];
  8291. 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 );
  8292. }
  8293. } else if ( material.envMap !== null ) {
  8294. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  8295. var cameraMatrix = camera.matrixWorldInverse;
  8296. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  8297. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8298. _uv1y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8299. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  8300. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8301. _uv2y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8302. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  8303. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  8304. _uv3y = ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  8305. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  8306. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  8307. }*/
  8308. } else {
  8309. _color.copy( material.color );
  8310. if ( material.vertexColors === THREE.FaceColors ) {
  8311. _color.r *= element.color.r;
  8312. _color.g *= element.color.g;
  8313. _color.b *= element.color.b;
  8314. }
  8315. material.wireframe === true
  8316. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8317. : fillPath( _color );
  8318. }
  8319. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8320. _near = camera.near;
  8321. _far = camera.far;
  8322. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8323. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8324. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8325. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  8326. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  8327. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  8328. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8329. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  8330. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8331. _color.r = normalToComponent( element.normalWorld.x );
  8332. _color.g = normalToComponent( element.normalWorld.y );
  8333. _color.b = normalToComponent( element.normalWorld.z );
  8334. material.wireframe === true
  8335. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8336. : fillPath( _color );
  8337. }
  8338. }
  8339. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  8340. _this.info.render.vertices += 4;
  8341. _this.info.render.faces ++;
  8342. setOpacity( material.opacity );
  8343. setBlending( material.blending );
  8344. if ( ( material.map !== undefined && material.map !== null ) || ( material.envMap !== undefined && material.envMap !== null ) ) {
  8345. // Let renderFace3() handle this
  8346. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  8347. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  8348. return;
  8349. }
  8350. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  8351. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  8352. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  8353. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  8354. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  8355. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  8356. if ( material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial ) {
  8357. _diffuseColor.copy( material.color );
  8358. _emissiveColor.copy( material.emissive );
  8359. if ( material.vertexColors === THREE.FaceColors ) {
  8360. _diffuseColor.r *= element.color.r;
  8361. _diffuseColor.g *= element.color.g;
  8362. _diffuseColor.b *= element.color.b;
  8363. }
  8364. if ( _enableLighting === true ) {
  8365. if ( material.wireframe === false && material.shading == THREE.SmoothShading && element.vertexNormalsLength == 4 ) {
  8366. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  8367. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  8368. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  8369. calculateLight( element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  8370. calculateLight( element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  8371. calculateLight( element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  8372. calculateLight( element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  8373. _color1.r = _color1.r * _diffuseColor.r + _emissiveColor.r;
  8374. _color1.g = _color1.g * _diffuseColor.g + _emissiveColor.g;
  8375. _color1.b = _color1.b * _diffuseColor.b + _emissiveColor.b;
  8376. _color2.r = _color2.r * _diffuseColor.r + _emissiveColor.r;
  8377. _color2.g = _color2.g * _diffuseColor.g + _emissiveColor.g;
  8378. _color2.b = _color2.b * _diffuseColor.b + _emissiveColor.b;
  8379. _color3.r = _color3.r * _diffuseColor.r + _emissiveColor.r;
  8380. _color3.g = _color3.g * _diffuseColor.g + _emissiveColor.g;
  8381. _color3.b = _color3.b * _diffuseColor.b + _emissiveColor.b;
  8382. _color4.r = _color4.r * _diffuseColor.r + _emissiveColor.r;
  8383. _color4.g = _color4.g * _diffuseColor.g + _emissiveColor.g;
  8384. _color4.b = _color4.b * _diffuseColor.b + _emissiveColor.b;
  8385. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8386. // TODO: UVs are incorrect, v4->v3?
  8387. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8388. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8389. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8390. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8391. } else {
  8392. _color.r = _ambientLight.r;
  8393. _color.g = _ambientLight.g;
  8394. _color.b = _ambientLight.b;
  8395. calculateLight( element.centroidWorld, element.normalWorld, _color );
  8396. _color.r = _color.r * _diffuseColor.r + _emissiveColor.r;
  8397. _color.g = _color.g * _diffuseColor.g + _emissiveColor.g;
  8398. _color.b = _color.b * _diffuseColor.b + _emissiveColor.b;
  8399. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8400. material.wireframe === true
  8401. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8402. : fillPath( _color );
  8403. }
  8404. } else {
  8405. _color.r = _diffuseColor.r + _emissiveColor.r;
  8406. _color.g = _diffuseColor.g + _emissiveColor.g;
  8407. _color.b = _diffuseColor.b + _emissiveColor.b;
  8408. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8409. material.wireframe === true
  8410. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8411. : fillPath( _color );
  8412. }
  8413. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8414. _color.copy( material.color );
  8415. if ( material.vertexColors === THREE.FaceColors ) {
  8416. _color.r *= element.color.r;
  8417. _color.g *= element.color.g;
  8418. _color.b *= element.color.b;
  8419. }
  8420. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8421. material.wireframe === true
  8422. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8423. : fillPath( _color );
  8424. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8425. _color.r = normalToComponent( element.normalWorld.x );
  8426. _color.g = normalToComponent( element.normalWorld.y );
  8427. _color.b = normalToComponent( element.normalWorld.z );
  8428. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  8429. material.wireframe === true
  8430. ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin )
  8431. : fillPath( _color );
  8432. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8433. _near = camera.near;
  8434. _far = camera.far;
  8435. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  8436. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  8437. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  8438. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  8439. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  8440. // TODO: UVs are incorrect, v4->v3?
  8441. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  8442. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  8443. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  8444. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  8445. }
  8446. }
  8447. //
  8448. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  8449. _context.beginPath();
  8450. _context.moveTo( x0, y0 );
  8451. _context.lineTo( x1, y1 );
  8452. _context.lineTo( x2, y2 );
  8453. _context.closePath();
  8454. }
  8455. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  8456. _context.beginPath();
  8457. _context.moveTo( x0, y0 );
  8458. _context.lineTo( x1, y1 );
  8459. _context.lineTo( x2, y2 );
  8460. _context.lineTo( x3, y3 );
  8461. _context.closePath();
  8462. }
  8463. function strokePath( color, linewidth, linecap, linejoin ) {
  8464. setLineWidth( linewidth );
  8465. setLineCap( linecap );
  8466. setLineJoin( linejoin );
  8467. setStrokeStyle( color.getStyle() );
  8468. _context.stroke();
  8469. _bboxRect.inflate( linewidth * 2 );
  8470. }
  8471. function fillPath( color ) {
  8472. setFillStyle( color.getStyle() );
  8473. _context.fill();
  8474. }
  8475. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  8476. if ( texture instanceof THREE.DataTexture || texture.image === undefined || texture.image.width == 0 ) return;
  8477. if ( texture.needsUpdate === true ) {
  8478. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  8479. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  8480. _patterns[ texture.id ] = _context.createPattern(
  8481. texture.image, repeatX === true && repeatY === true
  8482. ? 'repeat'
  8483. : repeatX === true && repeatY === false
  8484. ? 'repeat-x'
  8485. : repeatX === false && repeatY === true
  8486. ? 'repeat-y'
  8487. : 'no-repeat'
  8488. );
  8489. texture.needsUpdate = false;
  8490. }
  8491. _patterns[ texture.id ] === undefined
  8492. ? setFillStyle( 'rgba(0,0,0,1)' )
  8493. : setFillStyle( _patterns[ texture.id ] );
  8494. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8495. var a, b, c, d, e, f, det, idet,
  8496. offsetX = texture.offset.x / texture.repeat.x,
  8497. offsetY = texture.offset.y / texture.repeat.y,
  8498. width = texture.image.width * texture.repeat.x,
  8499. height = texture.image.height * texture.repeat.y;
  8500. u0 = ( u0 + offsetX ) * width;
  8501. v0 = ( 1.0 - v0 + offsetY ) * height;
  8502. u1 = ( u1 + offsetX ) * width;
  8503. v1 = ( 1.0 - v1 + offsetY ) * height;
  8504. u2 = ( u2 + offsetX ) * width;
  8505. v2 = ( 1.0 - v2 + offsetY ) * height;
  8506. x1 -= x0; y1 -= y0;
  8507. x2 -= x0; y2 -= y0;
  8508. u1 -= u0; v1 -= v0;
  8509. u2 -= u0; v2 -= v0;
  8510. det = u1 * v2 - u2 * v1;
  8511. if ( det === 0 ) {
  8512. if ( _imagedatas[ texture.id ] === undefined ) {
  8513. var canvas = document.createElement( 'canvas' )
  8514. canvas.width = texture.image.width;
  8515. canvas.height = texture.image.height;
  8516. var context = canvas.getContext( '2d' );
  8517. context.drawImage( texture.image, 0, 0 );
  8518. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  8519. }
  8520. var data = _imagedatas[ texture.id ];
  8521. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  8522. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  8523. fillPath( _color );
  8524. return;
  8525. }
  8526. idet = 1 / det;
  8527. a = ( v2 * x1 - v1 * x2 ) * idet;
  8528. b = ( v2 * y1 - v1 * y2 ) * idet;
  8529. c = ( u1 * x2 - u2 * x1 ) * idet;
  8530. d = ( u1 * y2 - u2 * y1 ) * idet;
  8531. e = x0 - a * u0 - c * v0;
  8532. f = y0 - b * u0 - d * v0;
  8533. _context.save();
  8534. _context.transform( a, b, c, d, e, f );
  8535. _context.fill();
  8536. _context.restore();
  8537. }
  8538. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  8539. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  8540. var a, b, c, d, e, f, det, idet,
  8541. width = image.width - 1,
  8542. height = image.height - 1;
  8543. u0 *= width; v0 *= height;
  8544. u1 *= width; v1 *= height;
  8545. u2 *= width; v2 *= height;
  8546. x1 -= x0; y1 -= y0;
  8547. x2 -= x0; y2 -= y0;
  8548. u1 -= u0; v1 -= v0;
  8549. u2 -= u0; v2 -= v0;
  8550. det = u1 * v2 - u2 * v1;
  8551. idet = 1 / det;
  8552. a = ( v2 * x1 - v1 * x2 ) * idet;
  8553. b = ( v2 * y1 - v1 * y2 ) * idet;
  8554. c = ( u1 * x2 - u2 * x1 ) * idet;
  8555. d = ( u1 * y2 - u2 * y1 ) * idet;
  8556. e = x0 - a * u0 - c * v0;
  8557. f = y0 - b * u0 - d * v0;
  8558. _context.save();
  8559. _context.transform( a, b, c, d, e, f );
  8560. _context.clip();
  8561. _context.drawImage( image, 0, 0 );
  8562. _context.restore();
  8563. }
  8564. function getGradientTexture( color1, color2, color3, color4 ) {
  8565. // http://mrdoob.com/blog/post/710
  8566. _pixelMapData[ 0 ] = ( color1.r * 255 ) | 0;
  8567. _pixelMapData[ 1 ] = ( color1.g * 255 ) | 0;
  8568. _pixelMapData[ 2 ] = ( color1.b * 255 ) | 0;
  8569. _pixelMapData[ 4 ] = ( color2.r * 255 ) | 0;
  8570. _pixelMapData[ 5 ] = ( color2.g * 255 ) | 0;
  8571. _pixelMapData[ 6 ] = ( color2.b * 255 ) | 0;
  8572. _pixelMapData[ 8 ] = ( color3.r * 255 ) | 0;
  8573. _pixelMapData[ 9 ] = ( color3.g * 255 ) | 0;
  8574. _pixelMapData[ 10 ] = ( color3.b * 255 ) | 0;
  8575. _pixelMapData[ 12 ] = ( color4.r * 255 ) | 0;
  8576. _pixelMapData[ 13 ] = ( color4.g * 255 ) | 0;
  8577. _pixelMapData[ 14 ] = ( color4.b * 255 ) | 0;
  8578. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  8579. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  8580. return _gradientMap;
  8581. }
  8582. function smoothstep( value, min, max ) {
  8583. var x = ( value - min ) / ( max - min );
  8584. return x * x * ( 3 - 2 * x );
  8585. }
  8586. function normalToComponent( normal ) {
  8587. var component = ( normal + 1 ) * 0.5;
  8588. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  8589. }
  8590. // Hide anti-alias gaps
  8591. function expand( v1, v2 ) {
  8592. var x = v2.x - v1.x, y = v2.y - v1.y,
  8593. det = x * x + y * y, idet;
  8594. if ( det === 0 ) return;
  8595. idet = 1 / Math.sqrt( det );
  8596. x *= idet; y *= idet;
  8597. v2.x += x; v2.y += y;
  8598. v1.x -= x; v1.y -= y;
  8599. }
  8600. };
  8601. // Context cached methods.
  8602. function setOpacity( value ) {
  8603. if ( _contextGlobalAlpha !== value ) {
  8604. _context.globalAlpha = value;
  8605. _contextGlobalAlpha = value;
  8606. }
  8607. }
  8608. function setBlending( value ) {
  8609. if ( _contextGlobalCompositeOperation !== value ) {
  8610. if ( value === THREE.NormalBlending ) {
  8611. _context.globalCompositeOperation = 'source-over';
  8612. } else if ( value === THREE.AdditiveBlending ) {
  8613. _context.globalCompositeOperation = 'lighter';
  8614. } else if ( value === THREE.SubtractiveBlending ) {
  8615. _context.globalCompositeOperation = 'darker';
  8616. }
  8617. _contextGlobalCompositeOperation = value;
  8618. }
  8619. }
  8620. function setLineWidth( value ) {
  8621. if ( _contextLineWidth !== value ) {
  8622. _context.lineWidth = value;
  8623. _contextLineWidth = value;
  8624. }
  8625. }
  8626. function setLineCap( value ) {
  8627. // "butt", "round", "square"
  8628. if ( _contextLineCap !== value ) {
  8629. _context.lineCap = value;
  8630. _contextLineCap = value;
  8631. }
  8632. }
  8633. function setLineJoin( value ) {
  8634. // "round", "bevel", "miter"
  8635. if ( _contextLineJoin !== value ) {
  8636. _context.lineJoin = value;
  8637. _contextLineJoin = value;
  8638. }
  8639. }
  8640. function setStrokeStyle( value ) {
  8641. if ( _contextStrokeStyle !== value ) {
  8642. _context.strokeStyle = value;
  8643. _contextStrokeStyle = value;
  8644. }
  8645. }
  8646. function setFillStyle( value ) {
  8647. if ( _contextFillStyle !== value ) {
  8648. _context.fillStyle = value;
  8649. _contextFillStyle = value;
  8650. }
  8651. }
  8652. };
  8653. /**
  8654. * @author alteredq / http://alteredqualia.com/
  8655. * @author mrdoob / http://mrdoob.com/
  8656. * @author mikael emtinger / http://gomo.se/
  8657. */
  8658. THREE.ShaderChunk = {
  8659. // FOG
  8660. fog_pars_fragment: [
  8661. "#ifdef USE_FOG",
  8662. "uniform vec3 fogColor;",
  8663. "#ifdef FOG_EXP2",
  8664. "uniform float fogDensity;",
  8665. "#else",
  8666. "uniform float fogNear;",
  8667. "uniform float fogFar;",
  8668. "#endif",
  8669. "#endif"
  8670. ].join("\n"),
  8671. fog_fragment: [
  8672. "#ifdef USE_FOG",
  8673. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  8674. "#ifdef FOG_EXP2",
  8675. "const float LOG2 = 1.442695;",
  8676. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  8677. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  8678. "#else",
  8679. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  8680. "#endif",
  8681. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  8682. "#endif"
  8683. ].join("\n"),
  8684. // ENVIRONMENT MAP
  8685. envmap_pars_fragment: [
  8686. "#ifdef USE_ENVMAP",
  8687. "uniform float reflectivity;",
  8688. "uniform samplerCube envMap;",
  8689. "uniform float flipEnvMap;",
  8690. "uniform int combine;",
  8691. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8692. "uniform bool useRefract;",
  8693. "uniform float refractionRatio;",
  8694. "#else",
  8695. "varying vec3 vReflect;",
  8696. "#endif",
  8697. "#endif"
  8698. ].join("\n"),
  8699. envmap_fragment: [
  8700. "#ifdef USE_ENVMAP",
  8701. "vec3 reflectVec;",
  8702. "#if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP )",
  8703. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  8704. "if ( useRefract ) {",
  8705. "reflectVec = refract( cameraToVertex, normal, refractionRatio );",
  8706. "} else { ",
  8707. "reflectVec = reflect( cameraToVertex, normal );",
  8708. "}",
  8709. "#else",
  8710. "reflectVec = vReflect;",
  8711. "#endif",
  8712. "#ifdef DOUBLE_SIDED",
  8713. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  8714. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8715. "#else",
  8716. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) );",
  8717. "#endif",
  8718. "#ifdef GAMMA_INPUT",
  8719. "cubeColor.xyz *= cubeColor.xyz;",
  8720. "#endif",
  8721. "if ( combine == 1 ) {",
  8722. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularStrength * reflectivity );",
  8723. "} else if ( combine == 2 ) {",
  8724. "gl_FragColor.xyz += cubeColor.xyz * specularStrength * reflectivity;",
  8725. "} else {",
  8726. "gl_FragColor.xyz = mix( gl_FragColor.xyz, gl_FragColor.xyz * cubeColor.xyz, specularStrength * reflectivity );",
  8727. "}",
  8728. "#endif"
  8729. ].join("\n"),
  8730. envmap_pars_vertex: [
  8731. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8732. "varying vec3 vReflect;",
  8733. "uniform float refractionRatio;",
  8734. "uniform bool useRefract;",
  8735. "#endif"
  8736. ].join("\n"),
  8737. worldpos_vertex : [
  8738. "#if defined( USE_ENVMAP ) || defined( PHONG ) || defined( LAMBERT ) || defined ( USE_SHADOWMAP )",
  8739. "#ifdef USE_SKINNING",
  8740. "vec4 worldPosition = modelMatrix * skinned;",
  8741. "#endif",
  8742. "#if defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8743. "vec4 worldPosition = modelMatrix * vec4( morphed, 1.0 );",
  8744. "#endif",
  8745. "#if ! defined( USE_MORPHTARGETS ) && ! defined( USE_SKINNING )",
  8746. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  8747. "#endif",
  8748. "#endif"
  8749. ].join("\n"),
  8750. envmap_vertex : [
  8751. "#if defined( USE_ENVMAP ) && ! defined( USE_BUMPMAP ) && ! defined( USE_NORMALMAP )",
  8752. "vec3 worldNormal = mat3( modelMatrix[ 0 ].xyz, modelMatrix[ 1 ].xyz, modelMatrix[ 2 ].xyz ) * objectNormal;",
  8753. "worldNormal = normalize( worldNormal );",
  8754. "vec3 cameraToVertex = normalize( worldPosition.xyz - cameraPosition );",
  8755. "if ( useRefract ) {",
  8756. "vReflect = refract( cameraToVertex, worldNormal, refractionRatio );",
  8757. "} else {",
  8758. "vReflect = reflect( cameraToVertex, worldNormal );",
  8759. "}",
  8760. "#endif"
  8761. ].join("\n"),
  8762. // COLOR MAP (particles)
  8763. map_particle_pars_fragment: [
  8764. "#ifdef USE_MAP",
  8765. "uniform sampler2D map;",
  8766. "#endif"
  8767. ].join("\n"),
  8768. map_particle_fragment: [
  8769. "#ifdef USE_MAP",
  8770. "gl_FragColor = gl_FragColor * texture2D( map, vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y ) );",
  8771. "#endif"
  8772. ].join("\n"),
  8773. // COLOR MAP (triangles)
  8774. map_pars_vertex: [
  8775. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8776. "varying vec2 vUv;",
  8777. "uniform vec4 offsetRepeat;",
  8778. "#endif"
  8779. ].join("\n"),
  8780. map_pars_fragment: [
  8781. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8782. "varying vec2 vUv;",
  8783. "#endif",
  8784. "#ifdef USE_MAP",
  8785. "uniform sampler2D map;",
  8786. "#endif"
  8787. ].join("\n"),
  8788. map_vertex: [
  8789. "#if defined( USE_MAP ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( USE_SPECULARMAP )",
  8790. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  8791. "#endif"
  8792. ].join("\n"),
  8793. map_fragment: [
  8794. "#ifdef USE_MAP",
  8795. "vec4 texelColor = texture2D( map, vUv );",
  8796. "#ifdef GAMMA_INPUT",
  8797. "texelColor.xyz *= texelColor.xyz;",
  8798. "#endif",
  8799. "gl_FragColor = gl_FragColor * texelColor;",
  8800. "#endif"
  8801. ].join("\n"),
  8802. // LIGHT MAP
  8803. lightmap_pars_fragment: [
  8804. "#ifdef USE_LIGHTMAP",
  8805. "varying vec2 vUv2;",
  8806. "uniform sampler2D lightMap;",
  8807. "#endif"
  8808. ].join("\n"),
  8809. lightmap_pars_vertex: [
  8810. "#ifdef USE_LIGHTMAP",
  8811. "varying vec2 vUv2;",
  8812. "#endif"
  8813. ].join("\n"),
  8814. lightmap_fragment: [
  8815. "#ifdef USE_LIGHTMAP",
  8816. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  8817. "#endif"
  8818. ].join("\n"),
  8819. lightmap_vertex: [
  8820. "#ifdef USE_LIGHTMAP",
  8821. "vUv2 = uv2;",
  8822. "#endif"
  8823. ].join("\n"),
  8824. // BUMP MAP
  8825. bumpmap_pars_fragment: [
  8826. "#ifdef USE_BUMPMAP",
  8827. "uniform sampler2D bumpMap;",
  8828. "uniform float bumpScale;",
  8829. // Derivative maps - bump mapping unparametrized surfaces by Morten Mikkelsen
  8830. // http://mmikkelsen3d.blogspot.sk/2011/07/derivative-maps.html
  8831. // Evaluate the derivative of the height w.r.t. screen-space using forward differencing (listing 2)
  8832. "vec2 dHdxy_fwd() {",
  8833. "vec2 dSTdx = dFdx( vUv );",
  8834. "vec2 dSTdy = dFdy( vUv );",
  8835. "float Hll = bumpScale * texture2D( bumpMap, vUv ).x;",
  8836. "float dBx = bumpScale * texture2D( bumpMap, vUv + dSTdx ).x - Hll;",
  8837. "float dBy = bumpScale * texture2D( bumpMap, vUv + dSTdy ).x - Hll;",
  8838. "return vec2( dBx, dBy );",
  8839. "}",
  8840. "vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy ) {",
  8841. "vec3 vSigmaX = dFdx( surf_pos );",
  8842. "vec3 vSigmaY = dFdy( surf_pos );",
  8843. "vec3 vN = surf_norm;", // normalized
  8844. "vec3 R1 = cross( vSigmaY, vN );",
  8845. "vec3 R2 = cross( vN, vSigmaX );",
  8846. "float fDet = dot( vSigmaX, R1 );",
  8847. "vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 );",
  8848. "return normalize( abs( fDet ) * surf_norm - vGrad );",
  8849. "}",
  8850. "#endif"
  8851. ].join("\n"),
  8852. // NORMAL MAP
  8853. normalmap_pars_fragment: [
  8854. "#ifdef USE_NORMALMAP",
  8855. "uniform sampler2D normalMap;",
  8856. "uniform vec2 normalScale;",
  8857. // Per-Pixel Tangent Space Normal Mapping
  8858. // http://hacksoflife.blogspot.ch/2009/11/per-pixel-tangent-space-normal-mapping.html
  8859. "vec3 perturbNormal2Arb( vec3 eye_pos, vec3 surf_norm ) {",
  8860. "vec3 q0 = dFdx( eye_pos.xyz );",
  8861. "vec3 q1 = dFdy( eye_pos.xyz );",
  8862. "vec2 st0 = dFdx( vUv.st );",
  8863. "vec2 st1 = dFdy( vUv.st );",
  8864. "vec3 S = normalize( q0 * st1.t - q1 * st0.t );",
  8865. "vec3 T = normalize( -q0 * st1.s + q1 * st0.s );",
  8866. "vec3 N = normalize( surf_norm );",
  8867. "vec3 mapN = texture2D( normalMap, vUv ).xyz * 2.0 - 1.0;",
  8868. "mapN.xy = normalScale * mapN.xy;",
  8869. "mat3 tsn = mat3( S, T, N );",
  8870. "return normalize( tsn * mapN );",
  8871. "}",
  8872. "#endif"
  8873. ].join("\n"),
  8874. // SPECULAR MAP
  8875. specularmap_pars_fragment: [
  8876. "#ifdef USE_SPECULARMAP",
  8877. "uniform sampler2D specularMap;",
  8878. "#endif"
  8879. ].join("\n"),
  8880. specularmap_fragment: [
  8881. "float specularStrength;",
  8882. "#ifdef USE_SPECULARMAP",
  8883. "vec4 texelSpecular = texture2D( specularMap, vUv );",
  8884. "specularStrength = texelSpecular.r;",
  8885. "#else",
  8886. "specularStrength = 1.0;",
  8887. "#endif"
  8888. ].join("\n"),
  8889. // LIGHTS LAMBERT
  8890. lights_lambert_pars_vertex: [
  8891. "uniform vec3 ambient;",
  8892. "uniform vec3 diffuse;",
  8893. "uniform vec3 emissive;",
  8894. "uniform vec3 ambientLightColor;",
  8895. "#if MAX_DIR_LIGHTS > 0",
  8896. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  8897. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  8898. "#endif",
  8899. "#if MAX_HEMI_LIGHTS > 0",
  8900. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  8901. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  8902. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  8903. "#endif",
  8904. "#if MAX_POINT_LIGHTS > 0",
  8905. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  8906. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  8907. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  8908. "#endif",
  8909. "#if MAX_SPOT_LIGHTS > 0",
  8910. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  8911. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  8912. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  8913. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  8914. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  8915. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  8916. "#endif",
  8917. "#ifdef WRAP_AROUND",
  8918. "uniform vec3 wrapRGB;",
  8919. "#endif"
  8920. ].join("\n"),
  8921. lights_lambert_vertex: [
  8922. "vLightFront = vec3( 0.0 );",
  8923. "#ifdef DOUBLE_SIDED",
  8924. "vLightBack = vec3( 0.0 );",
  8925. "#endif",
  8926. "transformedNormal = normalize( transformedNormal );",
  8927. "#if MAX_DIR_LIGHTS > 0",
  8928. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  8929. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  8930. "vec3 dirVector = normalize( lDirection.xyz );",
  8931. "float dotProduct = dot( transformedNormal, dirVector );",
  8932. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8933. "#ifdef DOUBLE_SIDED",
  8934. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8935. "#ifdef WRAP_AROUND",
  8936. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8937. "#endif",
  8938. "#endif",
  8939. "#ifdef WRAP_AROUND",
  8940. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8941. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  8942. "#ifdef DOUBLE_SIDED",
  8943. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  8944. "#endif",
  8945. "#endif",
  8946. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  8947. "#ifdef DOUBLE_SIDED",
  8948. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  8949. "#endif",
  8950. "}",
  8951. "#endif",
  8952. "#if MAX_POINT_LIGHTS > 0",
  8953. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  8954. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  8955. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8956. "float lDistance = 1.0;",
  8957. "if ( pointLightDistance[ i ] > 0.0 )",
  8958. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  8959. "lVector = normalize( lVector );",
  8960. "float dotProduct = dot( transformedNormal, lVector );",
  8961. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8962. "#ifdef DOUBLE_SIDED",
  8963. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8964. "#ifdef WRAP_AROUND",
  8965. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8966. "#endif",
  8967. "#endif",
  8968. "#ifdef WRAP_AROUND",
  8969. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  8970. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  8971. "#ifdef DOUBLE_SIDED",
  8972. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  8973. "#endif",
  8974. "#endif",
  8975. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  8976. "#ifdef DOUBLE_SIDED",
  8977. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  8978. "#endif",
  8979. "}",
  8980. "#endif",
  8981. "#if MAX_SPOT_LIGHTS > 0",
  8982. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  8983. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  8984. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  8985. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - worldPosition.xyz ) );",
  8986. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  8987. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  8988. "float lDistance = 1.0;",
  8989. "if ( spotLightDistance[ i ] > 0.0 )",
  8990. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  8991. "lVector = normalize( lVector );",
  8992. "float dotProduct = dot( transformedNormal, lVector );",
  8993. "vec3 spotLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  8994. "#ifdef DOUBLE_SIDED",
  8995. "vec3 spotLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  8996. "#ifdef WRAP_AROUND",
  8997. "vec3 spotLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  8998. "#endif",
  8999. "#endif",
  9000. "#ifdef WRAP_AROUND",
  9001. "vec3 spotLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  9002. "spotLightWeighting = mix( spotLightWeighting, spotLightWeightingHalf, wrapRGB );",
  9003. "#ifdef DOUBLE_SIDED",
  9004. "spotLightWeightingBack = mix( spotLightWeightingBack, spotLightWeightingHalfBack, wrapRGB );",
  9005. "#endif",
  9006. "#endif",
  9007. "vLightFront += spotLightColor[ i ] * spotLightWeighting * lDistance * spotEffect;",
  9008. "#ifdef DOUBLE_SIDED",
  9009. "vLightBack += spotLightColor[ i ] * spotLightWeightingBack * lDistance * spotEffect;",
  9010. "#endif",
  9011. "}",
  9012. "}",
  9013. "#endif",
  9014. "#if MAX_HEMI_LIGHTS > 0",
  9015. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9016. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9017. "vec3 lVector = normalize( lDirection.xyz );",
  9018. "float dotProduct = dot( transformedNormal, lVector );",
  9019. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9020. "float hemiDiffuseWeightBack = -0.5 * dotProduct + 0.5;",
  9021. "vLightFront += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9022. "#ifdef DOUBLE_SIDED",
  9023. "vLightBack += mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeightBack );",
  9024. "#endif",
  9025. "}",
  9026. "#endif",
  9027. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  9028. "#ifdef DOUBLE_SIDED",
  9029. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  9030. "#endif"
  9031. ].join("\n"),
  9032. // LIGHTS PHONG
  9033. lights_phong_pars_vertex: [
  9034. "#ifndef PHONG_PER_PIXEL",
  9035. "#if MAX_POINT_LIGHTS > 0",
  9036. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9037. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9038. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9039. "#endif",
  9040. "#if MAX_SPOT_LIGHTS > 0",
  9041. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9042. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9043. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9044. "#endif",
  9045. "#endif",
  9046. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9047. "varying vec3 vWorldPosition;",
  9048. "#endif"
  9049. ].join("\n"),
  9050. lights_phong_vertex: [
  9051. "#ifndef PHONG_PER_PIXEL",
  9052. "#if MAX_POINT_LIGHTS > 0",
  9053. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9054. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9055. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9056. "float lDistance = 1.0;",
  9057. "if ( pointLightDistance[ i ] > 0.0 )",
  9058. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9059. "vPointLight[ i ] = vec4( lVector, lDistance );",
  9060. "}",
  9061. "#endif",
  9062. "#if MAX_SPOT_LIGHTS > 0",
  9063. "for( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9064. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9065. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  9066. "float lDistance = 1.0;",
  9067. "if ( spotLightDistance[ i ] > 0.0 )",
  9068. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9069. "vSpotLight[ i ] = vec4( lVector, lDistance );",
  9070. "}",
  9071. "#endif",
  9072. "#endif",
  9073. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9074. "vWorldPosition = worldPosition.xyz;",
  9075. "#endif"
  9076. ].join("\n"),
  9077. lights_phong_pars_fragment: [
  9078. "uniform vec3 ambientLightColor;",
  9079. "#if MAX_DIR_LIGHTS > 0",
  9080. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  9081. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  9082. "#endif",
  9083. "#if MAX_HEMI_LIGHTS > 0",
  9084. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  9085. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  9086. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  9087. "#endif",
  9088. "#if MAX_POINT_LIGHTS > 0",
  9089. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  9090. "#ifdef PHONG_PER_PIXEL",
  9091. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  9092. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  9093. "#else",
  9094. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  9095. "#endif",
  9096. "#endif",
  9097. "#if MAX_SPOT_LIGHTS > 0",
  9098. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  9099. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  9100. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  9101. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  9102. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  9103. "#ifdef PHONG_PER_PIXEL",
  9104. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  9105. "#else",
  9106. "varying vec4 vSpotLight[ MAX_SPOT_LIGHTS ];",
  9107. "#endif",
  9108. "#endif",
  9109. "#if MAX_SPOT_LIGHTS > 0 || defined( USE_BUMPMAP )",
  9110. "varying vec3 vWorldPosition;",
  9111. "#endif",
  9112. "#ifdef WRAP_AROUND",
  9113. "uniform vec3 wrapRGB;",
  9114. "#endif",
  9115. "varying vec3 vViewPosition;",
  9116. "varying vec3 vNormal;"
  9117. ].join("\n"),
  9118. lights_phong_fragment: [
  9119. "vec3 normal = normalize( vNormal );",
  9120. "vec3 viewPosition = normalize( vViewPosition );",
  9121. "#ifdef DOUBLE_SIDED",
  9122. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  9123. "#endif",
  9124. "#ifdef USE_NORMALMAP",
  9125. "normal = perturbNormal2Arb( -viewPosition, normal );",
  9126. "#elif defined( USE_BUMPMAP )",
  9127. "normal = perturbNormalArb( -vViewPosition, normal, dHdxy_fwd() );",
  9128. "#endif",
  9129. "#if MAX_POINT_LIGHTS > 0",
  9130. "vec3 pointDiffuse = vec3( 0.0 );",
  9131. "vec3 pointSpecular = vec3( 0.0 );",
  9132. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  9133. "#ifdef PHONG_PER_PIXEL",
  9134. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  9135. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9136. "float lDistance = 1.0;",
  9137. "if ( pointLightDistance[ i ] > 0.0 )",
  9138. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  9139. "lVector = normalize( lVector );",
  9140. "#else",
  9141. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  9142. "float lDistance = vPointLight[ i ].w;",
  9143. "#endif",
  9144. // diffuse
  9145. "float dotProduct = dot( normal, lVector );",
  9146. "#ifdef WRAP_AROUND",
  9147. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  9148. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9149. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  9150. "#else",
  9151. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  9152. "#endif",
  9153. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  9154. // specular
  9155. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  9156. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  9157. "float pointSpecularWeight = specularStrength * max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  9158. "#ifdef PHYSICALLY_BASED_SHADING",
  9159. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9160. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9161. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  9162. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  9163. "#else",
  9164. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  9165. "#endif",
  9166. "}",
  9167. "#endif",
  9168. "#if MAX_SPOT_LIGHTS > 0",
  9169. "vec3 spotDiffuse = vec3( 0.0 );",
  9170. "vec3 spotSpecular = vec3( 0.0 );",
  9171. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  9172. "#ifdef PHONG_PER_PIXEL",
  9173. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  9174. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  9175. "float lDistance = 1.0;",
  9176. "if ( spotLightDistance[ i ] > 0.0 )",
  9177. "lDistance = 1.0 - min( ( length( lVector ) / spotLightDistance[ i ] ), 1.0 );",
  9178. "lVector = normalize( lVector );",
  9179. "#else",
  9180. "vec3 lVector = normalize( vSpotLight[ i ].xyz );",
  9181. "float lDistance = vSpotLight[ i ].w;",
  9182. "#endif",
  9183. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  9184. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  9185. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  9186. // diffuse
  9187. "float dotProduct = dot( normal, lVector );",
  9188. "#ifdef WRAP_AROUND",
  9189. "float spotDiffuseWeightFull = max( dotProduct, 0.0 );",
  9190. "float spotDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9191. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  9192. "#else",
  9193. "float spotDiffuseWeight = max( dotProduct, 0.0 );",
  9194. "#endif",
  9195. "spotDiffuse += diffuse * spotLightColor[ i ] * spotDiffuseWeight * lDistance * spotEffect;",
  9196. // specular
  9197. "vec3 spotHalfVector = normalize( lVector + viewPosition );",
  9198. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  9199. "float spotSpecularWeight = specularStrength * max( pow( spotDotNormalHalf, shininess ), 0.0 );",
  9200. "#ifdef PHYSICALLY_BASED_SHADING",
  9201. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9202. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9203. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, spotHalfVector ), 5.0 );",
  9204. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * specularNormalization * spotEffect;",
  9205. "#else",
  9206. "spotSpecular += specular * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * lDistance * spotEffect;",
  9207. "#endif",
  9208. "}",
  9209. "}",
  9210. "#endif",
  9211. "#if MAX_DIR_LIGHTS > 0",
  9212. "vec3 dirDiffuse = vec3( 0.0 );",
  9213. "vec3 dirSpecular = vec3( 0.0 );" ,
  9214. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  9215. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  9216. "vec3 dirVector = normalize( lDirection.xyz );",
  9217. // diffuse
  9218. "float dotProduct = dot( normal, dirVector );",
  9219. "#ifdef WRAP_AROUND",
  9220. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  9221. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  9222. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  9223. "#else",
  9224. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  9225. "#endif",
  9226. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  9227. // specular
  9228. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  9229. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  9230. "float dirSpecularWeight = specularStrength * max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  9231. "#ifdef PHYSICALLY_BASED_SHADING",
  9232. /*
  9233. // fresnel term from skin shader
  9234. "const float F0 = 0.128;",
  9235. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  9236. "float exponential = pow( base, 5.0 );",
  9237. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  9238. */
  9239. /*
  9240. // fresnel term from fresnel shader
  9241. "const float mFresnelBias = 0.08;",
  9242. "const float mFresnelScale = 0.3;",
  9243. "const float mFresnelPower = 5.0;",
  9244. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  9245. */
  9246. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9247. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9248. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  9249. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  9250. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  9251. "#else",
  9252. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  9253. "#endif",
  9254. "}",
  9255. "#endif",
  9256. "#if MAX_HEMI_LIGHTS > 0",
  9257. "vec3 hemiDiffuse = vec3( 0.0 );",
  9258. "vec3 hemiSpecular = vec3( 0.0 );" ,
  9259. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  9260. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  9261. "vec3 lVector = normalize( lDirection.xyz );",
  9262. // diffuse
  9263. "float dotProduct = dot( normal, lVector );",
  9264. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  9265. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  9266. "hemiDiffuse += diffuse * hemiColor;",
  9267. // specular (sky light)
  9268. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  9269. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  9270. "float hemiSpecularWeightSky = specularStrength * max( pow( hemiDotNormalHalfSky, shininess ), 0.0 );",
  9271. // specular (ground light)
  9272. "vec3 lVectorGround = -lVector;",
  9273. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  9274. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  9275. "float hemiSpecularWeightGround = specularStrength * max( pow( hemiDotNormalHalfGround, shininess ), 0.0 );",
  9276. "#ifdef PHYSICALLY_BASED_SHADING",
  9277. "float dotProductGround = dot( normal, lVectorGround );",
  9278. // 2.0 => 2.0001 is hack to work around ANGLE bug
  9279. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  9280. "vec3 schlickSky = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  9281. "vec3 schlickGround = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  9282. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  9283. "#else",
  9284. "hemiSpecular += specular * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  9285. "#endif",
  9286. "}",
  9287. "#endif",
  9288. "vec3 totalDiffuse = vec3( 0.0 );",
  9289. "vec3 totalSpecular = vec3( 0.0 );",
  9290. "#if MAX_DIR_LIGHTS > 0",
  9291. "totalDiffuse += dirDiffuse;",
  9292. "totalSpecular += dirSpecular;",
  9293. "#endif",
  9294. "#if MAX_HEMI_LIGHTS > 0",
  9295. "totalDiffuse += hemiDiffuse;",
  9296. "totalSpecular += hemiSpecular;",
  9297. "#endif",
  9298. "#if MAX_POINT_LIGHTS > 0",
  9299. "totalDiffuse += pointDiffuse;",
  9300. "totalSpecular += pointSpecular;",
  9301. "#endif",
  9302. "#if MAX_SPOT_LIGHTS > 0",
  9303. "totalDiffuse += spotDiffuse;",
  9304. "totalSpecular += spotSpecular;",
  9305. "#endif",
  9306. "#ifdef METAL",
  9307. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  9308. "#else",
  9309. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  9310. "#endif"
  9311. ].join("\n"),
  9312. // VERTEX COLORS
  9313. color_pars_fragment: [
  9314. "#ifdef USE_COLOR",
  9315. "varying vec3 vColor;",
  9316. "#endif"
  9317. ].join("\n"),
  9318. color_fragment: [
  9319. "#ifdef USE_COLOR",
  9320. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  9321. "#endif"
  9322. ].join("\n"),
  9323. color_pars_vertex: [
  9324. "#ifdef USE_COLOR",
  9325. "varying vec3 vColor;",
  9326. "#endif"
  9327. ].join("\n"),
  9328. color_vertex: [
  9329. "#ifdef USE_COLOR",
  9330. "#ifdef GAMMA_INPUT",
  9331. "vColor = color * color;",
  9332. "#else",
  9333. "vColor = color;",
  9334. "#endif",
  9335. "#endif"
  9336. ].join("\n"),
  9337. // SKINNING
  9338. skinning_pars_vertex: [
  9339. "#ifdef USE_SKINNING",
  9340. "#ifdef BONE_TEXTURE",
  9341. "uniform sampler2D boneTexture;",
  9342. "mat4 getBoneMatrix( const in float i ) {",
  9343. "float j = i * 4.0;",
  9344. "float x = mod( j, N_BONE_PIXEL_X );",
  9345. "float y = floor( j / N_BONE_PIXEL_X );",
  9346. "const float dx = 1.0 / N_BONE_PIXEL_X;",
  9347. "const float dy = 1.0 / N_BONE_PIXEL_Y;",
  9348. "y = dy * ( y + 0.5 );",
  9349. "vec4 v1 = texture2D( boneTexture, vec2( dx * ( x + 0.5 ), y ) );",
  9350. "vec4 v2 = texture2D( boneTexture, vec2( dx * ( x + 1.5 ), y ) );",
  9351. "vec4 v3 = texture2D( boneTexture, vec2( dx * ( x + 2.5 ), y ) );",
  9352. "vec4 v4 = texture2D( boneTexture, vec2( dx * ( x + 3.5 ), y ) );",
  9353. "mat4 bone = mat4( v1, v2, v3, v4 );",
  9354. "return bone;",
  9355. "}",
  9356. "#else",
  9357. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  9358. "mat4 getBoneMatrix( const in float i ) {",
  9359. "mat4 bone = boneGlobalMatrices[ int(i) ];",
  9360. "return bone;",
  9361. "}",
  9362. "#endif",
  9363. "#endif"
  9364. ].join("\n"),
  9365. skinbase_vertex: [
  9366. "#ifdef USE_SKINNING",
  9367. "mat4 boneMatX = getBoneMatrix( skinIndex.x );",
  9368. "mat4 boneMatY = getBoneMatrix( skinIndex.y );",
  9369. "#endif"
  9370. ].join("\n"),
  9371. skinning_vertex: [
  9372. "#ifdef USE_SKINNING",
  9373. "#ifdef USE_MORPHTARGETS",
  9374. "vec4 skinVertex = vec4( morphed, 1.0 );",
  9375. "#else",
  9376. "vec4 skinVertex = vec4( position, 1.0 );",
  9377. "#endif",
  9378. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  9379. "skinned += boneMatY * skinVertex * skinWeight.y;",
  9380. "#endif"
  9381. ].join("\n"),
  9382. // MORPHING
  9383. morphtarget_pars_vertex: [
  9384. "#ifdef USE_MORPHTARGETS",
  9385. "#ifndef USE_MORPHNORMALS",
  9386. "uniform float morphTargetInfluences[ 8 ];",
  9387. "#else",
  9388. "uniform float morphTargetInfluences[ 4 ];",
  9389. "#endif",
  9390. "#endif"
  9391. ].join("\n"),
  9392. morphtarget_vertex: [
  9393. "#ifdef USE_MORPHTARGETS",
  9394. "vec3 morphed = vec3( 0.0 );",
  9395. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  9396. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  9397. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  9398. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  9399. "#ifndef USE_MORPHNORMALS",
  9400. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  9401. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  9402. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  9403. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  9404. "#endif",
  9405. "morphed += position;",
  9406. "#endif"
  9407. ].join("\n"),
  9408. default_vertex : [
  9409. "vec4 mvPosition;",
  9410. "#ifdef USE_SKINNING",
  9411. "mvPosition = modelViewMatrix * skinned;",
  9412. "#endif",
  9413. "#if !defined( USE_SKINNING ) && defined( USE_MORPHTARGETS )",
  9414. "mvPosition = modelViewMatrix * vec4( morphed, 1.0 );",
  9415. "#endif",
  9416. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHTARGETS )",
  9417. "mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9418. "#endif",
  9419. "gl_Position = projectionMatrix * mvPosition;"
  9420. ].join("\n"),
  9421. morphnormal_vertex: [
  9422. "#ifdef USE_MORPHNORMALS",
  9423. "vec3 morphedNormal = vec3( 0.0 );",
  9424. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  9425. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  9426. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  9427. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  9428. "morphedNormal += normal;",
  9429. "#endif"
  9430. ].join("\n"),
  9431. skinnormal_vertex: [
  9432. "#ifdef USE_SKINNING",
  9433. "mat4 skinMatrix = skinWeight.x * boneMatX;",
  9434. "skinMatrix += skinWeight.y * boneMatY;",
  9435. "#ifdef USE_MORPHNORMALS",
  9436. "vec4 skinnedNormal = skinMatrix * vec4( morphedNormal, 0.0 );",
  9437. "#else",
  9438. "vec4 skinnedNormal = skinMatrix * vec4( normal, 0.0 );",
  9439. "#endif",
  9440. "#endif"
  9441. ].join("\n"),
  9442. defaultnormal_vertex: [
  9443. "vec3 objectNormal;",
  9444. "#ifdef USE_SKINNING",
  9445. "objectNormal = skinnedNormal.xyz;",
  9446. "#endif",
  9447. "#if !defined( USE_SKINNING ) && defined( USE_MORPHNORMALS )",
  9448. "objectNormal = morphedNormal;",
  9449. "#endif",
  9450. "#if !defined( USE_SKINNING ) && ! defined( USE_MORPHNORMALS )",
  9451. "objectNormal = normal;",
  9452. "#endif",
  9453. "#ifdef FLIP_SIDED",
  9454. "objectNormal = -objectNormal;",
  9455. "#endif",
  9456. "vec3 transformedNormal = normalMatrix * objectNormal;"
  9457. ].join("\n"),
  9458. // SHADOW MAP
  9459. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  9460. // http://spidergl.org/example.php?id=6
  9461. // http://fabiensanglard.net/shadowmapping
  9462. shadowmap_pars_fragment: [
  9463. "#ifdef USE_SHADOWMAP",
  9464. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  9465. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  9466. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  9467. "uniform float shadowBias[ MAX_SHADOWS ];",
  9468. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9469. "float unpackDepth( const in vec4 rgba_depth ) {",
  9470. "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 );",
  9471. "float depth = dot( rgba_depth, bit_shift );",
  9472. "return depth;",
  9473. "}",
  9474. "#endif"
  9475. ].join("\n"),
  9476. shadowmap_fragment: [
  9477. "#ifdef USE_SHADOWMAP",
  9478. "#ifdef SHADOWMAP_DEBUG",
  9479. "vec3 frustumColors[3];",
  9480. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  9481. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  9482. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  9483. "#endif",
  9484. "#ifdef SHADOWMAP_CASCADE",
  9485. "int inFrustumCount = 0;",
  9486. "#endif",
  9487. "float fDepth;",
  9488. "vec3 shadowColor = vec3( 1.0 );",
  9489. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9490. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  9491. // "if ( something && something )" breaks ATI OpenGL shader compiler
  9492. // "if ( all( something, something ) )" using this instead
  9493. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  9494. "bool inFrustum = all( inFrustumVec );",
  9495. // don't shadow pixels outside of light frustum
  9496. // use just first frustum (for cascades)
  9497. // don't shadow pixels behind far plane of light frustum
  9498. "#ifdef SHADOWMAP_CASCADE",
  9499. "inFrustumCount += int( inFrustum );",
  9500. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  9501. "#else",
  9502. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  9503. "#endif",
  9504. "bool frustumTest = all( frustumTestVec );",
  9505. "if ( frustumTest ) {",
  9506. "shadowCoord.z += shadowBias[ i ];",
  9507. "#ifdef SHADOWMAP_SOFT",
  9508. // Percentage-close filtering
  9509. // (9 pixel kernel)
  9510. // http://fabiensanglard.net/shadowmappingPCF/
  9511. "float shadow = 0.0;",
  9512. /*
  9513. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  9514. // must enroll loop manually
  9515. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  9516. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  9517. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  9518. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  9519. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  9520. "float fDepth = unpackDepth( rgbaDepth );",
  9521. "if ( fDepth < shadowCoord.z )",
  9522. "shadow += 1.0;",
  9523. "}",
  9524. "shadow /= 9.0;",
  9525. */
  9526. "const float shadowDelta = 1.0 / 9.0;",
  9527. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  9528. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  9529. "float dx0 = -1.25 * xPixelOffset;",
  9530. "float dy0 = -1.25 * yPixelOffset;",
  9531. "float dx1 = 1.25 * xPixelOffset;",
  9532. "float dy1 = 1.25 * yPixelOffset;",
  9533. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  9534. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9535. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  9536. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9537. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  9538. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9539. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  9540. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9541. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  9542. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9543. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  9544. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9545. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  9546. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9547. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  9548. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9549. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  9550. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  9551. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  9552. "#else",
  9553. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  9554. "float fDepth = unpackDepth( rgbaDepth );",
  9555. "if ( fDepth < shadowCoord.z )",
  9556. // spot with multiple shadows is darker
  9557. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  9558. // spot with multiple shadows has the same color as single shadow spot
  9559. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  9560. "#endif",
  9561. "}",
  9562. "#ifdef SHADOWMAP_DEBUG",
  9563. "#ifdef SHADOWMAP_CASCADE",
  9564. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  9565. "#else",
  9566. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  9567. "#endif",
  9568. "#endif",
  9569. "}",
  9570. "#ifdef GAMMA_OUTPUT",
  9571. "shadowColor *= shadowColor;",
  9572. "#endif",
  9573. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  9574. "#endif"
  9575. ].join("\n"),
  9576. shadowmap_pars_vertex: [
  9577. "#ifdef USE_SHADOWMAP",
  9578. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  9579. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  9580. "#endif"
  9581. ].join("\n"),
  9582. shadowmap_vertex: [
  9583. "#ifdef USE_SHADOWMAP",
  9584. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  9585. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  9586. "}",
  9587. "#endif"
  9588. ].join("\n"),
  9589. // ALPHATEST
  9590. alphatest_fragment: [
  9591. "#ifdef ALPHATEST",
  9592. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  9593. "#endif"
  9594. ].join("\n"),
  9595. // LINEAR SPACE
  9596. linear_to_gamma_fragment: [
  9597. "#ifdef GAMMA_OUTPUT",
  9598. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  9599. "#endif"
  9600. ].join("\n")
  9601. };
  9602. THREE.UniformsUtils = {
  9603. merge: function ( uniforms ) {
  9604. var u, p, tmp, merged = {};
  9605. for ( u = 0; u < uniforms.length; u ++ ) {
  9606. tmp = this.clone( uniforms[ u ] );
  9607. for ( p in tmp ) {
  9608. merged[ p ] = tmp[ p ];
  9609. }
  9610. }
  9611. return merged;
  9612. },
  9613. clone: function ( uniforms_src ) {
  9614. var u, p, parameter, parameter_src, uniforms_dst = {};
  9615. for ( u in uniforms_src ) {
  9616. uniforms_dst[ u ] = {};
  9617. for ( p in uniforms_src[ u ] ) {
  9618. parameter_src = uniforms_src[ u ][ p ];
  9619. if ( parameter_src instanceof THREE.Color ||
  9620. parameter_src instanceof THREE.Vector2 ||
  9621. parameter_src instanceof THREE.Vector3 ||
  9622. parameter_src instanceof THREE.Vector4 ||
  9623. parameter_src instanceof THREE.Matrix4 ||
  9624. parameter_src instanceof THREE.Texture ) {
  9625. uniforms_dst[ u ][ p ] = parameter_src.clone();
  9626. } else if ( parameter_src instanceof Array ) {
  9627. uniforms_dst[ u ][ p ] = parameter_src.slice();
  9628. } else {
  9629. uniforms_dst[ u ][ p ] = parameter_src;
  9630. }
  9631. }
  9632. }
  9633. return uniforms_dst;
  9634. }
  9635. };
  9636. THREE.UniformsLib = {
  9637. common: {
  9638. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9639. "opacity" : { type: "f", value: 1.0 },
  9640. "map" : { type: "t", value: null },
  9641. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  9642. "lightMap" : { type: "t", value: null },
  9643. "specularMap" : { type: "t", value: null },
  9644. "envMap" : { type: "t", value: null },
  9645. "flipEnvMap" : { type: "f", value: -1 },
  9646. "useRefract" : { type: "i", value: 0 },
  9647. "reflectivity" : { type: "f", value: 1.0 },
  9648. "refractionRatio" : { type: "f", value: 0.98 },
  9649. "combine" : { type: "i", value: 0 },
  9650. "morphTargetInfluences" : { type: "f", value: 0 }
  9651. },
  9652. bump: {
  9653. "bumpMap" : { type: "t", value: null },
  9654. "bumpScale" : { type: "f", value: 1 }
  9655. },
  9656. normalmap: {
  9657. "normalMap" : { type: "t", value: null },
  9658. "normalScale" : { type: "v2", value: new THREE.Vector2( 1, 1 ) }
  9659. },
  9660. fog : {
  9661. "fogDensity" : { type: "f", value: 0.00025 },
  9662. "fogNear" : { type: "f", value: 1 },
  9663. "fogFar" : { type: "f", value: 2000 },
  9664. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9665. },
  9666. lights: {
  9667. "ambientLightColor" : { type: "fv", value: [] },
  9668. "directionalLightDirection" : { type: "fv", value: [] },
  9669. "directionalLightColor" : { type: "fv", value: [] },
  9670. "hemisphereLightDirection" : { type: "fv", value: [] },
  9671. "hemisphereLightSkyColor" : { type: "fv", value: [] },
  9672. "hemisphereLightGroundColor" : { type: "fv", value: [] },
  9673. "pointLightColor" : { type: "fv", value: [] },
  9674. "pointLightPosition" : { type: "fv", value: [] },
  9675. "pointLightDistance" : { type: "fv1", value: [] },
  9676. "spotLightColor" : { type: "fv", value: [] },
  9677. "spotLightPosition" : { type: "fv", value: [] },
  9678. "spotLightDirection" : { type: "fv", value: [] },
  9679. "spotLightDistance" : { type: "fv1", value: [] },
  9680. "spotLightAngleCos" : { type: "fv1", value: [] },
  9681. "spotLightExponent" : { type: "fv1", value: [] }
  9682. },
  9683. particle: {
  9684. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  9685. "opacity" : { type: "f", value: 1.0 },
  9686. "size" : { type: "f", value: 1.0 },
  9687. "scale" : { type: "f", value: 1.0 },
  9688. "map" : { type: "t", value: null },
  9689. "fogDensity" : { type: "f", value: 0.00025 },
  9690. "fogNear" : { type: "f", value: 1 },
  9691. "fogFar" : { type: "f", value: 2000 },
  9692. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  9693. },
  9694. shadowmap: {
  9695. "shadowMap": { type: "tv", value: [] },
  9696. "shadowMapSize": { type: "v2v", value: [] },
  9697. "shadowBias" : { type: "fv1", value: [] },
  9698. "shadowDarkness": { type: "fv1", value: [] },
  9699. "shadowMatrix" : { type: "m4v", value: [] }
  9700. }
  9701. };
  9702. THREE.ShaderLib = {
  9703. 'depth': {
  9704. uniforms: {
  9705. "mNear": { type: "f", value: 1.0 },
  9706. "mFar" : { type: "f", value: 2000.0 },
  9707. "opacity" : { type: "f", value: 1.0 }
  9708. },
  9709. vertexShader: [
  9710. "void main() {",
  9711. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  9712. "}"
  9713. ].join("\n"),
  9714. fragmentShader: [
  9715. "uniform float mNear;",
  9716. "uniform float mFar;",
  9717. "uniform float opacity;",
  9718. "void main() {",
  9719. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  9720. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  9721. "gl_FragColor = vec4( vec3( color ), opacity );",
  9722. "}"
  9723. ].join("\n")
  9724. },
  9725. 'normal': {
  9726. uniforms: {
  9727. "opacity" : { type: "f", value: 1.0 }
  9728. },
  9729. vertexShader: [
  9730. "varying vec3 vNormal;",
  9731. "void main() {",
  9732. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9733. "vNormal = normalize( normalMatrix * normal );",
  9734. "gl_Position = projectionMatrix * mvPosition;",
  9735. "}"
  9736. ].join("\n"),
  9737. fragmentShader: [
  9738. "uniform float opacity;",
  9739. "varying vec3 vNormal;",
  9740. "void main() {",
  9741. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  9742. "}"
  9743. ].join("\n")
  9744. },
  9745. 'basic': {
  9746. uniforms: THREE.UniformsUtils.merge( [
  9747. THREE.UniformsLib[ "common" ],
  9748. THREE.UniformsLib[ "fog" ],
  9749. THREE.UniformsLib[ "shadowmap" ]
  9750. ] ),
  9751. vertexShader: [
  9752. THREE.ShaderChunk[ "map_pars_vertex" ],
  9753. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9754. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9755. THREE.ShaderChunk[ "color_pars_vertex" ],
  9756. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9757. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9758. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9759. "void main() {",
  9760. THREE.ShaderChunk[ "map_vertex" ],
  9761. THREE.ShaderChunk[ "lightmap_vertex" ],
  9762. THREE.ShaderChunk[ "color_vertex" ],
  9763. "#ifdef USE_ENVMAP",
  9764. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9765. THREE.ShaderChunk[ "skinbase_vertex" ],
  9766. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9767. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9768. "#endif",
  9769. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9770. THREE.ShaderChunk[ "skinning_vertex" ],
  9771. THREE.ShaderChunk[ "default_vertex" ],
  9772. THREE.ShaderChunk[ "worldpos_vertex" ],
  9773. THREE.ShaderChunk[ "envmap_vertex" ],
  9774. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9775. "}"
  9776. ].join("\n"),
  9777. fragmentShader: [
  9778. "uniform vec3 diffuse;",
  9779. "uniform float opacity;",
  9780. THREE.ShaderChunk[ "color_pars_fragment" ],
  9781. THREE.ShaderChunk[ "map_pars_fragment" ],
  9782. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9783. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9784. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9785. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9786. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9787. "void main() {",
  9788. "gl_FragColor = vec4( diffuse, opacity );",
  9789. THREE.ShaderChunk[ "map_fragment" ],
  9790. THREE.ShaderChunk[ "alphatest_fragment" ],
  9791. THREE.ShaderChunk[ "specularmap_fragment" ],
  9792. THREE.ShaderChunk[ "lightmap_fragment" ],
  9793. THREE.ShaderChunk[ "color_fragment" ],
  9794. THREE.ShaderChunk[ "envmap_fragment" ],
  9795. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9796. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9797. THREE.ShaderChunk[ "fog_fragment" ],
  9798. "}"
  9799. ].join("\n")
  9800. },
  9801. 'lambert': {
  9802. uniforms: THREE.UniformsUtils.merge( [
  9803. THREE.UniformsLib[ "common" ],
  9804. THREE.UniformsLib[ "fog" ],
  9805. THREE.UniformsLib[ "lights" ],
  9806. THREE.UniformsLib[ "shadowmap" ],
  9807. {
  9808. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9809. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9810. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9811. }
  9812. ] ),
  9813. vertexShader: [
  9814. "#define LAMBERT",
  9815. "varying vec3 vLightFront;",
  9816. "#ifdef DOUBLE_SIDED",
  9817. "varying vec3 vLightBack;",
  9818. "#endif",
  9819. THREE.ShaderChunk[ "map_pars_vertex" ],
  9820. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9821. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9822. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  9823. THREE.ShaderChunk[ "color_pars_vertex" ],
  9824. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9825. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9826. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9827. "void main() {",
  9828. THREE.ShaderChunk[ "map_vertex" ],
  9829. THREE.ShaderChunk[ "lightmap_vertex" ],
  9830. THREE.ShaderChunk[ "color_vertex" ],
  9831. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9832. THREE.ShaderChunk[ "skinbase_vertex" ],
  9833. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9834. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9835. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9836. THREE.ShaderChunk[ "skinning_vertex" ],
  9837. THREE.ShaderChunk[ "default_vertex" ],
  9838. THREE.ShaderChunk[ "worldpos_vertex" ],
  9839. THREE.ShaderChunk[ "envmap_vertex" ],
  9840. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  9841. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9842. "}"
  9843. ].join("\n"),
  9844. fragmentShader: [
  9845. "uniform float opacity;",
  9846. "varying vec3 vLightFront;",
  9847. "#ifdef DOUBLE_SIDED",
  9848. "varying vec3 vLightBack;",
  9849. "#endif",
  9850. THREE.ShaderChunk[ "color_pars_fragment" ],
  9851. THREE.ShaderChunk[ "map_pars_fragment" ],
  9852. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9853. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9854. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9855. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9856. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9857. "void main() {",
  9858. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9859. THREE.ShaderChunk[ "map_fragment" ],
  9860. THREE.ShaderChunk[ "alphatest_fragment" ],
  9861. THREE.ShaderChunk[ "specularmap_fragment" ],
  9862. "#ifdef DOUBLE_SIDED",
  9863. //"float isFront = float( gl_FrontFacing );",
  9864. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  9865. "if ( gl_FrontFacing )",
  9866. "gl_FragColor.xyz *= vLightFront;",
  9867. "else",
  9868. "gl_FragColor.xyz *= vLightBack;",
  9869. "#else",
  9870. "gl_FragColor.xyz *= vLightFront;",
  9871. "#endif",
  9872. THREE.ShaderChunk[ "lightmap_fragment" ],
  9873. THREE.ShaderChunk[ "color_fragment" ],
  9874. THREE.ShaderChunk[ "envmap_fragment" ],
  9875. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9876. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9877. THREE.ShaderChunk[ "fog_fragment" ],
  9878. "}"
  9879. ].join("\n")
  9880. },
  9881. 'phong': {
  9882. uniforms: THREE.UniformsUtils.merge( [
  9883. THREE.UniformsLib[ "common" ],
  9884. THREE.UniformsLib[ "bump" ],
  9885. THREE.UniformsLib[ "normalmap" ],
  9886. THREE.UniformsLib[ "fog" ],
  9887. THREE.UniformsLib[ "lights" ],
  9888. THREE.UniformsLib[ "shadowmap" ],
  9889. {
  9890. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  9891. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  9892. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  9893. "shininess": { type: "f", value: 30 },
  9894. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  9895. }
  9896. ] ),
  9897. vertexShader: [
  9898. "#define PHONG",
  9899. "varying vec3 vViewPosition;",
  9900. "varying vec3 vNormal;",
  9901. THREE.ShaderChunk[ "map_pars_vertex" ],
  9902. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  9903. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  9904. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  9905. THREE.ShaderChunk[ "color_pars_vertex" ],
  9906. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  9907. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  9908. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9909. "void main() {",
  9910. THREE.ShaderChunk[ "map_vertex" ],
  9911. THREE.ShaderChunk[ "lightmap_vertex" ],
  9912. THREE.ShaderChunk[ "color_vertex" ],
  9913. THREE.ShaderChunk[ "morphnormal_vertex" ],
  9914. THREE.ShaderChunk[ "skinbase_vertex" ],
  9915. THREE.ShaderChunk[ "skinnormal_vertex" ],
  9916. THREE.ShaderChunk[ "defaultnormal_vertex" ],
  9917. "vNormal = normalize( transformedNormal );",
  9918. THREE.ShaderChunk[ "morphtarget_vertex" ],
  9919. THREE.ShaderChunk[ "skinning_vertex" ],
  9920. THREE.ShaderChunk[ "default_vertex" ],
  9921. "vViewPosition = -mvPosition.xyz;",
  9922. THREE.ShaderChunk[ "worldpos_vertex" ],
  9923. THREE.ShaderChunk[ "envmap_vertex" ],
  9924. THREE.ShaderChunk[ "lights_phong_vertex" ],
  9925. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9926. "}"
  9927. ].join("\n"),
  9928. fragmentShader: [
  9929. "uniform vec3 diffuse;",
  9930. "uniform float opacity;",
  9931. "uniform vec3 ambient;",
  9932. "uniform vec3 emissive;",
  9933. "uniform vec3 specular;",
  9934. "uniform float shininess;",
  9935. THREE.ShaderChunk[ "color_pars_fragment" ],
  9936. THREE.ShaderChunk[ "map_pars_fragment" ],
  9937. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  9938. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  9939. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9940. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  9941. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9942. THREE.ShaderChunk[ "bumpmap_pars_fragment" ],
  9943. THREE.ShaderChunk[ "normalmap_pars_fragment" ],
  9944. THREE.ShaderChunk[ "specularmap_pars_fragment" ],
  9945. "void main() {",
  9946. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  9947. THREE.ShaderChunk[ "map_fragment" ],
  9948. THREE.ShaderChunk[ "alphatest_fragment" ],
  9949. THREE.ShaderChunk[ "specularmap_fragment" ],
  9950. THREE.ShaderChunk[ "lights_phong_fragment" ],
  9951. THREE.ShaderChunk[ "lightmap_fragment" ],
  9952. THREE.ShaderChunk[ "color_fragment" ],
  9953. THREE.ShaderChunk[ "envmap_fragment" ],
  9954. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9955. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  9956. THREE.ShaderChunk[ "fog_fragment" ],
  9957. "}"
  9958. ].join("\n")
  9959. },
  9960. 'particle_basic': {
  9961. uniforms: THREE.UniformsUtils.merge( [
  9962. THREE.UniformsLib[ "particle" ],
  9963. THREE.UniformsLib[ "shadowmap" ]
  9964. ] ),
  9965. vertexShader: [
  9966. "uniform float size;",
  9967. "uniform float scale;",
  9968. THREE.ShaderChunk[ "color_pars_vertex" ],
  9969. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  9970. "void main() {",
  9971. THREE.ShaderChunk[ "color_vertex" ],
  9972. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  9973. "#ifdef USE_SIZEATTENUATION",
  9974. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  9975. "#else",
  9976. "gl_PointSize = size;",
  9977. "#endif",
  9978. "gl_Position = projectionMatrix * mvPosition;",
  9979. THREE.ShaderChunk[ "worldpos_vertex" ],
  9980. THREE.ShaderChunk[ "shadowmap_vertex" ],
  9981. "}"
  9982. ].join("\n"),
  9983. fragmentShader: [
  9984. "uniform vec3 psColor;",
  9985. "uniform float opacity;",
  9986. THREE.ShaderChunk[ "color_pars_fragment" ],
  9987. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  9988. THREE.ShaderChunk[ "fog_pars_fragment" ],
  9989. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  9990. "void main() {",
  9991. "gl_FragColor = vec4( psColor, opacity );",
  9992. THREE.ShaderChunk[ "map_particle_fragment" ],
  9993. THREE.ShaderChunk[ "alphatest_fragment" ],
  9994. THREE.ShaderChunk[ "color_fragment" ],
  9995. THREE.ShaderChunk[ "shadowmap_fragment" ],
  9996. THREE.ShaderChunk[ "fog_fragment" ],
  9997. "}"
  9998. ].join("\n")
  9999. },
  10000. 'dashed': {
  10001. uniforms: THREE.UniformsUtils.merge( [
  10002. THREE.UniformsLib[ "common" ],
  10003. THREE.UniformsLib[ "fog" ],
  10004. {
  10005. "scale": { type: "f", value: 1 },
  10006. "dashSize": { type: "f", value: 1 },
  10007. "totalSize": { type: "f", value: 2 }
  10008. }
  10009. ] ),
  10010. vertexShader: [
  10011. "uniform float scale;",
  10012. "attribute float lineDistance;",
  10013. "varying float vLineDistance;",
  10014. THREE.ShaderChunk[ "color_pars_vertex" ],
  10015. "void main() {",
  10016. THREE.ShaderChunk[ "color_vertex" ],
  10017. "vLineDistance = scale * lineDistance;",
  10018. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10019. "gl_Position = projectionMatrix * mvPosition;",
  10020. "}"
  10021. ].join("\n"),
  10022. fragmentShader: [
  10023. "uniform vec3 diffuse;",
  10024. "uniform float opacity;",
  10025. "uniform float dashSize;",
  10026. "uniform float totalSize;",
  10027. "varying float vLineDistance;",
  10028. THREE.ShaderChunk[ "color_pars_fragment" ],
  10029. THREE.ShaderChunk[ "fog_pars_fragment" ],
  10030. "void main() {",
  10031. "if ( mod( vLineDistance, totalSize ) > dashSize ) {",
  10032. "discard;",
  10033. "}",
  10034. "gl_FragColor = vec4( diffuse, opacity );",
  10035. THREE.ShaderChunk[ "color_fragment" ],
  10036. THREE.ShaderChunk[ "fog_fragment" ],
  10037. "}"
  10038. ].join("\n")
  10039. },
  10040. // Depth encoding into RGBA texture
  10041. // based on SpiderGL shadow map example
  10042. // http://spidergl.org/example.php?id=6
  10043. // originally from
  10044. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  10045. // see also here:
  10046. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  10047. 'depthRGBA': {
  10048. uniforms: {},
  10049. vertexShader: [
  10050. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  10051. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  10052. "void main() {",
  10053. THREE.ShaderChunk[ "skinbase_vertex" ],
  10054. THREE.ShaderChunk[ "morphtarget_vertex" ],
  10055. THREE.ShaderChunk[ "skinning_vertex" ],
  10056. THREE.ShaderChunk[ "default_vertex" ],
  10057. "}"
  10058. ].join("\n"),
  10059. fragmentShader: [
  10060. "vec4 pack_depth( const in float depth ) {",
  10061. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  10062. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  10063. "vec4 res = fract( depth * bit_shift );",
  10064. "res -= res.xxyz * bit_mask;",
  10065. "return res;",
  10066. "}",
  10067. "void main() {",
  10068. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  10069. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  10070. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  10071. //"gl_FragData[ 0 ] = pack_depth( z );",
  10072. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  10073. "}"
  10074. ].join("\n")
  10075. }
  10076. };
  10077. /**
  10078. * @author supereggbert / http://www.paulbrunt.co.uk/
  10079. * @author mrdoob / http://mrdoob.com/
  10080. * @author alteredq / http://alteredqualia.com/
  10081. * @author szimek / https://github.com/szimek/
  10082. */
  10083. THREE.WebGLRenderer = function ( parameters ) {
  10084. console.log( 'THREE.WebGLRenderer', THREE.REVISION );
  10085. parameters = parameters || {};
  10086. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  10087. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  10088. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  10089. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  10090. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  10091. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  10092. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  10093. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  10094. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0;
  10095. // public properties
  10096. this.domElement = _canvas;
  10097. this.context = null;
  10098. // clearing
  10099. this.autoClear = true;
  10100. this.autoClearColor = true;
  10101. this.autoClearDepth = true;
  10102. this.autoClearStencil = true;
  10103. // scene graph
  10104. this.sortObjects = true;
  10105. this.autoUpdateObjects = true;
  10106. this.autoUpdateScene = true;
  10107. // physically based shading
  10108. this.gammaInput = false;
  10109. this.gammaOutput = false;
  10110. this.physicallyBasedShading = false;
  10111. // shadow map
  10112. this.shadowMapEnabled = false;
  10113. this.shadowMapAutoUpdate = true;
  10114. this.shadowMapSoft = true;
  10115. this.shadowMapCullFace = THREE.CullFaceFront;
  10116. this.shadowMapDebug = false;
  10117. this.shadowMapCascade = false;
  10118. // morphs
  10119. this.maxMorphTargets = 8;
  10120. this.maxMorphNormals = 4;
  10121. // flags
  10122. this.autoScaleCubemaps = true;
  10123. // custom render plugins
  10124. this.renderPluginsPre = [];
  10125. this.renderPluginsPost = [];
  10126. // info
  10127. this.info = {
  10128. memory: {
  10129. programs: 0,
  10130. geometries: 0,
  10131. textures: 0
  10132. },
  10133. render: {
  10134. calls: 0,
  10135. vertices: 0,
  10136. faces: 0,
  10137. points: 0
  10138. }
  10139. };
  10140. // internal properties
  10141. var _this = this,
  10142. _programs = [],
  10143. _programs_counter = 0,
  10144. // internal state cache
  10145. _currentProgram = null,
  10146. _currentFramebuffer = null,
  10147. _currentMaterialId = -1,
  10148. _currentGeometryGroupHash = null,
  10149. _currentCamera = null,
  10150. _geometryGroupCounter = 0,
  10151. _usedTextureUnits = 0,
  10152. // GL state cache
  10153. _oldDoubleSided = -1,
  10154. _oldFlipSided = -1,
  10155. _oldBlending = -1,
  10156. _oldBlendEquation = -1,
  10157. _oldBlendSrc = -1,
  10158. _oldBlendDst = -1,
  10159. _oldDepthTest = -1,
  10160. _oldDepthWrite = -1,
  10161. _oldPolygonOffset = null,
  10162. _oldPolygonOffsetFactor = null,
  10163. _oldPolygonOffsetUnits = null,
  10164. _oldLineWidth = null,
  10165. _viewportX = 0,
  10166. _viewportY = 0,
  10167. _viewportWidth = 0,
  10168. _viewportHeight = 0,
  10169. _currentWidth = 0,
  10170. _currentHeight = 0,
  10171. _enabledAttributes = {},
  10172. // frustum
  10173. _frustum = new THREE.Frustum(),
  10174. // camera matrices cache
  10175. _projScreenMatrix = new THREE.Matrix4(),
  10176. _projScreenMatrixPS = new THREE.Matrix4(),
  10177. _vector3 = new THREE.Vector3(),
  10178. // light arrays cache
  10179. _direction = new THREE.Vector3(),
  10180. _lightsNeedUpdate = true,
  10181. _lights = {
  10182. ambient: [ 0, 0, 0 ],
  10183. directional: { length: 0, colors: new Array(), positions: new Array() },
  10184. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() },
  10185. spot: { length: 0, colors: new Array(), positions: new Array(), distances: new Array(), directions: new Array(), anglesCos: new Array(), exponents: new Array() },
  10186. hemi: { length: 0, skyColors: new Array(), groundColors: new Array(), positions: new Array() }
  10187. };
  10188. // initialize
  10189. var _gl;
  10190. var _glExtensionTextureFloat;
  10191. var _glExtensionStandardDerivatives;
  10192. var _glExtensionTextureFilterAnisotropic;
  10193. var _glExtensionCompressedTextureS3TC;
  10194. initGL();
  10195. setDefaultGLState();
  10196. this.context = _gl;
  10197. // GPU capabilities
  10198. var _maxTextures = _gl.getParameter( _gl.MAX_TEXTURE_IMAGE_UNITS );
  10199. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS );
  10200. var _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE );
  10201. var _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  10202. var _maxAnisotropy = _glExtensionTextureFilterAnisotropic ? _gl.getParameter( _glExtensionTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT ) : 0;
  10203. var _supportsVertexTextures = ( _maxVertexTextures > 0 );
  10204. var _supportsBoneTextures = _supportsVertexTextures && _glExtensionTextureFloat;
  10205. var _compressedTextureFormats = _glExtensionCompressedTextureS3TC ? _gl.getParameter( _gl.COMPRESSED_TEXTURE_FORMATS ) : [];
  10206. // API
  10207. this.getContext = function () {
  10208. return _gl;
  10209. };
  10210. this.supportsVertexTextures = function () {
  10211. return _supportsVertexTextures;
  10212. };
  10213. this.getMaxAnisotropy = function () {
  10214. return _maxAnisotropy;
  10215. };
  10216. this.setSize = function ( width, height ) {
  10217. _canvas.width = width;
  10218. _canvas.height = height;
  10219. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  10220. };
  10221. this.setViewport = function ( x, y, width, height ) {
  10222. _viewportX = x !== undefined ? x : 0;
  10223. _viewportY = y !== undefined ? y : 0;
  10224. _viewportWidth = width !== undefined ? width : _canvas.width;
  10225. _viewportHeight = height !== undefined ? height : _canvas.height;
  10226. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  10227. };
  10228. this.setScissor = function ( x, y, width, height ) {
  10229. _gl.scissor( x, y, width, height );
  10230. };
  10231. this.enableScissorTest = function ( enable ) {
  10232. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  10233. };
  10234. // Clearing
  10235. this.setClearColorHex = function ( hex, alpha ) {
  10236. _clearColor.setHex( hex );
  10237. _clearAlpha = alpha;
  10238. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10239. };
  10240. this.setClearColor = function ( color, alpha ) {
  10241. _clearColor.copy( color );
  10242. _clearAlpha = alpha;
  10243. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  10244. };
  10245. this.getClearColor = function () {
  10246. return _clearColor;
  10247. };
  10248. this.getClearAlpha = function () {
  10249. return _clearAlpha;
  10250. };
  10251. this.clear = function ( color, depth, stencil ) {
  10252. var bits = 0;
  10253. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  10254. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  10255. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  10256. _gl.clear( bits );
  10257. };
  10258. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  10259. this.setRenderTarget( renderTarget );
  10260. this.clear( color, depth, stencil );
  10261. };
  10262. // Plugins
  10263. this.addPostPlugin = function ( plugin ) {
  10264. plugin.init( this );
  10265. this.renderPluginsPost.push( plugin );
  10266. };
  10267. this.addPrePlugin = function ( plugin ) {
  10268. plugin.init( this );
  10269. this.renderPluginsPre.push( plugin );
  10270. };
  10271. // Deallocation
  10272. this.deallocateObject = function ( object ) {
  10273. if ( ! object.__webglInit ) return;
  10274. object.__webglInit = false;
  10275. delete object._modelViewMatrix;
  10276. delete object._normalMatrix;
  10277. if ( object instanceof THREE.Mesh ) {
  10278. for ( var g in object.geometry.geometryGroups ) {
  10279. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  10280. }
  10281. } else if ( object instanceof THREE.Ribbon ) {
  10282. deleteRibbonBuffers( object.geometry );
  10283. } else if ( object instanceof THREE.Line ) {
  10284. deleteLineBuffers( object.geometry );
  10285. } else if ( object instanceof THREE.ParticleSystem ) {
  10286. deleteParticleBuffers( object.geometry );
  10287. }
  10288. };
  10289. this.deallocateTexture = function ( texture ) {
  10290. // cube texture
  10291. if ( texture.image && texture.image.__webglTextureCube ) {
  10292. _gl.deleteTexture( texture.image.__webglTextureCube );
  10293. // 2D texture
  10294. } else {
  10295. if ( ! texture.__webglInit ) return;
  10296. texture.__webglInit = false;
  10297. _gl.deleteTexture( texture.__webglTexture );
  10298. }
  10299. _this.info.memory.textures --;
  10300. };
  10301. this.deallocateRenderTarget = function ( renderTarget ) {
  10302. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  10303. _gl.deleteTexture( renderTarget.__webglTexture );
  10304. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  10305. for ( var i = 0; i < 6; i ++ ) {
  10306. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  10307. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  10308. }
  10309. } else {
  10310. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  10311. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  10312. }
  10313. };
  10314. this.deallocateMaterial = function ( material ) {
  10315. var program = material.program;
  10316. if ( ! program ) return;
  10317. material.program = undefined;
  10318. // only deallocate GL program if this was the last use of shared program
  10319. // assumed there is only single copy of any program in the _programs list
  10320. // (that's how it's constructed)
  10321. var i, il, programInfo;
  10322. var deleteProgram = false;
  10323. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10324. programInfo = _programs[ i ];
  10325. if ( programInfo.program === program ) {
  10326. programInfo.usedTimes --;
  10327. if ( programInfo.usedTimes === 0 ) {
  10328. deleteProgram = true;
  10329. }
  10330. break;
  10331. }
  10332. }
  10333. if ( deleteProgram ) {
  10334. // avoid using array.splice, this is costlier than creating new array from scratch
  10335. var newPrograms = [];
  10336. for ( i = 0, il = _programs.length; i < il; i ++ ) {
  10337. programInfo = _programs[ i ];
  10338. if ( programInfo.program !== program ) {
  10339. newPrograms.push( programInfo );
  10340. }
  10341. }
  10342. _programs = newPrograms;
  10343. _gl.deleteProgram( program );
  10344. _this.info.memory.programs --;
  10345. }
  10346. };
  10347. // Rendering
  10348. this.updateShadowMap = function ( scene, camera ) {
  10349. _currentProgram = null;
  10350. _oldBlending = -1;
  10351. _oldDepthTest = -1;
  10352. _oldDepthWrite = -1;
  10353. _currentGeometryGroupHash = -1;
  10354. _currentMaterialId = -1;
  10355. _lightsNeedUpdate = true;
  10356. _oldDoubleSided = -1;
  10357. _oldFlipSided = -1;
  10358. this.shadowMapPlugin.update( scene, camera );
  10359. };
  10360. // Internal functions
  10361. // Buffer allocation
  10362. function createParticleBuffers ( geometry ) {
  10363. geometry.__webglVertexBuffer = _gl.createBuffer();
  10364. geometry.__webglColorBuffer = _gl.createBuffer();
  10365. _this.info.memory.geometries ++;
  10366. };
  10367. function createLineBuffers ( geometry ) {
  10368. geometry.__webglVertexBuffer = _gl.createBuffer();
  10369. geometry.__webglColorBuffer = _gl.createBuffer();
  10370. geometry.__webglLineDistanceBuffer = _gl.createBuffer();
  10371. _this.info.memory.geometries ++;
  10372. };
  10373. function createRibbonBuffers ( geometry ) {
  10374. geometry.__webglVertexBuffer = _gl.createBuffer();
  10375. geometry.__webglColorBuffer = _gl.createBuffer();
  10376. geometry.__webglNormalBuffer = _gl.createBuffer();
  10377. _this.info.memory.geometries ++;
  10378. };
  10379. function createMeshBuffers ( geometryGroup ) {
  10380. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  10381. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  10382. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  10383. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  10384. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  10385. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  10386. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  10387. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  10388. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  10389. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  10390. var m, ml;
  10391. if ( geometryGroup.numMorphTargets ) {
  10392. geometryGroup.__webglMorphTargetsBuffers = [];
  10393. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10394. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  10395. }
  10396. }
  10397. if ( geometryGroup.numMorphNormals ) {
  10398. geometryGroup.__webglMorphNormalsBuffers = [];
  10399. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10400. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  10401. }
  10402. }
  10403. _this.info.memory.geometries ++;
  10404. };
  10405. // Buffer deallocation
  10406. function deleteParticleBuffers ( geometry ) {
  10407. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10408. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10409. deleteCustomAttributesBuffers( geometry );
  10410. _this.info.memory.geometries --;
  10411. };
  10412. function deleteLineBuffers ( geometry ) {
  10413. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10414. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10415. _gl.deleteBuffer( geometry.__webglLineDistanceBuffer );
  10416. deleteCustomAttributesBuffers( geometry );
  10417. _this.info.memory.geometries --;
  10418. };
  10419. function deleteRibbonBuffers ( geometry ) {
  10420. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  10421. _gl.deleteBuffer( geometry.__webglColorBuffer );
  10422. _gl.deleteBuffer( geometry.__webglNormalBuffer );
  10423. deleteCustomAttributesBuffers( geometry );
  10424. _this.info.memory.geometries --;
  10425. };
  10426. function deleteMeshBuffers ( geometryGroup ) {
  10427. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  10428. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  10429. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  10430. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  10431. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  10432. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  10433. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  10434. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  10435. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  10436. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  10437. var m, ml;
  10438. if ( geometryGroup.numMorphTargets ) {
  10439. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10440. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  10441. }
  10442. }
  10443. if ( geometryGroup.numMorphNormals ) {
  10444. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10445. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  10446. }
  10447. }
  10448. deleteCustomAttributesBuffers( geometryGroup );
  10449. _this.info.memory.geometries --;
  10450. };
  10451. function deleteCustomAttributesBuffers( geometry ) {
  10452. if ( geometry.__webglCustomAttributesList ) {
  10453. for ( var id in geometry.__webglCustomAttributesList ) {
  10454. _gl.deleteBuffer( geometry.__webglCustomAttributesList[ id ].buffer );
  10455. }
  10456. }
  10457. };
  10458. // Buffer initialization
  10459. function initCustomAttributes ( geometry, object ) {
  10460. var nvertices = geometry.vertices.length;
  10461. var material = object.material;
  10462. if ( material.attributes ) {
  10463. if ( geometry.__webglCustomAttributesList === undefined ) {
  10464. geometry.__webglCustomAttributesList = [];
  10465. }
  10466. for ( var a in material.attributes ) {
  10467. var attribute = material.attributes[ a ];
  10468. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10469. attribute.__webglInitialized = true;
  10470. var size = 1; // "f" and "i"
  10471. if ( attribute.type === "v2" ) size = 2;
  10472. else if ( attribute.type === "v3" ) size = 3;
  10473. else if ( attribute.type === "v4" ) size = 4;
  10474. else if ( attribute.type === "c" ) size = 3;
  10475. attribute.size = size;
  10476. attribute.array = new Float32Array( nvertices * size );
  10477. attribute.buffer = _gl.createBuffer();
  10478. attribute.buffer.belongsToAttribute = a;
  10479. attribute.needsUpdate = true;
  10480. }
  10481. geometry.__webglCustomAttributesList.push( attribute );
  10482. }
  10483. }
  10484. };
  10485. function initParticleBuffers ( geometry, object ) {
  10486. var nvertices = geometry.vertices.length;
  10487. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10488. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10489. geometry.__sortArray = [];
  10490. geometry.__webglParticleCount = nvertices;
  10491. initCustomAttributes ( geometry, object );
  10492. };
  10493. function initLineBuffers ( geometry, object ) {
  10494. var nvertices = geometry.vertices.length;
  10495. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10496. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10497. geometry.__lineDistanceArray = new Float32Array( nvertices * 1 );
  10498. geometry.__webglLineCount = nvertices;
  10499. initCustomAttributes ( geometry, object );
  10500. };
  10501. function initRibbonBuffers ( geometry, object ) {
  10502. var nvertices = geometry.vertices.length;
  10503. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  10504. geometry.__colorArray = new Float32Array( nvertices * 3 );
  10505. geometry.__normalArray = new Float32Array( nvertices * 3 );
  10506. geometry.__webglVertexCount = nvertices;
  10507. initCustomAttributes ( geometry, object );
  10508. };
  10509. function initMeshBuffers ( geometryGroup, object ) {
  10510. var geometry = object.geometry,
  10511. faces3 = geometryGroup.faces3,
  10512. faces4 = geometryGroup.faces4,
  10513. nvertices = faces3.length * 3 + faces4.length * 4,
  10514. ntris = faces3.length * 1 + faces4.length * 2,
  10515. nlines = faces3.length * 3 + faces4.length * 4,
  10516. material = getBufferMaterial( object, geometryGroup ),
  10517. uvType = bufferGuessUVType( material ),
  10518. normalType = bufferGuessNormalType( material ),
  10519. vertexColorType = bufferGuessVertexColorType( material );
  10520. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  10521. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  10522. if ( normalType ) {
  10523. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  10524. }
  10525. if ( geometry.hasTangents ) {
  10526. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  10527. }
  10528. if ( vertexColorType ) {
  10529. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  10530. }
  10531. if ( uvType ) {
  10532. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  10533. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  10534. }
  10535. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  10536. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  10537. }
  10538. }
  10539. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  10540. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  10541. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  10542. }
  10543. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  10544. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  10545. var m, ml;
  10546. if ( geometryGroup.numMorphTargets ) {
  10547. geometryGroup.__morphTargetsArrays = [];
  10548. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  10549. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  10550. }
  10551. }
  10552. if ( geometryGroup.numMorphNormals ) {
  10553. geometryGroup.__morphNormalsArrays = [];
  10554. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  10555. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  10556. }
  10557. }
  10558. geometryGroup.__webglFaceCount = ntris * 3;
  10559. geometryGroup.__webglLineCount = nlines * 2;
  10560. // custom attributes
  10561. if ( material.attributes ) {
  10562. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  10563. geometryGroup.__webglCustomAttributesList = [];
  10564. }
  10565. for ( var a in material.attributes ) {
  10566. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  10567. // attribute buffers which are correctly indexed in the setMeshBuffers function
  10568. var originalAttribute = material.attributes[ a ];
  10569. var attribute = {};
  10570. for ( var property in originalAttribute ) {
  10571. attribute[ property ] = originalAttribute[ property ];
  10572. }
  10573. if ( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  10574. attribute.__webglInitialized = true;
  10575. var size = 1; // "f" and "i"
  10576. if( attribute.type === "v2" ) size = 2;
  10577. else if( attribute.type === "v3" ) size = 3;
  10578. else if( attribute.type === "v4" ) size = 4;
  10579. else if( attribute.type === "c" ) size = 3;
  10580. attribute.size = size;
  10581. attribute.array = new Float32Array( nvertices * size );
  10582. attribute.buffer = _gl.createBuffer();
  10583. attribute.buffer.belongsToAttribute = a;
  10584. originalAttribute.needsUpdate = true;
  10585. attribute.__original = originalAttribute;
  10586. }
  10587. geometryGroup.__webglCustomAttributesList.push( attribute );
  10588. }
  10589. }
  10590. geometryGroup.__inittedArrays = true;
  10591. };
  10592. function getBufferMaterial( object, geometryGroup ) {
  10593. return object.material instanceof THREE.MeshFaceMaterial
  10594. ? object.material.materials[ geometryGroup.materialIndex ]
  10595. : object.material;
  10596. };
  10597. function materialNeedsSmoothNormals ( material ) {
  10598. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  10599. };
  10600. function bufferGuessNormalType ( material ) {
  10601. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  10602. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  10603. return false;
  10604. }
  10605. if ( materialNeedsSmoothNormals( material ) ) {
  10606. return THREE.SmoothShading;
  10607. } else {
  10608. return THREE.FlatShading;
  10609. }
  10610. };
  10611. function bufferGuessVertexColorType ( material ) {
  10612. if ( material.vertexColors ) {
  10613. return material.vertexColors;
  10614. }
  10615. return false;
  10616. };
  10617. function bufferGuessUVType ( material ) {
  10618. // material must use some texture to require uvs
  10619. if ( material.map || material.lightMap || material.bumpMap || material.normalMap || material.specularMap || material instanceof THREE.ShaderMaterial ) {
  10620. return true;
  10621. }
  10622. return false;
  10623. };
  10624. //
  10625. function initDirectBuffers( geometry ) {
  10626. var a, attribute, type;
  10627. for ( a in geometry.attributes ) {
  10628. if ( a === "index" ) {
  10629. type = _gl.ELEMENT_ARRAY_BUFFER;
  10630. } else {
  10631. type = _gl.ARRAY_BUFFER;
  10632. }
  10633. attribute = geometry.attributes[ a ];
  10634. attribute.buffer = _gl.createBuffer();
  10635. _gl.bindBuffer( type, attribute.buffer );
  10636. _gl.bufferData( type, attribute.array, _gl.STATIC_DRAW );
  10637. }
  10638. };
  10639. // Buffer setting
  10640. function setParticleBuffers ( geometry, hint, object ) {
  10641. var v, c, vertex, offset, index, color,
  10642. vertices = geometry.vertices,
  10643. vl = vertices.length,
  10644. colors = geometry.colors,
  10645. cl = colors.length,
  10646. vertexArray = geometry.__vertexArray,
  10647. colorArray = geometry.__colorArray,
  10648. sortArray = geometry.__sortArray,
  10649. dirtyVertices = geometry.verticesNeedUpdate,
  10650. dirtyElements = geometry.elementsNeedUpdate,
  10651. dirtyColors = geometry.colorsNeedUpdate,
  10652. customAttributes = geometry.__webglCustomAttributesList,
  10653. i, il,
  10654. a, ca, cal, value,
  10655. customAttribute;
  10656. if ( object.sortParticles ) {
  10657. _projScreenMatrixPS.copy( _projScreenMatrix );
  10658. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  10659. for ( v = 0; v < vl; v ++ ) {
  10660. vertex = vertices[ v ];
  10661. _vector3.copy( vertex );
  10662. _projScreenMatrixPS.multiplyVector3( _vector3 );
  10663. sortArray[ v ] = [ _vector3.z, v ];
  10664. }
  10665. sortArray.sort( numericalSort );
  10666. for ( v = 0; v < vl; v ++ ) {
  10667. vertex = vertices[ sortArray[v][1] ];
  10668. offset = v * 3;
  10669. vertexArray[ offset ] = vertex.x;
  10670. vertexArray[ offset + 1 ] = vertex.y;
  10671. vertexArray[ offset + 2 ] = vertex.z;
  10672. }
  10673. for ( c = 0; c < cl; c ++ ) {
  10674. offset = c * 3;
  10675. color = colors[ sortArray[c][1] ];
  10676. colorArray[ offset ] = color.r;
  10677. colorArray[ offset + 1 ] = color.g;
  10678. colorArray[ offset + 2 ] = color.b;
  10679. }
  10680. if ( customAttributes ) {
  10681. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10682. customAttribute = customAttributes[ i ];
  10683. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  10684. offset = 0;
  10685. cal = customAttribute.value.length;
  10686. if ( customAttribute.size === 1 ) {
  10687. for ( ca = 0; ca < cal; ca ++ ) {
  10688. index = sortArray[ ca ][ 1 ];
  10689. customAttribute.array[ ca ] = customAttribute.value[ index ];
  10690. }
  10691. } else if ( customAttribute.size === 2 ) {
  10692. for ( ca = 0; ca < cal; ca ++ ) {
  10693. index = sortArray[ ca ][ 1 ];
  10694. value = customAttribute.value[ index ];
  10695. customAttribute.array[ offset ] = value.x;
  10696. customAttribute.array[ offset + 1 ] = value.y;
  10697. offset += 2;
  10698. }
  10699. } else if ( customAttribute.size === 3 ) {
  10700. if ( customAttribute.type === "c" ) {
  10701. for ( ca = 0; ca < cal; ca ++ ) {
  10702. index = sortArray[ ca ][ 1 ];
  10703. value = customAttribute.value[ index ];
  10704. customAttribute.array[ offset ] = value.r;
  10705. customAttribute.array[ offset + 1 ] = value.g;
  10706. customAttribute.array[ offset + 2 ] = value.b;
  10707. offset += 3;
  10708. }
  10709. } else {
  10710. for ( ca = 0; ca < cal; ca ++ ) {
  10711. index = sortArray[ ca ][ 1 ];
  10712. value = customAttribute.value[ index ];
  10713. customAttribute.array[ offset ] = value.x;
  10714. customAttribute.array[ offset + 1 ] = value.y;
  10715. customAttribute.array[ offset + 2 ] = value.z;
  10716. offset += 3;
  10717. }
  10718. }
  10719. } else if ( customAttribute.size === 4 ) {
  10720. for ( ca = 0; ca < cal; ca ++ ) {
  10721. index = sortArray[ ca ][ 1 ];
  10722. value = customAttribute.value[ index ];
  10723. customAttribute.array[ offset ] = value.x;
  10724. customAttribute.array[ offset + 1 ] = value.y;
  10725. customAttribute.array[ offset + 2 ] = value.z;
  10726. customAttribute.array[ offset + 3 ] = value.w;
  10727. offset += 4;
  10728. }
  10729. }
  10730. }
  10731. }
  10732. } else {
  10733. if ( dirtyVertices ) {
  10734. for ( v = 0; v < vl; v ++ ) {
  10735. vertex = vertices[ v ];
  10736. offset = v * 3;
  10737. vertexArray[ offset ] = vertex.x;
  10738. vertexArray[ offset + 1 ] = vertex.y;
  10739. vertexArray[ offset + 2 ] = vertex.z;
  10740. }
  10741. }
  10742. if ( dirtyColors ) {
  10743. for ( c = 0; c < cl; c ++ ) {
  10744. color = colors[ c ];
  10745. offset = c * 3;
  10746. colorArray[ offset ] = color.r;
  10747. colorArray[ offset + 1 ] = color.g;
  10748. colorArray[ offset + 2 ] = color.b;
  10749. }
  10750. }
  10751. if ( customAttributes ) {
  10752. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10753. customAttribute = customAttributes[ i ];
  10754. if ( customAttribute.needsUpdate &&
  10755. ( customAttribute.boundTo === undefined ||
  10756. customAttribute.boundTo === "vertices") ) {
  10757. cal = customAttribute.value.length;
  10758. offset = 0;
  10759. if ( customAttribute.size === 1 ) {
  10760. for ( ca = 0; ca < cal; ca ++ ) {
  10761. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10762. }
  10763. } else if ( customAttribute.size === 2 ) {
  10764. for ( ca = 0; ca < cal; ca ++ ) {
  10765. value = customAttribute.value[ ca ];
  10766. customAttribute.array[ offset ] = value.x;
  10767. customAttribute.array[ offset + 1 ] = value.y;
  10768. offset += 2;
  10769. }
  10770. } else if ( customAttribute.size === 3 ) {
  10771. if ( customAttribute.type === "c" ) {
  10772. for ( ca = 0; ca < cal; ca ++ ) {
  10773. value = customAttribute.value[ ca ];
  10774. customAttribute.array[ offset ] = value.r;
  10775. customAttribute.array[ offset + 1 ] = value.g;
  10776. customAttribute.array[ offset + 2 ] = value.b;
  10777. offset += 3;
  10778. }
  10779. } else {
  10780. for ( ca = 0; ca < cal; ca ++ ) {
  10781. value = customAttribute.value[ ca ];
  10782. customAttribute.array[ offset ] = value.x;
  10783. customAttribute.array[ offset + 1 ] = value.y;
  10784. customAttribute.array[ offset + 2 ] = value.z;
  10785. offset += 3;
  10786. }
  10787. }
  10788. } else if ( customAttribute.size === 4 ) {
  10789. for ( ca = 0; ca < cal; ca ++ ) {
  10790. value = customAttribute.value[ ca ];
  10791. customAttribute.array[ offset ] = value.x;
  10792. customAttribute.array[ offset + 1 ] = value.y;
  10793. customAttribute.array[ offset + 2 ] = value.z;
  10794. customAttribute.array[ offset + 3 ] = value.w;
  10795. offset += 4;
  10796. }
  10797. }
  10798. }
  10799. }
  10800. }
  10801. }
  10802. if ( dirtyVertices || object.sortParticles ) {
  10803. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10804. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10805. }
  10806. if ( dirtyColors || object.sortParticles ) {
  10807. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10808. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10809. }
  10810. if ( customAttributes ) {
  10811. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10812. customAttribute = customAttributes[ i ];
  10813. if ( customAttribute.needsUpdate || object.sortParticles ) {
  10814. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10815. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10816. }
  10817. }
  10818. }
  10819. };
  10820. function setLineBuffers ( geometry, hint ) {
  10821. var v, c, d, vertex, offset, color,
  10822. vertices = geometry.vertices,
  10823. colors = geometry.colors,
  10824. lineDistances = geometry.lineDistances,
  10825. vl = vertices.length,
  10826. cl = colors.length,
  10827. dl = lineDistances.length,
  10828. vertexArray = geometry.__vertexArray,
  10829. colorArray = geometry.__colorArray,
  10830. lineDistanceArray = geometry.__lineDistanceArray,
  10831. dirtyVertices = geometry.verticesNeedUpdate,
  10832. dirtyColors = geometry.colorsNeedUpdate,
  10833. dirtyLineDistances = geometry.lineDistancesNeedUpdate,
  10834. customAttributes = geometry.__webglCustomAttributesList,
  10835. i, il,
  10836. a, ca, cal, value,
  10837. customAttribute;
  10838. if ( dirtyVertices ) {
  10839. for ( v = 0; v < vl; v ++ ) {
  10840. vertex = vertices[ v ];
  10841. offset = v * 3;
  10842. vertexArray[ offset ] = vertex.x;
  10843. vertexArray[ offset + 1 ] = vertex.y;
  10844. vertexArray[ offset + 2 ] = vertex.z;
  10845. }
  10846. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10847. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10848. }
  10849. if ( dirtyColors ) {
  10850. for ( c = 0; c < cl; c ++ ) {
  10851. color = colors[ c ];
  10852. offset = c * 3;
  10853. colorArray[ offset ] = color.r;
  10854. colorArray[ offset + 1 ] = color.g;
  10855. colorArray[ offset + 2 ] = color.b;
  10856. }
  10857. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10858. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10859. }
  10860. if ( dirtyLineDistances ) {
  10861. for ( d = 0; d < dl; d ++ ) {
  10862. lineDistanceArray[ d ] = lineDistances[ d ];
  10863. }
  10864. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglLineDistanceBuffer );
  10865. _gl.bufferData( _gl.ARRAY_BUFFER, lineDistanceArray, hint );
  10866. }
  10867. if ( customAttributes ) {
  10868. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10869. customAttribute = customAttributes[ i ];
  10870. if ( customAttribute.needsUpdate &&
  10871. ( customAttribute.boundTo === undefined ||
  10872. customAttribute.boundTo === "vertices" ) ) {
  10873. offset = 0;
  10874. cal = customAttribute.value.length;
  10875. if ( customAttribute.size === 1 ) {
  10876. for ( ca = 0; ca < cal; ca ++ ) {
  10877. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10878. }
  10879. } else if ( customAttribute.size === 2 ) {
  10880. for ( ca = 0; ca < cal; ca ++ ) {
  10881. value = customAttribute.value[ ca ];
  10882. customAttribute.array[ offset ] = value.x;
  10883. customAttribute.array[ offset + 1 ] = value.y;
  10884. offset += 2;
  10885. }
  10886. } else if ( customAttribute.size === 3 ) {
  10887. if ( customAttribute.type === "c" ) {
  10888. for ( ca = 0; ca < cal; ca ++ ) {
  10889. value = customAttribute.value[ ca ];
  10890. customAttribute.array[ offset ] = value.r;
  10891. customAttribute.array[ offset + 1 ] = value.g;
  10892. customAttribute.array[ offset + 2 ] = value.b;
  10893. offset += 3;
  10894. }
  10895. } else {
  10896. for ( ca = 0; ca < cal; ca ++ ) {
  10897. value = customAttribute.value[ ca ];
  10898. customAttribute.array[ offset ] = value.x;
  10899. customAttribute.array[ offset + 1 ] = value.y;
  10900. customAttribute.array[ offset + 2 ] = value.z;
  10901. offset += 3;
  10902. }
  10903. }
  10904. } else if ( customAttribute.size === 4 ) {
  10905. for ( ca = 0; ca < cal; ca ++ ) {
  10906. value = customAttribute.value[ ca ];
  10907. customAttribute.array[ offset ] = value.x;
  10908. customAttribute.array[ offset + 1 ] = value.y;
  10909. customAttribute.array[ offset + 2 ] = value.z;
  10910. customAttribute.array[ offset + 3 ] = value.w;
  10911. offset += 4;
  10912. }
  10913. }
  10914. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  10915. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  10916. }
  10917. }
  10918. }
  10919. };
  10920. function setRibbonBuffers ( geometry, hint ) {
  10921. var v, c, n, vertex, offset, color, normal,
  10922. i, il, ca, cal, customAttribute, value,
  10923. vertices = geometry.vertices,
  10924. colors = geometry.colors,
  10925. normals = geometry.normals,
  10926. vl = vertices.length,
  10927. cl = colors.length,
  10928. nl = normals.length,
  10929. vertexArray = geometry.__vertexArray,
  10930. colorArray = geometry.__colorArray,
  10931. normalArray = geometry.__normalArray,
  10932. dirtyVertices = geometry.verticesNeedUpdate,
  10933. dirtyColors = geometry.colorsNeedUpdate,
  10934. dirtyNormals = geometry.normalsNeedUpdate,
  10935. customAttributes = geometry.__webglCustomAttributesList;
  10936. if ( dirtyVertices ) {
  10937. for ( v = 0; v < vl; v ++ ) {
  10938. vertex = vertices[ v ];
  10939. offset = v * 3;
  10940. vertexArray[ offset ] = vertex.x;
  10941. vertexArray[ offset + 1 ] = vertex.y;
  10942. vertexArray[ offset + 2 ] = vertex.z;
  10943. }
  10944. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  10945. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  10946. }
  10947. if ( dirtyColors ) {
  10948. for ( c = 0; c < cl; c ++ ) {
  10949. color = colors[ c ];
  10950. offset = c * 3;
  10951. colorArray[ offset ] = color.r;
  10952. colorArray[ offset + 1 ] = color.g;
  10953. colorArray[ offset + 2 ] = color.b;
  10954. }
  10955. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  10956. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  10957. }
  10958. if ( dirtyNormals ) {
  10959. for ( n = 0; n < nl; n ++ ) {
  10960. normal = normals[ n ];
  10961. offset = n * 3;
  10962. normalArray[ offset ] = normal.x;
  10963. normalArray[ offset + 1 ] = normal.y;
  10964. normalArray[ offset + 2 ] = normal.z;
  10965. }
  10966. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglNormalBuffer );
  10967. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  10968. }
  10969. if ( customAttributes ) {
  10970. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  10971. customAttribute = customAttributes[ i ];
  10972. if ( customAttribute.needsUpdate &&
  10973. ( customAttribute.boundTo === undefined ||
  10974. customAttribute.boundTo === "vertices" ) ) {
  10975. offset = 0;
  10976. cal = customAttribute.value.length;
  10977. if ( customAttribute.size === 1 ) {
  10978. for ( ca = 0; ca < cal; ca ++ ) {
  10979. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  10980. }
  10981. } else if ( customAttribute.size === 2 ) {
  10982. for ( ca = 0; ca < cal; ca ++ ) {
  10983. value = customAttribute.value[ ca ];
  10984. customAttribute.array[ offset ] = value.x;
  10985. customAttribute.array[ offset + 1 ] = value.y;
  10986. offset += 2;
  10987. }
  10988. } else if ( customAttribute.size === 3 ) {
  10989. if ( customAttribute.type === "c" ) {
  10990. for ( ca = 0; ca < cal; ca ++ ) {
  10991. value = customAttribute.value[ ca ];
  10992. customAttribute.array[ offset ] = value.r;
  10993. customAttribute.array[ offset + 1 ] = value.g;
  10994. customAttribute.array[ offset + 2 ] = value.b;
  10995. offset += 3;
  10996. }
  10997. } else {
  10998. for ( ca = 0; ca < cal; ca ++ ) {
  10999. value = customAttribute.value[ ca ];
  11000. customAttribute.array[ offset ] = value.x;
  11001. customAttribute.array[ offset + 1 ] = value.y;
  11002. customAttribute.array[ offset + 2 ] = value.z;
  11003. offset += 3;
  11004. }
  11005. }
  11006. } else if ( customAttribute.size === 4 ) {
  11007. for ( ca = 0; ca < cal; ca ++ ) {
  11008. value = customAttribute.value[ ca ];
  11009. customAttribute.array[ offset ] = value.x;
  11010. customAttribute.array[ offset + 1 ] = value.y;
  11011. customAttribute.array[ offset + 2 ] = value.z;
  11012. customAttribute.array[ offset + 3 ] = value.w;
  11013. offset += 4;
  11014. }
  11015. }
  11016. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11017. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11018. }
  11019. }
  11020. }
  11021. };
  11022. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  11023. if ( ! geometryGroup.__inittedArrays ) {
  11024. return;
  11025. }
  11026. var normalType = bufferGuessNormalType( material ),
  11027. vertexColorType = bufferGuessVertexColorType( material ),
  11028. uvType = bufferGuessUVType( material ),
  11029. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  11030. var f, fl, fi, face,
  11031. vertexNormals, faceNormal, normal,
  11032. vertexColors, faceColor,
  11033. vertexTangents,
  11034. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  11035. c1, c2, c3, c4,
  11036. sw1, sw2, sw3, sw4,
  11037. si1, si2, si3, si4,
  11038. sa1, sa2, sa3, sa4,
  11039. sb1, sb2, sb3, sb4,
  11040. m, ml, i, il,
  11041. vn, uvi, uv2i,
  11042. vk, vkl, vka,
  11043. nka, chf, faceVertexNormals,
  11044. a,
  11045. vertexIndex = 0,
  11046. offset = 0,
  11047. offset_uv = 0,
  11048. offset_uv2 = 0,
  11049. offset_face = 0,
  11050. offset_normal = 0,
  11051. offset_tangent = 0,
  11052. offset_line = 0,
  11053. offset_color = 0,
  11054. offset_skin = 0,
  11055. offset_morphTarget = 0,
  11056. offset_custom = 0,
  11057. offset_customSrc = 0,
  11058. value,
  11059. vertexArray = geometryGroup.__vertexArray,
  11060. uvArray = geometryGroup.__uvArray,
  11061. uv2Array = geometryGroup.__uv2Array,
  11062. normalArray = geometryGroup.__normalArray,
  11063. tangentArray = geometryGroup.__tangentArray,
  11064. colorArray = geometryGroup.__colorArray,
  11065. skinIndexArray = geometryGroup.__skinIndexArray,
  11066. skinWeightArray = geometryGroup.__skinWeightArray,
  11067. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  11068. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  11069. customAttributes = geometryGroup.__webglCustomAttributesList,
  11070. customAttribute,
  11071. faceArray = geometryGroup.__faceArray,
  11072. lineArray = geometryGroup.__lineArray,
  11073. geometry = object.geometry, // this is shared for all chunks
  11074. dirtyVertices = geometry.verticesNeedUpdate,
  11075. dirtyElements = geometry.elementsNeedUpdate,
  11076. dirtyUvs = geometry.uvsNeedUpdate,
  11077. dirtyNormals = geometry.normalsNeedUpdate,
  11078. dirtyTangents = geometry.tangentsNeedUpdate,
  11079. dirtyColors = geometry.colorsNeedUpdate,
  11080. dirtyMorphTargets = geometry.morphTargetsNeedUpdate,
  11081. vertices = geometry.vertices,
  11082. chunk_faces3 = geometryGroup.faces3,
  11083. chunk_faces4 = geometryGroup.faces4,
  11084. obj_faces = geometry.faces,
  11085. obj_uvs = geometry.faceVertexUvs[ 0 ],
  11086. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  11087. obj_colors = geometry.colors,
  11088. obj_skinIndices = geometry.skinIndices,
  11089. obj_skinWeights = geometry.skinWeights,
  11090. morphTargets = geometry.morphTargets,
  11091. morphNormals = geometry.morphNormals;
  11092. if ( dirtyVertices ) {
  11093. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11094. face = obj_faces[ chunk_faces3[ f ] ];
  11095. v1 = vertices[ face.a ];
  11096. v2 = vertices[ face.b ];
  11097. v3 = vertices[ face.c ];
  11098. vertexArray[ offset ] = v1.x;
  11099. vertexArray[ offset + 1 ] = v1.y;
  11100. vertexArray[ offset + 2 ] = v1.z;
  11101. vertexArray[ offset + 3 ] = v2.x;
  11102. vertexArray[ offset + 4 ] = v2.y;
  11103. vertexArray[ offset + 5 ] = v2.z;
  11104. vertexArray[ offset + 6 ] = v3.x;
  11105. vertexArray[ offset + 7 ] = v3.y;
  11106. vertexArray[ offset + 8 ] = v3.z;
  11107. offset += 9;
  11108. }
  11109. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11110. face = obj_faces[ chunk_faces4[ f ] ];
  11111. v1 = vertices[ face.a ];
  11112. v2 = vertices[ face.b ];
  11113. v3 = vertices[ face.c ];
  11114. v4 = vertices[ face.d ];
  11115. vertexArray[ offset ] = v1.x;
  11116. vertexArray[ offset + 1 ] = v1.y;
  11117. vertexArray[ offset + 2 ] = v1.z;
  11118. vertexArray[ offset + 3 ] = v2.x;
  11119. vertexArray[ offset + 4 ] = v2.y;
  11120. vertexArray[ offset + 5 ] = v2.z;
  11121. vertexArray[ offset + 6 ] = v3.x;
  11122. vertexArray[ offset + 7 ] = v3.y;
  11123. vertexArray[ offset + 8 ] = v3.z;
  11124. vertexArray[ offset + 9 ] = v4.x;
  11125. vertexArray[ offset + 10 ] = v4.y;
  11126. vertexArray[ offset + 11 ] = v4.z;
  11127. offset += 12;
  11128. }
  11129. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  11130. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  11131. }
  11132. if ( dirtyMorphTargets ) {
  11133. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  11134. offset_morphTarget = 0;
  11135. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11136. chf = chunk_faces3[ f ];
  11137. face = obj_faces[ chf ];
  11138. // morph positions
  11139. v1 = morphTargets[ vk ].vertices[ face.a ];
  11140. v2 = morphTargets[ vk ].vertices[ face.b ];
  11141. v3 = morphTargets[ vk ].vertices[ face.c ];
  11142. vka = morphTargetsArrays[ vk ];
  11143. vka[ offset_morphTarget ] = v1.x;
  11144. vka[ offset_morphTarget + 1 ] = v1.y;
  11145. vka[ offset_morphTarget + 2 ] = v1.z;
  11146. vka[ offset_morphTarget + 3 ] = v2.x;
  11147. vka[ offset_morphTarget + 4 ] = v2.y;
  11148. vka[ offset_morphTarget + 5 ] = v2.z;
  11149. vka[ offset_morphTarget + 6 ] = v3.x;
  11150. vka[ offset_morphTarget + 7 ] = v3.y;
  11151. vka[ offset_morphTarget + 8 ] = v3.z;
  11152. // morph normals
  11153. if ( material.morphNormals ) {
  11154. if ( needsSmoothNormals ) {
  11155. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11156. n1 = faceVertexNormals.a;
  11157. n2 = faceVertexNormals.b;
  11158. n3 = faceVertexNormals.c;
  11159. } else {
  11160. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11161. n2 = n1;
  11162. n3 = n1;
  11163. }
  11164. nka = morphNormalsArrays[ vk ];
  11165. nka[ offset_morphTarget ] = n1.x;
  11166. nka[ offset_morphTarget + 1 ] = n1.y;
  11167. nka[ offset_morphTarget + 2 ] = n1.z;
  11168. nka[ offset_morphTarget + 3 ] = n2.x;
  11169. nka[ offset_morphTarget + 4 ] = n2.y;
  11170. nka[ offset_morphTarget + 5 ] = n2.z;
  11171. nka[ offset_morphTarget + 6 ] = n3.x;
  11172. nka[ offset_morphTarget + 7 ] = n3.y;
  11173. nka[ offset_morphTarget + 8 ] = n3.z;
  11174. }
  11175. //
  11176. offset_morphTarget += 9;
  11177. }
  11178. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11179. chf = chunk_faces4[ f ];
  11180. face = obj_faces[ chf ];
  11181. // morph positions
  11182. v1 = morphTargets[ vk ].vertices[ face.a ];
  11183. v2 = morphTargets[ vk ].vertices[ face.b ];
  11184. v3 = morphTargets[ vk ].vertices[ face.c ];
  11185. v4 = morphTargets[ vk ].vertices[ face.d ];
  11186. vka = morphTargetsArrays[ vk ];
  11187. vka[ offset_morphTarget ] = v1.x;
  11188. vka[ offset_morphTarget + 1 ] = v1.y;
  11189. vka[ offset_morphTarget + 2 ] = v1.z;
  11190. vka[ offset_morphTarget + 3 ] = v2.x;
  11191. vka[ offset_morphTarget + 4 ] = v2.y;
  11192. vka[ offset_morphTarget + 5 ] = v2.z;
  11193. vka[ offset_morphTarget + 6 ] = v3.x;
  11194. vka[ offset_morphTarget + 7 ] = v3.y;
  11195. vka[ offset_morphTarget + 8 ] = v3.z;
  11196. vka[ offset_morphTarget + 9 ] = v4.x;
  11197. vka[ offset_morphTarget + 10 ] = v4.y;
  11198. vka[ offset_morphTarget + 11 ] = v4.z;
  11199. // morph normals
  11200. if ( material.morphNormals ) {
  11201. if ( needsSmoothNormals ) {
  11202. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  11203. n1 = faceVertexNormals.a;
  11204. n2 = faceVertexNormals.b;
  11205. n3 = faceVertexNormals.c;
  11206. n4 = faceVertexNormals.d;
  11207. } else {
  11208. n1 = morphNormals[ vk ].faceNormals[ chf ];
  11209. n2 = n1;
  11210. n3 = n1;
  11211. n4 = n1;
  11212. }
  11213. nka = morphNormalsArrays[ vk ];
  11214. nka[ offset_morphTarget ] = n1.x;
  11215. nka[ offset_morphTarget + 1 ] = n1.y;
  11216. nka[ offset_morphTarget + 2 ] = n1.z;
  11217. nka[ offset_morphTarget + 3 ] = n2.x;
  11218. nka[ offset_morphTarget + 4 ] = n2.y;
  11219. nka[ offset_morphTarget + 5 ] = n2.z;
  11220. nka[ offset_morphTarget + 6 ] = n3.x;
  11221. nka[ offset_morphTarget + 7 ] = n3.y;
  11222. nka[ offset_morphTarget + 8 ] = n3.z;
  11223. nka[ offset_morphTarget + 9 ] = n4.x;
  11224. nka[ offset_morphTarget + 10 ] = n4.y;
  11225. nka[ offset_morphTarget + 11 ] = n4.z;
  11226. }
  11227. //
  11228. offset_morphTarget += 12;
  11229. }
  11230. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  11231. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  11232. if ( material.morphNormals ) {
  11233. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  11234. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  11235. }
  11236. }
  11237. }
  11238. if ( obj_skinWeights.length ) {
  11239. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11240. face = obj_faces[ chunk_faces3[ f ] ];
  11241. // weights
  11242. sw1 = obj_skinWeights[ face.a ];
  11243. sw2 = obj_skinWeights[ face.b ];
  11244. sw3 = obj_skinWeights[ face.c ];
  11245. skinWeightArray[ offset_skin ] = sw1.x;
  11246. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11247. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11248. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11249. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11250. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11251. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11252. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11253. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11254. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11255. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11256. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11257. // indices
  11258. si1 = obj_skinIndices[ face.a ];
  11259. si2 = obj_skinIndices[ face.b ];
  11260. si3 = obj_skinIndices[ face.c ];
  11261. skinIndexArray[ offset_skin ] = si1.x;
  11262. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11263. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11264. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11265. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11266. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11267. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11268. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11269. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11270. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11271. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11272. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11273. offset_skin += 12;
  11274. }
  11275. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11276. face = obj_faces[ chunk_faces4[ f ] ];
  11277. // weights
  11278. sw1 = obj_skinWeights[ face.a ];
  11279. sw2 = obj_skinWeights[ face.b ];
  11280. sw3 = obj_skinWeights[ face.c ];
  11281. sw4 = obj_skinWeights[ face.d ];
  11282. skinWeightArray[ offset_skin ] = sw1.x;
  11283. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  11284. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  11285. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  11286. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  11287. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  11288. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  11289. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  11290. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  11291. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  11292. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  11293. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  11294. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  11295. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  11296. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  11297. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  11298. // indices
  11299. si1 = obj_skinIndices[ face.a ];
  11300. si2 = obj_skinIndices[ face.b ];
  11301. si3 = obj_skinIndices[ face.c ];
  11302. si4 = obj_skinIndices[ face.d ];
  11303. skinIndexArray[ offset_skin ] = si1.x;
  11304. skinIndexArray[ offset_skin + 1 ] = si1.y;
  11305. skinIndexArray[ offset_skin + 2 ] = si1.z;
  11306. skinIndexArray[ offset_skin + 3 ] = si1.w;
  11307. skinIndexArray[ offset_skin + 4 ] = si2.x;
  11308. skinIndexArray[ offset_skin + 5 ] = si2.y;
  11309. skinIndexArray[ offset_skin + 6 ] = si2.z;
  11310. skinIndexArray[ offset_skin + 7 ] = si2.w;
  11311. skinIndexArray[ offset_skin + 8 ] = si3.x;
  11312. skinIndexArray[ offset_skin + 9 ] = si3.y;
  11313. skinIndexArray[ offset_skin + 10 ] = si3.z;
  11314. skinIndexArray[ offset_skin + 11 ] = si3.w;
  11315. skinIndexArray[ offset_skin + 12 ] = si4.x;
  11316. skinIndexArray[ offset_skin + 13 ] = si4.y;
  11317. skinIndexArray[ offset_skin + 14 ] = si4.z;
  11318. skinIndexArray[ offset_skin + 15 ] = si4.w;
  11319. offset_skin += 16;
  11320. }
  11321. if ( offset_skin > 0 ) {
  11322. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  11323. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  11324. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  11325. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  11326. }
  11327. }
  11328. if ( dirtyColors && vertexColorType ) {
  11329. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11330. face = obj_faces[ chunk_faces3[ f ] ];
  11331. vertexColors = face.vertexColors;
  11332. faceColor = face.color;
  11333. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  11334. c1 = vertexColors[ 0 ];
  11335. c2 = vertexColors[ 1 ];
  11336. c3 = vertexColors[ 2 ];
  11337. } else {
  11338. c1 = faceColor;
  11339. c2 = faceColor;
  11340. c3 = faceColor;
  11341. }
  11342. colorArray[ offset_color ] = c1.r;
  11343. colorArray[ offset_color + 1 ] = c1.g;
  11344. colorArray[ offset_color + 2 ] = c1.b;
  11345. colorArray[ offset_color + 3 ] = c2.r;
  11346. colorArray[ offset_color + 4 ] = c2.g;
  11347. colorArray[ offset_color + 5 ] = c2.b;
  11348. colorArray[ offset_color + 6 ] = c3.r;
  11349. colorArray[ offset_color + 7 ] = c3.g;
  11350. colorArray[ offset_color + 8 ] = c3.b;
  11351. offset_color += 9;
  11352. }
  11353. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11354. face = obj_faces[ chunk_faces4[ f ] ];
  11355. vertexColors = face.vertexColors;
  11356. faceColor = face.color;
  11357. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  11358. c1 = vertexColors[ 0 ];
  11359. c2 = vertexColors[ 1 ];
  11360. c3 = vertexColors[ 2 ];
  11361. c4 = vertexColors[ 3 ];
  11362. } else {
  11363. c1 = faceColor;
  11364. c2 = faceColor;
  11365. c3 = faceColor;
  11366. c4 = faceColor;
  11367. }
  11368. colorArray[ offset_color ] = c1.r;
  11369. colorArray[ offset_color + 1 ] = c1.g;
  11370. colorArray[ offset_color + 2 ] = c1.b;
  11371. colorArray[ offset_color + 3 ] = c2.r;
  11372. colorArray[ offset_color + 4 ] = c2.g;
  11373. colorArray[ offset_color + 5 ] = c2.b;
  11374. colorArray[ offset_color + 6 ] = c3.r;
  11375. colorArray[ offset_color + 7 ] = c3.g;
  11376. colorArray[ offset_color + 8 ] = c3.b;
  11377. colorArray[ offset_color + 9 ] = c4.r;
  11378. colorArray[ offset_color + 10 ] = c4.g;
  11379. colorArray[ offset_color + 11 ] = c4.b;
  11380. offset_color += 12;
  11381. }
  11382. if ( offset_color > 0 ) {
  11383. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  11384. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  11385. }
  11386. }
  11387. if ( dirtyTangents && geometry.hasTangents ) {
  11388. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11389. face = obj_faces[ chunk_faces3[ f ] ];
  11390. vertexTangents = face.vertexTangents;
  11391. t1 = vertexTangents[ 0 ];
  11392. t2 = vertexTangents[ 1 ];
  11393. t3 = vertexTangents[ 2 ];
  11394. tangentArray[ offset_tangent ] = t1.x;
  11395. tangentArray[ offset_tangent + 1 ] = t1.y;
  11396. tangentArray[ offset_tangent + 2 ] = t1.z;
  11397. tangentArray[ offset_tangent + 3 ] = t1.w;
  11398. tangentArray[ offset_tangent + 4 ] = t2.x;
  11399. tangentArray[ offset_tangent + 5 ] = t2.y;
  11400. tangentArray[ offset_tangent + 6 ] = t2.z;
  11401. tangentArray[ offset_tangent + 7 ] = t2.w;
  11402. tangentArray[ offset_tangent + 8 ] = t3.x;
  11403. tangentArray[ offset_tangent + 9 ] = t3.y;
  11404. tangentArray[ offset_tangent + 10 ] = t3.z;
  11405. tangentArray[ offset_tangent + 11 ] = t3.w;
  11406. offset_tangent += 12;
  11407. }
  11408. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11409. face = obj_faces[ chunk_faces4[ f ] ];
  11410. vertexTangents = face.vertexTangents;
  11411. t1 = vertexTangents[ 0 ];
  11412. t2 = vertexTangents[ 1 ];
  11413. t3 = vertexTangents[ 2 ];
  11414. t4 = vertexTangents[ 3 ];
  11415. tangentArray[ offset_tangent ] = t1.x;
  11416. tangentArray[ offset_tangent + 1 ] = t1.y;
  11417. tangentArray[ offset_tangent + 2 ] = t1.z;
  11418. tangentArray[ offset_tangent + 3 ] = t1.w;
  11419. tangentArray[ offset_tangent + 4 ] = t2.x;
  11420. tangentArray[ offset_tangent + 5 ] = t2.y;
  11421. tangentArray[ offset_tangent + 6 ] = t2.z;
  11422. tangentArray[ offset_tangent + 7 ] = t2.w;
  11423. tangentArray[ offset_tangent + 8 ] = t3.x;
  11424. tangentArray[ offset_tangent + 9 ] = t3.y;
  11425. tangentArray[ offset_tangent + 10 ] = t3.z;
  11426. tangentArray[ offset_tangent + 11 ] = t3.w;
  11427. tangentArray[ offset_tangent + 12 ] = t4.x;
  11428. tangentArray[ offset_tangent + 13 ] = t4.y;
  11429. tangentArray[ offset_tangent + 14 ] = t4.z;
  11430. tangentArray[ offset_tangent + 15 ] = t4.w;
  11431. offset_tangent += 16;
  11432. }
  11433. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  11434. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  11435. }
  11436. if ( dirtyNormals && normalType ) {
  11437. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11438. face = obj_faces[ chunk_faces3[ f ] ];
  11439. vertexNormals = face.vertexNormals;
  11440. faceNormal = face.normal;
  11441. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  11442. for ( i = 0; i < 3; i ++ ) {
  11443. vn = vertexNormals[ i ];
  11444. normalArray[ offset_normal ] = vn.x;
  11445. normalArray[ offset_normal + 1 ] = vn.y;
  11446. normalArray[ offset_normal + 2 ] = vn.z;
  11447. offset_normal += 3;
  11448. }
  11449. } else {
  11450. for ( i = 0; i < 3; i ++ ) {
  11451. normalArray[ offset_normal ] = faceNormal.x;
  11452. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11453. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11454. offset_normal += 3;
  11455. }
  11456. }
  11457. }
  11458. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11459. face = obj_faces[ chunk_faces4[ f ] ];
  11460. vertexNormals = face.vertexNormals;
  11461. faceNormal = face.normal;
  11462. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  11463. for ( i = 0; i < 4; i ++ ) {
  11464. vn = vertexNormals[ i ];
  11465. normalArray[ offset_normal ] = vn.x;
  11466. normalArray[ offset_normal + 1 ] = vn.y;
  11467. normalArray[ offset_normal + 2 ] = vn.z;
  11468. offset_normal += 3;
  11469. }
  11470. } else {
  11471. for ( i = 0; i < 4; i ++ ) {
  11472. normalArray[ offset_normal ] = faceNormal.x;
  11473. normalArray[ offset_normal + 1 ] = faceNormal.y;
  11474. normalArray[ offset_normal + 2 ] = faceNormal.z;
  11475. offset_normal += 3;
  11476. }
  11477. }
  11478. }
  11479. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  11480. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  11481. }
  11482. if ( dirtyUvs && obj_uvs && uvType ) {
  11483. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11484. fi = chunk_faces3[ f ];
  11485. uv = obj_uvs[ fi ];
  11486. if ( uv === undefined ) continue;
  11487. for ( i = 0; i < 3; i ++ ) {
  11488. uvi = uv[ i ];
  11489. uvArray[ offset_uv ] = uvi.u;
  11490. uvArray[ offset_uv + 1 ] = uvi.v;
  11491. offset_uv += 2;
  11492. }
  11493. }
  11494. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11495. fi = chunk_faces4[ f ];
  11496. uv = obj_uvs[ fi ];
  11497. if ( uv === undefined ) continue;
  11498. for ( i = 0; i < 4; i ++ ) {
  11499. uvi = uv[ i ];
  11500. uvArray[ offset_uv ] = uvi.u;
  11501. uvArray[ offset_uv + 1 ] = uvi.v;
  11502. offset_uv += 2;
  11503. }
  11504. }
  11505. if ( offset_uv > 0 ) {
  11506. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  11507. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  11508. }
  11509. }
  11510. if ( dirtyUvs && obj_uvs2 && uvType ) {
  11511. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11512. fi = chunk_faces3[ f ];
  11513. uv2 = obj_uvs2[ fi ];
  11514. if ( uv2 === undefined ) continue;
  11515. for ( i = 0; i < 3; i ++ ) {
  11516. uv2i = uv2[ i ];
  11517. uv2Array[ offset_uv2 ] = uv2i.u;
  11518. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  11519. offset_uv2 += 2;
  11520. }
  11521. }
  11522. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11523. fi = chunk_faces4[ f ];
  11524. uv2 = obj_uvs2[ fi ];
  11525. if ( uv2 === undefined ) continue;
  11526. for ( i = 0; i < 4; i ++ ) {
  11527. uv2i = uv2[ i ];
  11528. uv2Array[ offset_uv2 ] = uv2i.u;
  11529. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  11530. offset_uv2 += 2;
  11531. }
  11532. }
  11533. if ( offset_uv2 > 0 ) {
  11534. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  11535. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  11536. }
  11537. }
  11538. if ( dirtyElements ) {
  11539. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11540. faceArray[ offset_face ] = vertexIndex;
  11541. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11542. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  11543. offset_face += 3;
  11544. lineArray[ offset_line ] = vertexIndex;
  11545. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11546. lineArray[ offset_line + 2 ] = vertexIndex;
  11547. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  11548. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11549. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11550. offset_line += 6;
  11551. vertexIndex += 3;
  11552. }
  11553. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11554. faceArray[ offset_face ] = vertexIndex;
  11555. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  11556. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  11557. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  11558. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  11559. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  11560. offset_face += 6;
  11561. lineArray[ offset_line ] = vertexIndex;
  11562. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  11563. lineArray[ offset_line + 2 ] = vertexIndex;
  11564. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  11565. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  11566. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  11567. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  11568. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  11569. offset_line += 8;
  11570. vertexIndex += 4;
  11571. }
  11572. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  11573. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  11574. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  11575. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  11576. }
  11577. if ( customAttributes ) {
  11578. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  11579. customAttribute = customAttributes[ i ];
  11580. if ( ! customAttribute.__original.needsUpdate ) continue;
  11581. offset_custom = 0;
  11582. offset_customSrc = 0;
  11583. if ( customAttribute.size === 1 ) {
  11584. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11585. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11586. face = obj_faces[ chunk_faces3[ f ] ];
  11587. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11588. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11589. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11590. offset_custom += 3;
  11591. }
  11592. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11593. face = obj_faces[ chunk_faces4[ f ] ];
  11594. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  11595. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  11596. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  11597. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  11598. offset_custom += 4;
  11599. }
  11600. } else if ( customAttribute.boundTo === "faces" ) {
  11601. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11602. value = customAttribute.value[ chunk_faces3[ f ] ];
  11603. customAttribute.array[ offset_custom ] = value;
  11604. customAttribute.array[ offset_custom + 1 ] = value;
  11605. customAttribute.array[ offset_custom + 2 ] = value;
  11606. offset_custom += 3;
  11607. }
  11608. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11609. value = customAttribute.value[ chunk_faces4[ f ] ];
  11610. customAttribute.array[ offset_custom ] = value;
  11611. customAttribute.array[ offset_custom + 1 ] = value;
  11612. customAttribute.array[ offset_custom + 2 ] = value;
  11613. customAttribute.array[ offset_custom + 3 ] = value;
  11614. offset_custom += 4;
  11615. }
  11616. }
  11617. } else if ( customAttribute.size === 2 ) {
  11618. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11619. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11620. face = obj_faces[ chunk_faces3[ f ] ];
  11621. v1 = customAttribute.value[ face.a ];
  11622. v2 = customAttribute.value[ face.b ];
  11623. v3 = customAttribute.value[ face.c ];
  11624. customAttribute.array[ offset_custom ] = v1.x;
  11625. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11626. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11627. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11628. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11629. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11630. offset_custom += 6;
  11631. }
  11632. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11633. face = obj_faces[ chunk_faces4[ f ] ];
  11634. v1 = customAttribute.value[ face.a ];
  11635. v2 = customAttribute.value[ face.b ];
  11636. v3 = customAttribute.value[ face.c ];
  11637. v4 = customAttribute.value[ face.d ];
  11638. customAttribute.array[ offset_custom ] = v1.x;
  11639. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11640. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11641. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11642. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11643. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11644. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11645. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11646. offset_custom += 8;
  11647. }
  11648. } else if ( customAttribute.boundTo === "faces" ) {
  11649. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11650. value = customAttribute.value[ chunk_faces3[ f ] ];
  11651. v1 = value;
  11652. v2 = value;
  11653. v3 = value;
  11654. customAttribute.array[ offset_custom ] = v1.x;
  11655. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11656. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11657. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11658. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11659. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11660. offset_custom += 6;
  11661. }
  11662. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11663. value = customAttribute.value[ chunk_faces4[ f ] ];
  11664. v1 = value;
  11665. v2 = value;
  11666. v3 = value;
  11667. v4 = value;
  11668. customAttribute.array[ offset_custom ] = v1.x;
  11669. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11670. customAttribute.array[ offset_custom + 2 ] = v2.x;
  11671. customAttribute.array[ offset_custom + 3 ] = v2.y;
  11672. customAttribute.array[ offset_custom + 4 ] = v3.x;
  11673. customAttribute.array[ offset_custom + 5 ] = v3.y;
  11674. customAttribute.array[ offset_custom + 6 ] = v4.x;
  11675. customAttribute.array[ offset_custom + 7 ] = v4.y;
  11676. offset_custom += 8;
  11677. }
  11678. }
  11679. } else if ( customAttribute.size === 3 ) {
  11680. var pp;
  11681. if ( customAttribute.type === "c" ) {
  11682. pp = [ "r", "g", "b" ];
  11683. } else {
  11684. pp = [ "x", "y", "z" ];
  11685. }
  11686. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11687. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11688. face = obj_faces[ chunk_faces3[ f ] ];
  11689. v1 = customAttribute.value[ face.a ];
  11690. v2 = customAttribute.value[ face.b ];
  11691. v3 = customAttribute.value[ face.c ];
  11692. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11693. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11694. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11695. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11696. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11697. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11698. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11699. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11700. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11701. offset_custom += 9;
  11702. }
  11703. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11704. face = obj_faces[ chunk_faces4[ f ] ];
  11705. v1 = customAttribute.value[ face.a ];
  11706. v2 = customAttribute.value[ face.b ];
  11707. v3 = customAttribute.value[ face.c ];
  11708. v4 = customAttribute.value[ face.d ];
  11709. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11710. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11711. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11712. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11713. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11714. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11715. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11716. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11717. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11718. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11719. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11720. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11721. offset_custom += 12;
  11722. }
  11723. } else if ( customAttribute.boundTo === "faces" ) {
  11724. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11725. value = customAttribute.value[ chunk_faces3[ f ] ];
  11726. v1 = value;
  11727. v2 = value;
  11728. v3 = value;
  11729. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11730. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11731. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11732. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11733. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11734. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11735. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11736. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11737. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11738. offset_custom += 9;
  11739. }
  11740. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11741. value = customAttribute.value[ chunk_faces4[ f ] ];
  11742. v1 = value;
  11743. v2 = value;
  11744. v3 = value;
  11745. v4 = value;
  11746. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11747. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11748. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11749. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11750. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11751. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11752. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11753. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11754. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11755. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11756. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11757. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11758. offset_custom += 12;
  11759. }
  11760. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11761. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11762. value = customAttribute.value[ chunk_faces3[ f ] ];
  11763. v1 = value[ 0 ];
  11764. v2 = value[ 1 ];
  11765. v3 = value[ 2 ];
  11766. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11767. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11768. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11769. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11770. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11771. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11772. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11773. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11774. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11775. offset_custom += 9;
  11776. }
  11777. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11778. value = customAttribute.value[ chunk_faces4[ f ] ];
  11779. v1 = value[ 0 ];
  11780. v2 = value[ 1 ];
  11781. v3 = value[ 2 ];
  11782. v4 = value[ 3 ];
  11783. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  11784. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  11785. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  11786. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  11787. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  11788. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  11789. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  11790. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  11791. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  11792. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  11793. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  11794. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  11795. offset_custom += 12;
  11796. }
  11797. }
  11798. } else if ( customAttribute.size === 4 ) {
  11799. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  11800. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11801. face = obj_faces[ chunk_faces3[ f ] ];
  11802. v1 = customAttribute.value[ face.a ];
  11803. v2 = customAttribute.value[ face.b ];
  11804. v3 = customAttribute.value[ face.c ];
  11805. customAttribute.array[ offset_custom ] = v1.x;
  11806. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11807. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11808. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11809. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11810. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11811. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11812. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11813. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11814. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11815. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11816. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11817. offset_custom += 12;
  11818. }
  11819. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11820. face = obj_faces[ chunk_faces4[ f ] ];
  11821. v1 = customAttribute.value[ face.a ];
  11822. v2 = customAttribute.value[ face.b ];
  11823. v3 = customAttribute.value[ face.c ];
  11824. v4 = customAttribute.value[ face.d ];
  11825. customAttribute.array[ offset_custom ] = v1.x;
  11826. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11827. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11828. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11829. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11830. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11831. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11832. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11833. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11834. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11835. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11836. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11837. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11838. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11839. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11840. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11841. offset_custom += 16;
  11842. }
  11843. } else if ( customAttribute.boundTo === "faces" ) {
  11844. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11845. value = customAttribute.value[ chunk_faces3[ f ] ];
  11846. v1 = value;
  11847. v2 = value;
  11848. v3 = value;
  11849. customAttribute.array[ offset_custom ] = v1.x;
  11850. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11851. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11852. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11853. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11854. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11855. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11856. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11857. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11858. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11859. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11860. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11861. offset_custom += 12;
  11862. }
  11863. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11864. value = customAttribute.value[ chunk_faces4[ f ] ];
  11865. v1 = value;
  11866. v2 = value;
  11867. v3 = value;
  11868. v4 = value;
  11869. customAttribute.array[ offset_custom ] = v1.x;
  11870. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11871. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11872. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11873. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11874. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11875. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11876. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11877. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11878. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11879. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11880. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11881. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11882. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11883. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11884. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11885. offset_custom += 16;
  11886. }
  11887. } else if ( customAttribute.boundTo === "faceVertices" ) {
  11888. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  11889. value = customAttribute.value[ chunk_faces3[ f ] ];
  11890. v1 = value[ 0 ];
  11891. v2 = value[ 1 ];
  11892. v3 = value[ 2 ];
  11893. customAttribute.array[ offset_custom ] = v1.x;
  11894. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11895. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11896. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11897. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11898. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11899. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11900. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11901. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11902. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11903. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11904. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11905. offset_custom += 12;
  11906. }
  11907. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  11908. value = customAttribute.value[ chunk_faces4[ f ] ];
  11909. v1 = value[ 0 ];
  11910. v2 = value[ 1 ];
  11911. v3 = value[ 2 ];
  11912. v4 = value[ 3 ];
  11913. customAttribute.array[ offset_custom ] = v1.x;
  11914. customAttribute.array[ offset_custom + 1 ] = v1.y;
  11915. customAttribute.array[ offset_custom + 2 ] = v1.z;
  11916. customAttribute.array[ offset_custom + 3 ] = v1.w;
  11917. customAttribute.array[ offset_custom + 4 ] = v2.x;
  11918. customAttribute.array[ offset_custom + 5 ] = v2.y;
  11919. customAttribute.array[ offset_custom + 6 ] = v2.z;
  11920. customAttribute.array[ offset_custom + 7 ] = v2.w;
  11921. customAttribute.array[ offset_custom + 8 ] = v3.x;
  11922. customAttribute.array[ offset_custom + 9 ] = v3.y;
  11923. customAttribute.array[ offset_custom + 10 ] = v3.z;
  11924. customAttribute.array[ offset_custom + 11 ] = v3.w;
  11925. customAttribute.array[ offset_custom + 12 ] = v4.x;
  11926. customAttribute.array[ offset_custom + 13 ] = v4.y;
  11927. customAttribute.array[ offset_custom + 14 ] = v4.z;
  11928. customAttribute.array[ offset_custom + 15 ] = v4.w;
  11929. offset_custom += 16;
  11930. }
  11931. }
  11932. }
  11933. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  11934. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  11935. }
  11936. }
  11937. if ( dispose ) {
  11938. delete geometryGroup.__inittedArrays;
  11939. delete geometryGroup.__colorArray;
  11940. delete geometryGroup.__normalArray;
  11941. delete geometryGroup.__tangentArray;
  11942. delete geometryGroup.__uvArray;
  11943. delete geometryGroup.__uv2Array;
  11944. delete geometryGroup.__faceArray;
  11945. delete geometryGroup.__vertexArray;
  11946. delete geometryGroup.__lineArray;
  11947. delete geometryGroup.__skinIndexArray;
  11948. delete geometryGroup.__skinWeightArray;
  11949. }
  11950. };
  11951. function setDirectBuffers ( geometry, hint, dispose ) {
  11952. var attributes = geometry.attributes;
  11953. var index = attributes[ "index" ];
  11954. var position = attributes[ "position" ];
  11955. var normal = attributes[ "normal" ];
  11956. var uv = attributes[ "uv" ];
  11957. var color = attributes[ "color" ];
  11958. var tangent = attributes[ "tangent" ];
  11959. if ( geometry.elementsNeedUpdate && index !== undefined ) {
  11960. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  11961. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, index.array, hint );
  11962. }
  11963. if ( geometry.verticesNeedUpdate && position !== undefined ) {
  11964. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  11965. _gl.bufferData( _gl.ARRAY_BUFFER, position.array, hint );
  11966. }
  11967. if ( geometry.normalsNeedUpdate && normal !== undefined ) {
  11968. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  11969. _gl.bufferData( _gl.ARRAY_BUFFER, normal.array, hint );
  11970. }
  11971. if ( geometry.uvsNeedUpdate && uv !== undefined ) {
  11972. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  11973. _gl.bufferData( _gl.ARRAY_BUFFER, uv.array, hint );
  11974. }
  11975. if ( geometry.colorsNeedUpdate && color !== undefined ) {
  11976. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  11977. _gl.bufferData( _gl.ARRAY_BUFFER, color.array, hint );
  11978. }
  11979. if ( geometry.tangentsNeedUpdate && tangent !== undefined ) {
  11980. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  11981. _gl.bufferData( _gl.ARRAY_BUFFER, tangent.array, hint );
  11982. }
  11983. if ( dispose ) {
  11984. for ( var i in geometry.attributes ) {
  11985. delete geometry.attributes[ i ].array;
  11986. }
  11987. }
  11988. };
  11989. // Buffer rendering
  11990. this.renderBufferImmediate = function ( object, program, material ) {
  11991. if ( object.hasPositions && ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  11992. if ( object.hasNormals && ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  11993. if ( object.hasUvs && ! object.__webglUvBuffer ) object.__webglUvBuffer = _gl.createBuffer();
  11994. if ( object.hasColors && ! object.__webglColorBuffer ) object.__webglColorBuffer = _gl.createBuffer();
  11995. if ( object.hasPositions ) {
  11996. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  11997. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  11998. _gl.enableVertexAttribArray( program.attributes.position );
  11999. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12000. }
  12001. if ( object.hasNormals ) {
  12002. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  12003. if ( material.shading === THREE.FlatShading ) {
  12004. var nx, ny, nz,
  12005. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  12006. normalArray,
  12007. i, il = object.count * 3;
  12008. for( i = 0; i < il; i += 9 ) {
  12009. normalArray = object.normalArray;
  12010. nax = normalArray[ i ];
  12011. nay = normalArray[ i + 1 ];
  12012. naz = normalArray[ i + 2 ];
  12013. nbx = normalArray[ i + 3 ];
  12014. nby = normalArray[ i + 4 ];
  12015. nbz = normalArray[ i + 5 ];
  12016. ncx = normalArray[ i + 6 ];
  12017. ncy = normalArray[ i + 7 ];
  12018. ncz = normalArray[ i + 8 ];
  12019. nx = ( nax + nbx + ncx ) / 3;
  12020. ny = ( nay + nby + ncy ) / 3;
  12021. nz = ( naz + nbz + ncz ) / 3;
  12022. normalArray[ i ] = nx;
  12023. normalArray[ i + 1 ] = ny;
  12024. normalArray[ i + 2 ] = nz;
  12025. normalArray[ i + 3 ] = nx;
  12026. normalArray[ i + 4 ] = ny;
  12027. normalArray[ i + 5 ] = nz;
  12028. normalArray[ i + 6 ] = nx;
  12029. normalArray[ i + 7 ] = ny;
  12030. normalArray[ i + 8 ] = nz;
  12031. }
  12032. }
  12033. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  12034. _gl.enableVertexAttribArray( program.attributes.normal );
  12035. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12036. }
  12037. if ( object.hasUvs && material.map ) {
  12038. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglUvBuffer );
  12039. _gl.bufferData( _gl.ARRAY_BUFFER, object.uvArray, _gl.DYNAMIC_DRAW );
  12040. _gl.enableVertexAttribArray( program.attributes.uv );
  12041. _gl.vertexAttribPointer( program.attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12042. }
  12043. if ( object.hasColors && material.vertexColors !== THREE.NoColors ) {
  12044. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglColorBuffer );
  12045. _gl.bufferData( _gl.ARRAY_BUFFER, object.colorArray, _gl.DYNAMIC_DRAW );
  12046. _gl.enableVertexAttribArray( program.attributes.color );
  12047. _gl.vertexAttribPointer( program.attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12048. }
  12049. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  12050. object.count = 0;
  12051. };
  12052. this.renderBufferDirect = function ( camera, lights, fog, material, geometry, object ) {
  12053. if ( material.visible === false ) return;
  12054. var program, attributes, linewidth, primitives, a, attribute;
  12055. program = setProgram( camera, lights, fog, material, object );
  12056. attributes = program.attributes;
  12057. var updateBuffers = false,
  12058. wireframeBit = material.wireframe ? 1 : 0,
  12059. geometryHash = ( geometry.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12060. if ( geometryHash !== _currentGeometryGroupHash ) {
  12061. _currentGeometryGroupHash = geometryHash;
  12062. updateBuffers = true;
  12063. }
  12064. if ( updateBuffers ) {
  12065. disableAttributes();
  12066. }
  12067. // render mesh
  12068. if ( object instanceof THREE.Mesh ) {
  12069. var index = geometry.attributes[ "index" ];
  12070. // indexed triangles
  12071. if ( index ) {
  12072. var offsets = geometry.offsets;
  12073. // if there is more than 1 chunk
  12074. // must set attribute pointers to use new offsets for each chunk
  12075. // even if geometry and materials didn't change
  12076. if ( offsets.length > 1 ) updateBuffers = true;
  12077. for ( var i = 0, il = offsets.length; i < il; i ++ ) {
  12078. var startIndex = offsets[ i ].index;
  12079. if ( updateBuffers ) {
  12080. // vertices
  12081. var position = geometry.attributes[ "position" ];
  12082. var positionSize = position.itemSize;
  12083. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12084. enableAttribute( attributes.position );
  12085. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, startIndex * positionSize * 4 ); // 4 bytes per Float32
  12086. // normals
  12087. var normal = geometry.attributes[ "normal" ];
  12088. if ( attributes.normal >= 0 && normal ) {
  12089. var normalSize = normal.itemSize;
  12090. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12091. enableAttribute( attributes.normal );
  12092. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, startIndex * normalSize * 4 );
  12093. }
  12094. // uvs
  12095. var uv = geometry.attributes[ "uv" ];
  12096. if ( attributes.uv >= 0 && uv ) {
  12097. var uvSize = uv.itemSize;
  12098. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12099. enableAttribute( attributes.uv );
  12100. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, startIndex * uvSize * 4 );
  12101. }
  12102. // colors
  12103. var color = geometry.attributes[ "color" ];
  12104. if ( attributes.color >= 0 && color ) {
  12105. var colorSize = color.itemSize;
  12106. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12107. enableAttribute( attributes.color );
  12108. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, startIndex * colorSize * 4 );
  12109. }
  12110. // tangents
  12111. var tangent = geometry.attributes[ "tangent" ];
  12112. if ( attributes.tangent >= 0 && tangent ) {
  12113. var tangentSize = tangent.itemSize;
  12114. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12115. enableAttribute( attributes.tangent );
  12116. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, startIndex * tangentSize * 4 );
  12117. }
  12118. // indices
  12119. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, index.buffer );
  12120. }
  12121. // render indexed triangles
  12122. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 bytes per Uint16
  12123. _this.info.render.calls ++;
  12124. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  12125. _this.info.render.faces += offsets[ i ].count / 3;
  12126. }
  12127. // non-indexed triangles
  12128. } else {
  12129. if ( updateBuffers ) {
  12130. // vertices
  12131. var position = geometry.attributes[ "position" ];
  12132. var positionSize = position.itemSize;
  12133. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12134. enableAttribute( attributes.position );
  12135. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12136. // normals
  12137. var normal = geometry.attributes[ "normal" ];
  12138. if ( attributes.normal >= 0 && normal ) {
  12139. var normalSize = normal.itemSize;
  12140. _gl.bindBuffer( _gl.ARRAY_BUFFER, normal.buffer );
  12141. enableAttribute( attributes.normal );
  12142. _gl.vertexAttribPointer( attributes.normal, normalSize, _gl.FLOAT, false, 0, 0 );
  12143. }
  12144. // uvs
  12145. var uv = geometry.attributes[ "uv" ];
  12146. if ( attributes.uv >= 0 && uv ) {
  12147. var uvSize = uv.itemSize;
  12148. _gl.bindBuffer( _gl.ARRAY_BUFFER, uv.buffer );
  12149. enableAttribute( attributes.uv );
  12150. _gl.vertexAttribPointer( attributes.uv, uvSize, _gl.FLOAT, false, 0, 0 );
  12151. }
  12152. // colors
  12153. var color = geometry.attributes[ "color" ];
  12154. if ( attributes.color >= 0 && color ) {
  12155. var colorSize = color.itemSize;
  12156. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12157. enableAttribute( attributes.color );
  12158. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12159. }
  12160. // tangents
  12161. var tangent = geometry.attributes[ "tangent" ];
  12162. if ( attributes.tangent >= 0 && tangent ) {
  12163. var tangentSize = tangent.itemSize;
  12164. _gl.bindBuffer( _gl.ARRAY_BUFFER, tangent.buffer );
  12165. enableAttribute( attributes.tangent );
  12166. _gl.vertexAttribPointer( attributes.tangent, tangentSize, _gl.FLOAT, false, 0, 0 );
  12167. }
  12168. }
  12169. // render non-indexed triangles
  12170. _gl.drawArrays( _gl.TRIANGLES, 0, position.numItems / 3 );
  12171. _this.info.render.calls ++;
  12172. _this.info.render.vertices += position.numItems / 3;
  12173. _this.info.render.faces += position.numItems / 3 / 3;
  12174. }
  12175. // render particles
  12176. } else if ( object instanceof THREE.ParticleSystem ) {
  12177. if ( updateBuffers ) {
  12178. // vertices
  12179. var position = geometry.attributes[ "position" ];
  12180. var positionSize = position.itemSize;
  12181. _gl.bindBuffer( _gl.ARRAY_BUFFER, position.buffer );
  12182. enableAttribute( attributes.position );
  12183. _gl.vertexAttribPointer( attributes.position, positionSize, _gl.FLOAT, false, 0, 0 );
  12184. // colors
  12185. var color = geometry.attributes[ "color" ];
  12186. if ( attributes.color >= 0 && color ) {
  12187. var colorSize = color.itemSize;
  12188. _gl.bindBuffer( _gl.ARRAY_BUFFER, color.buffer );
  12189. enableAttribute( attributes.color );
  12190. _gl.vertexAttribPointer( attributes.color, colorSize, _gl.FLOAT, false, 0, 0 );
  12191. }
  12192. // render particles
  12193. _gl.drawArrays( _gl.POINTS, 0, position.numItems / 3 );
  12194. _this.info.render.calls ++;
  12195. _this.info.render.points += position.numItems / 3;
  12196. }
  12197. }
  12198. };
  12199. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  12200. if ( material.visible === false ) return;
  12201. var program, attributes, linewidth, primitives, a, attribute, i, il;
  12202. program = setProgram( camera, lights, fog, material, object );
  12203. attributes = program.attributes;
  12204. var updateBuffers = false,
  12205. wireframeBit = material.wireframe ? 1 : 0,
  12206. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  12207. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  12208. _currentGeometryGroupHash = geometryGroupHash;
  12209. updateBuffers = true;
  12210. }
  12211. if ( updateBuffers ) {
  12212. disableAttributes();
  12213. }
  12214. // vertices
  12215. if ( !material.morphTargets && attributes.position >= 0 ) {
  12216. if ( updateBuffers ) {
  12217. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12218. enableAttribute( attributes.position );
  12219. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12220. }
  12221. } else {
  12222. if ( object.morphTargetBase ) {
  12223. setupMorphTargets( material, geometryGroup, object );
  12224. }
  12225. }
  12226. if ( updateBuffers ) {
  12227. // custom attributes
  12228. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  12229. if ( geometryGroup.__webglCustomAttributesList ) {
  12230. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  12231. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  12232. if ( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  12233. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  12234. enableAttribute( attributes[ attribute.buffer.belongsToAttribute ] );
  12235. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  12236. }
  12237. }
  12238. }
  12239. // colors
  12240. if ( attributes.color >= 0 ) {
  12241. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  12242. enableAttribute( attributes.color );
  12243. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  12244. }
  12245. // normals
  12246. if ( attributes.normal >= 0 ) {
  12247. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  12248. enableAttribute( attributes.normal );
  12249. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  12250. }
  12251. // tangents
  12252. if ( attributes.tangent >= 0 ) {
  12253. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  12254. enableAttribute( attributes.tangent );
  12255. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  12256. }
  12257. // uvs
  12258. if ( attributes.uv >= 0 ) {
  12259. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  12260. enableAttribute( attributes.uv );
  12261. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  12262. }
  12263. if ( attributes.uv2 >= 0 ) {
  12264. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  12265. enableAttribute( attributes.uv2 );
  12266. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  12267. }
  12268. if ( material.skinning &&
  12269. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  12270. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  12271. enableAttribute( attributes.skinIndex );
  12272. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  12273. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  12274. enableAttribute( attributes.skinWeight );
  12275. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  12276. }
  12277. // line distances
  12278. if ( attributes.lineDistance >= 0 ) {
  12279. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglLineDistanceBuffer );
  12280. enableAttribute( attributes.lineDistance );
  12281. _gl.vertexAttribPointer( attributes.lineDistance, 1, _gl.FLOAT, false, 0, 0 );
  12282. }
  12283. }
  12284. // render mesh
  12285. if ( object instanceof THREE.Mesh ) {
  12286. // wireframe
  12287. if ( material.wireframe ) {
  12288. setLineWidth( material.wireframeLinewidth );
  12289. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  12290. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  12291. // triangles
  12292. } else {
  12293. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  12294. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  12295. }
  12296. _this.info.render.calls ++;
  12297. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  12298. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  12299. // render lines
  12300. } else if ( object instanceof THREE.Line ) {
  12301. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  12302. setLineWidth( material.linewidth );
  12303. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  12304. _this.info.render.calls ++;
  12305. // render particles
  12306. } else if ( object instanceof THREE.ParticleSystem ) {
  12307. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  12308. _this.info.render.calls ++;
  12309. _this.info.render.points += geometryGroup.__webglParticleCount;
  12310. // render ribbon
  12311. } else if ( object instanceof THREE.Ribbon ) {
  12312. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  12313. _this.info.render.calls ++;
  12314. }
  12315. };
  12316. function enableAttribute( attribute ) {
  12317. if ( ! _enabledAttributes[ attribute ] ) {
  12318. _gl.enableVertexAttribArray( attribute );
  12319. _enabledAttributes[ attribute ] = true;
  12320. }
  12321. };
  12322. function disableAttributes() {
  12323. for ( var attribute in _enabledAttributes ) {
  12324. if ( _enabledAttributes[ attribute ] ) {
  12325. _gl.disableVertexAttribArray( attribute );
  12326. _enabledAttributes[ attribute ] = false;
  12327. }
  12328. }
  12329. };
  12330. function setupMorphTargets ( material, geometryGroup, object ) {
  12331. // set base
  12332. var attributes = material.program.attributes;
  12333. if ( object.morphTargetBase !== -1 && attributes.position >= 0 ) {
  12334. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  12335. enableAttribute( attributes.position );
  12336. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12337. } else if ( attributes.position >= 0 ) {
  12338. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  12339. enableAttribute( attributes.position );
  12340. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  12341. }
  12342. if ( object.morphTargetForcedOrder.length ) {
  12343. // set forced order
  12344. var m = 0;
  12345. var order = object.morphTargetForcedOrder;
  12346. var influences = object.morphTargetInfluences;
  12347. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  12348. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12349. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  12350. enableAttribute( attributes[ "morphTarget" + m ] );
  12351. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12352. }
  12353. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12354. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  12355. enableAttribute( attributes[ "morphNormal" + m ] );
  12356. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12357. }
  12358. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  12359. m ++;
  12360. }
  12361. } else {
  12362. // find the most influencing
  12363. var influence, activeInfluenceIndices = [];
  12364. var influences = object.morphTargetInfluences;
  12365. var i, il = influences.length;
  12366. for ( i = 0; i < il; i ++ ) {
  12367. influence = influences[ i ];
  12368. if ( influence > 0 ) {
  12369. activeInfluenceIndices.push( [ influence, i ] );
  12370. }
  12371. }
  12372. if ( activeInfluenceIndices.length > material.numSupportedMorphTargets ) {
  12373. activeInfluenceIndices.sort( numericalSort );
  12374. activeInfluenceIndices.length = material.numSupportedMorphTargets;
  12375. } else if ( activeInfluenceIndices.length > material.numSupportedMorphNormals ) {
  12376. activeInfluenceIndices.sort( numericalSort );
  12377. } else if ( activeInfluenceIndices.length === 0 ) {
  12378. activeInfluenceIndices.push( [ 0, 0 ] );
  12379. };
  12380. var influenceIndex, m = 0;
  12381. while ( m < material.numSupportedMorphTargets ) {
  12382. if ( activeInfluenceIndices[ m ] ) {
  12383. influenceIndex = activeInfluenceIndices[ m ][ 1 ];
  12384. if ( attributes[ "morphTarget" + m ] >= 0 ) {
  12385. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ influenceIndex ] );
  12386. enableAttribute( attributes[ "morphTarget" + m ] );
  12387. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12388. }
  12389. if ( attributes[ "morphNormal" + m ] >= 0 && material.morphNormals ) {
  12390. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ influenceIndex ] );
  12391. enableAttribute( attributes[ "morphNormal" + m ] );
  12392. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12393. }
  12394. object.__webglMorphTargetInfluences[ m ] = influences[ influenceIndex ];
  12395. } else {
  12396. /*
  12397. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12398. if ( material.morphNormals ) {
  12399. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  12400. }
  12401. */
  12402. object.__webglMorphTargetInfluences[ m ] = 0;
  12403. }
  12404. m ++;
  12405. }
  12406. }
  12407. // load updated influences uniform
  12408. if ( material.program.uniforms.morphTargetInfluences !== null ) {
  12409. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  12410. }
  12411. };
  12412. // Sorting
  12413. function painterSortStable ( a, b ) {
  12414. if ( a.z !== b.z ) {
  12415. return b.z - a.z;
  12416. } else {
  12417. return b.id - a.id;
  12418. }
  12419. };
  12420. function numericalSort ( a, b ) {
  12421. return b[ 0 ] - a[ 0 ];
  12422. };
  12423. // Rendering
  12424. this.render = function ( scene, camera, renderTarget, forceClear ) {
  12425. if ( camera instanceof THREE.Camera === false ) {
  12426. console.error( 'THREE.WebGLRenderer.render: camera is not an instance of THREE.Camera.' );
  12427. return;
  12428. }
  12429. var i, il,
  12430. webglObject, object,
  12431. renderList,
  12432. lights = scene.__lights,
  12433. fog = scene.fog;
  12434. // reset caching for this frame
  12435. _currentMaterialId = -1;
  12436. _lightsNeedUpdate = true;
  12437. // update scene graph
  12438. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  12439. // update camera matrices and frustum
  12440. if ( camera.parent === undefined ) camera.updateMatrixWorld();
  12441. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  12442. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  12443. _frustum.setFromMatrix( _projScreenMatrix );
  12444. // update WebGL objects
  12445. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  12446. // custom render plugins (pre pass)
  12447. renderPlugins( this.renderPluginsPre, scene, camera );
  12448. //
  12449. _this.info.render.calls = 0;
  12450. _this.info.render.vertices = 0;
  12451. _this.info.render.faces = 0;
  12452. _this.info.render.points = 0;
  12453. this.setRenderTarget( renderTarget );
  12454. if ( this.autoClear || forceClear ) {
  12455. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  12456. }
  12457. // set matrices for regular objects (frustum culled)
  12458. renderList = scene.__webglObjects;
  12459. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12460. webglObject = renderList[ i ];
  12461. object = webglObject.object;
  12462. webglObject.render = false;
  12463. if ( object.visible ) {
  12464. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  12465. setupMatrices( object, camera );
  12466. unrollBufferMaterial( webglObject );
  12467. webglObject.render = true;
  12468. if ( this.sortObjects === true ) {
  12469. if ( object.renderDepth !== null ) {
  12470. webglObject.z = object.renderDepth;
  12471. } else {
  12472. _vector3.copy( object.matrixWorld.getPosition() );
  12473. _projScreenMatrix.multiplyVector3( _vector3 );
  12474. webglObject.z = _vector3.z;
  12475. }
  12476. webglObject.id = object.id;
  12477. }
  12478. }
  12479. }
  12480. }
  12481. if ( this.sortObjects ) {
  12482. renderList.sort( painterSortStable );
  12483. }
  12484. // set matrices for immediate objects
  12485. renderList = scene.__webglObjectsImmediate;
  12486. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  12487. webglObject = renderList[ i ];
  12488. object = webglObject.object;
  12489. if ( object.visible ) {
  12490. setupMatrices( object, camera );
  12491. unrollImmediateBufferMaterial( webglObject );
  12492. }
  12493. }
  12494. if ( scene.overrideMaterial ) {
  12495. var material = scene.overrideMaterial;
  12496. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12497. this.setDepthTest( material.depthTest );
  12498. this.setDepthWrite( material.depthWrite );
  12499. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12500. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  12501. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  12502. } else {
  12503. var material = null;
  12504. // opaque pass (front-to-back order)
  12505. this.setBlending( THREE.NoBlending );
  12506. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false, material );
  12507. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false, material );
  12508. // transparent pass (back-to-front order)
  12509. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true, material );
  12510. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true, material );
  12511. }
  12512. // custom render plugins (post pass)
  12513. renderPlugins( this.renderPluginsPost, scene, camera );
  12514. // Generate mipmap if we're using any kind of mipmap filtering
  12515. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  12516. updateRenderTargetMipmap( renderTarget );
  12517. }
  12518. // Ensure depth buffer writing is enabled so it can be cleared on next render
  12519. this.setDepthTest( true );
  12520. this.setDepthWrite( true );
  12521. // _gl.finish();
  12522. };
  12523. function renderPlugins( plugins, scene, camera ) {
  12524. if ( ! plugins.length ) return;
  12525. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  12526. // reset state for plugin (to start from clean slate)
  12527. _currentProgram = null;
  12528. _currentCamera = null;
  12529. _oldBlending = -1;
  12530. _oldDepthTest = -1;
  12531. _oldDepthWrite = -1;
  12532. _oldDoubleSided = -1;
  12533. _oldFlipSided = -1;
  12534. _currentGeometryGroupHash = -1;
  12535. _currentMaterialId = -1;
  12536. _lightsNeedUpdate = true;
  12537. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  12538. // reset state after plugin (anything could have changed)
  12539. _currentProgram = null;
  12540. _currentCamera = null;
  12541. _oldBlending = -1;
  12542. _oldDepthTest = -1;
  12543. _oldDepthWrite = -1;
  12544. _oldDoubleSided = -1;
  12545. _oldFlipSided = -1;
  12546. _currentGeometryGroupHash = -1;
  12547. _currentMaterialId = -1;
  12548. _lightsNeedUpdate = true;
  12549. }
  12550. };
  12551. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12552. var webglObject, object, buffer, material, start, end, delta;
  12553. if ( reverse ) {
  12554. start = renderList.length - 1;
  12555. end = -1;
  12556. delta = -1;
  12557. } else {
  12558. start = 0;
  12559. end = renderList.length;
  12560. delta = 1;
  12561. }
  12562. for ( var i = start; i !== end; i += delta ) {
  12563. webglObject = renderList[ i ];
  12564. if ( webglObject.render ) {
  12565. object = webglObject.object;
  12566. buffer = webglObject.buffer;
  12567. if ( overrideMaterial ) {
  12568. material = overrideMaterial;
  12569. } else {
  12570. material = webglObject[ materialType ];
  12571. if ( ! material ) continue;
  12572. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12573. _this.setDepthTest( material.depthTest );
  12574. _this.setDepthWrite( material.depthWrite );
  12575. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12576. }
  12577. _this.setMaterialFaces( material );
  12578. if ( buffer instanceof THREE.BufferGeometry ) {
  12579. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  12580. } else {
  12581. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  12582. }
  12583. }
  12584. }
  12585. };
  12586. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  12587. var webglObject, object, material, program;
  12588. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  12589. webglObject = renderList[ i ];
  12590. object = webglObject.object;
  12591. if ( object.visible ) {
  12592. if ( overrideMaterial ) {
  12593. material = overrideMaterial;
  12594. } else {
  12595. material = webglObject[ materialType ];
  12596. if ( ! material ) continue;
  12597. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  12598. _this.setDepthTest( material.depthTest );
  12599. _this.setDepthWrite( material.depthWrite );
  12600. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  12601. }
  12602. _this.renderImmediateObject( camera, lights, fog, material, object );
  12603. }
  12604. }
  12605. };
  12606. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  12607. var program = setProgram( camera, lights, fog, material, object );
  12608. _currentGeometryGroupHash = -1;
  12609. _this.setMaterialFaces( material );
  12610. if ( object.immediateRenderCallback ) {
  12611. object.immediateRenderCallback( program, _gl, _frustum );
  12612. } else {
  12613. object.render( function( object ) { _this.renderBufferImmediate( object, program, material ); } );
  12614. }
  12615. };
  12616. function unrollImmediateBufferMaterial ( globject ) {
  12617. var object = globject.object,
  12618. material = object.material;
  12619. if ( material.transparent ) {
  12620. globject.transparent = material;
  12621. globject.opaque = null;
  12622. } else {
  12623. globject.opaque = material;
  12624. globject.transparent = null;
  12625. }
  12626. };
  12627. function unrollBufferMaterial ( globject ) {
  12628. var object = globject.object,
  12629. buffer = globject.buffer,
  12630. material, materialIndex, meshMaterial;
  12631. meshMaterial = object.material;
  12632. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  12633. materialIndex = buffer.materialIndex;
  12634. material = meshMaterial.materials[ materialIndex ];
  12635. if ( material.transparent ) {
  12636. globject.transparent = material;
  12637. globject.opaque = null;
  12638. } else {
  12639. globject.opaque = material;
  12640. globject.transparent = null;
  12641. }
  12642. } else {
  12643. material = meshMaterial;
  12644. if ( material ) {
  12645. if ( material.transparent ) {
  12646. globject.transparent = material;
  12647. globject.opaque = null;
  12648. } else {
  12649. globject.opaque = material;
  12650. globject.transparent = null;
  12651. }
  12652. }
  12653. }
  12654. };
  12655. // Geometry splitting
  12656. function sortFacesByMaterial ( geometry, material ) {
  12657. var f, fl, face, materialIndex, vertices,
  12658. groupHash, hash_map = {};
  12659. var numMorphTargets = geometry.morphTargets.length;
  12660. var numMorphNormals = geometry.morphNormals.length;
  12661. var usesFaceMaterial = material instanceof THREE.MeshFaceMaterial;
  12662. geometry.geometryGroups = {};
  12663. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  12664. face = geometry.faces[ f ];
  12665. materialIndex = usesFaceMaterial ? face.materialIndex : 0;
  12666. if ( hash_map[ materialIndex ] === undefined ) {
  12667. hash_map[ materialIndex ] = { 'hash': materialIndex, 'counter': 0 };
  12668. }
  12669. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12670. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12671. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12672. }
  12673. vertices = face instanceof THREE.Face3 ? 3 : 4;
  12674. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  12675. hash_map[ materialIndex ].counter += 1;
  12676. groupHash = hash_map[ materialIndex ].hash + '_' + hash_map[ materialIndex ].counter;
  12677. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  12678. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  12679. }
  12680. }
  12681. if ( face instanceof THREE.Face3 ) {
  12682. geometry.geometryGroups[ groupHash ].faces3.push( f );
  12683. } else {
  12684. geometry.geometryGroups[ groupHash ].faces4.push( f );
  12685. }
  12686. geometry.geometryGroups[ groupHash ].vertices += vertices;
  12687. }
  12688. geometry.geometryGroupsList = [];
  12689. for ( var g in geometry.geometryGroups ) {
  12690. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  12691. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  12692. }
  12693. };
  12694. // Objects refresh
  12695. this.initWebGLObjects = function ( scene ) {
  12696. if ( !scene.__webglObjects ) {
  12697. scene.__webglObjects = [];
  12698. scene.__webglObjectsImmediate = [];
  12699. scene.__webglSprites = [];
  12700. scene.__webglFlares = [];
  12701. }
  12702. while ( scene.__objectsAdded.length ) {
  12703. addObject( scene.__objectsAdded[ 0 ], scene );
  12704. scene.__objectsAdded.splice( 0, 1 );
  12705. }
  12706. while ( scene.__objectsRemoved.length ) {
  12707. removeObject( scene.__objectsRemoved[ 0 ], scene );
  12708. scene.__objectsRemoved.splice( 0, 1 );
  12709. }
  12710. // update must be called after objects adding / removal
  12711. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  12712. updateObject( scene.__webglObjects[ o ].object );
  12713. }
  12714. };
  12715. // Objects adding
  12716. function addObject ( object, scene ) {
  12717. var g, geometry, material, geometryGroup;
  12718. if ( ! object.__webglInit ) {
  12719. object.__webglInit = true;
  12720. object._modelViewMatrix = new THREE.Matrix4();
  12721. object._normalMatrix = new THREE.Matrix3();
  12722. if ( object instanceof THREE.Mesh ) {
  12723. geometry = object.geometry;
  12724. material = object.material;
  12725. if ( geometry instanceof THREE.Geometry ) {
  12726. if ( geometry.geometryGroups === undefined ) {
  12727. sortFacesByMaterial( geometry, material );
  12728. }
  12729. // create separate VBOs per geometry chunk
  12730. for ( g in geometry.geometryGroups ) {
  12731. geometryGroup = geometry.geometryGroups[ g ];
  12732. // initialise VBO on the first access
  12733. if ( ! geometryGroup.__webglVertexBuffer ) {
  12734. createMeshBuffers( geometryGroup );
  12735. initMeshBuffers( geometryGroup, object );
  12736. geometry.verticesNeedUpdate = true;
  12737. geometry.morphTargetsNeedUpdate = true;
  12738. geometry.elementsNeedUpdate = true;
  12739. geometry.uvsNeedUpdate = true;
  12740. geometry.normalsNeedUpdate = true;
  12741. geometry.tangentsNeedUpdate = true;
  12742. geometry.colorsNeedUpdate = true;
  12743. }
  12744. }
  12745. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12746. initDirectBuffers( geometry );
  12747. }
  12748. } else if ( object instanceof THREE.Ribbon ) {
  12749. geometry = object.geometry;
  12750. if ( ! geometry.__webglVertexBuffer ) {
  12751. createRibbonBuffers( geometry );
  12752. initRibbonBuffers( geometry, object );
  12753. geometry.verticesNeedUpdate = true;
  12754. geometry.colorsNeedUpdate = true;
  12755. geometry.normalsNeedUpdate = true;
  12756. }
  12757. } else if ( object instanceof THREE.Line ) {
  12758. geometry = object.geometry;
  12759. if ( ! geometry.__webglVertexBuffer ) {
  12760. createLineBuffers( geometry );
  12761. initLineBuffers( geometry, object );
  12762. geometry.verticesNeedUpdate = true;
  12763. geometry.colorsNeedUpdate = true;
  12764. geometry.lineDistancesNeedUpdate = true;
  12765. }
  12766. } else if ( object instanceof THREE.ParticleSystem ) {
  12767. geometry = object.geometry;
  12768. if ( ! geometry.__webglVertexBuffer ) {
  12769. if ( geometry instanceof THREE.Geometry ) {
  12770. createParticleBuffers( geometry );
  12771. initParticleBuffers( geometry, object );
  12772. geometry.verticesNeedUpdate = true;
  12773. geometry.colorsNeedUpdate = true;
  12774. } else if ( geometry instanceof THREE.BufferGeometry ) {
  12775. initDirectBuffers( geometry );
  12776. }
  12777. }
  12778. }
  12779. }
  12780. if ( ! object.__webglActive ) {
  12781. if ( object instanceof THREE.Mesh ) {
  12782. geometry = object.geometry;
  12783. if ( geometry instanceof THREE.BufferGeometry ) {
  12784. addBuffer( scene.__webglObjects, geometry, object );
  12785. } else {
  12786. for ( g in geometry.geometryGroups ) {
  12787. geometryGroup = geometry.geometryGroups[ g ];
  12788. addBuffer( scene.__webglObjects, geometryGroup, object );
  12789. }
  12790. }
  12791. } else if ( object instanceof THREE.Ribbon ||
  12792. object instanceof THREE.Line ||
  12793. object instanceof THREE.ParticleSystem ) {
  12794. geometry = object.geometry;
  12795. addBuffer( scene.__webglObjects, geometry, object );
  12796. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12797. addBufferImmediate( scene.__webglObjectsImmediate, object );
  12798. } else if ( object instanceof THREE.Sprite ) {
  12799. scene.__webglSprites.push( object );
  12800. } else if ( object instanceof THREE.LensFlare ) {
  12801. scene.__webglFlares.push( object );
  12802. }
  12803. object.__webglActive = true;
  12804. }
  12805. };
  12806. function addBuffer ( objlist, buffer, object ) {
  12807. objlist.push(
  12808. {
  12809. buffer: buffer,
  12810. object: object,
  12811. opaque: null,
  12812. transparent: null
  12813. }
  12814. );
  12815. };
  12816. function addBufferImmediate ( objlist, object ) {
  12817. objlist.push(
  12818. {
  12819. object: object,
  12820. opaque: null,
  12821. transparent: null
  12822. }
  12823. );
  12824. };
  12825. // Objects updates
  12826. function updateObject ( object ) {
  12827. var geometry = object.geometry,
  12828. geometryGroup, customAttributesDirty, material;
  12829. if ( object instanceof THREE.Mesh ) {
  12830. if ( geometry instanceof THREE.BufferGeometry ) {
  12831. if ( geometry.verticesNeedUpdate || geometry.elementsNeedUpdate ||
  12832. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12833. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate ) {
  12834. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12835. }
  12836. geometry.verticesNeedUpdate = false;
  12837. geometry.elementsNeedUpdate = false;
  12838. geometry.uvsNeedUpdate = false;
  12839. geometry.normalsNeedUpdate = false;
  12840. geometry.colorsNeedUpdate = false;
  12841. geometry.tangentsNeedUpdate = false;
  12842. } else {
  12843. // check all geometry groups
  12844. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  12845. geometryGroup = geometry.geometryGroupsList[ i ];
  12846. material = getBufferMaterial( object, geometryGroup );
  12847. if ( geometry.buffersNeedUpdate ) {
  12848. initMeshBuffers( geometryGroup, object );
  12849. }
  12850. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12851. if ( geometry.verticesNeedUpdate || geometry.morphTargetsNeedUpdate || geometry.elementsNeedUpdate ||
  12852. geometry.uvsNeedUpdate || geometry.normalsNeedUpdate ||
  12853. geometry.colorsNeedUpdate || geometry.tangentsNeedUpdate || customAttributesDirty ) {
  12854. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  12855. }
  12856. }
  12857. geometry.verticesNeedUpdate = false;
  12858. geometry.morphTargetsNeedUpdate = false;
  12859. geometry.elementsNeedUpdate = false;
  12860. geometry.uvsNeedUpdate = false;
  12861. geometry.normalsNeedUpdate = false;
  12862. geometry.colorsNeedUpdate = false;
  12863. geometry.tangentsNeedUpdate = false;
  12864. geometry.buffersNeedUpdate = false;
  12865. material.attributes && clearCustomAttributes( material );
  12866. }
  12867. } else if ( object instanceof THREE.Ribbon ) {
  12868. material = getBufferMaterial( object, geometry );
  12869. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12870. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.normalsNeedUpdate || customAttributesDirty ) {
  12871. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  12872. }
  12873. geometry.verticesNeedUpdate = false;
  12874. geometry.colorsNeedUpdate = false;
  12875. geometry.normalsNeedUpdate = false;
  12876. material.attributes && clearCustomAttributes( material );
  12877. } else if ( object instanceof THREE.Line ) {
  12878. material = getBufferMaterial( object, geometry );
  12879. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12880. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || geometry.lineDistancesNeedUpdate || customAttributesDirty ) {
  12881. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  12882. }
  12883. geometry.verticesNeedUpdate = false;
  12884. geometry.colorsNeedUpdate = false;
  12885. geometry.lineDistancesNeedUpdate = false;
  12886. material.attributes && clearCustomAttributes( material );
  12887. } else if ( object instanceof THREE.ParticleSystem ) {
  12888. if ( geometry instanceof THREE.BufferGeometry ) {
  12889. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate ) {
  12890. setDirectBuffers( geometry, _gl.DYNAMIC_DRAW, !geometry.dynamic );
  12891. }
  12892. geometry.verticesNeedUpdate = false;
  12893. geometry.colorsNeedUpdate = false;
  12894. } else {
  12895. material = getBufferMaterial( object, geometry );
  12896. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  12897. if ( geometry.verticesNeedUpdate || geometry.colorsNeedUpdate || object.sortParticles || customAttributesDirty ) {
  12898. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  12899. }
  12900. geometry.verticesNeedUpdate = false;
  12901. geometry.colorsNeedUpdate = false;
  12902. material.attributes && clearCustomAttributes( material );
  12903. }
  12904. }
  12905. };
  12906. // Objects updates - custom attributes check
  12907. function areCustomAttributesDirty ( material ) {
  12908. for ( var a in material.attributes ) {
  12909. if ( material.attributes[ a ].needsUpdate ) return true;
  12910. }
  12911. return false;
  12912. };
  12913. function clearCustomAttributes ( material ) {
  12914. for ( var a in material.attributes ) {
  12915. material.attributes[ a ].needsUpdate = false;
  12916. }
  12917. };
  12918. // Objects removal
  12919. function removeObject ( object, scene ) {
  12920. if ( object instanceof THREE.Mesh ||
  12921. object instanceof THREE.ParticleSystem ||
  12922. object instanceof THREE.Ribbon ||
  12923. object instanceof THREE.Line ) {
  12924. removeInstances( scene.__webglObjects, object );
  12925. } else if ( object instanceof THREE.Sprite ) {
  12926. removeInstancesDirect( scene.__webglSprites, object );
  12927. } else if ( object instanceof THREE.LensFlare ) {
  12928. removeInstancesDirect( scene.__webglFlares, object );
  12929. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  12930. removeInstances( scene.__webglObjectsImmediate, object );
  12931. }
  12932. object.__webglActive = false;
  12933. };
  12934. function removeInstances ( objlist, object ) {
  12935. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12936. if ( objlist[ o ].object === object ) {
  12937. objlist.splice( o, 1 );
  12938. }
  12939. }
  12940. };
  12941. function removeInstancesDirect ( objlist, object ) {
  12942. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  12943. if ( objlist[ o ] === object ) {
  12944. objlist.splice( o, 1 );
  12945. }
  12946. }
  12947. };
  12948. // Materials
  12949. this.initMaterial = function ( material, lights, fog, object ) {
  12950. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  12951. if ( material instanceof THREE.MeshDepthMaterial ) {
  12952. shaderID = 'depth';
  12953. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  12954. shaderID = 'normal';
  12955. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  12956. shaderID = 'basic';
  12957. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  12958. shaderID = 'lambert';
  12959. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  12960. shaderID = 'phong';
  12961. } else if ( material instanceof THREE.LineBasicMaterial ) {
  12962. shaderID = 'basic';
  12963. } else if ( material instanceof THREE.LineDashedMaterial ) {
  12964. shaderID = 'dashed';
  12965. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  12966. shaderID = 'particle_basic';
  12967. }
  12968. if ( shaderID ) {
  12969. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  12970. }
  12971. // heuristics to create shader parameters according to lights in the scene
  12972. // (not to blow over maxLights budget)
  12973. maxLightCount = allocateLights( lights );
  12974. maxShadows = allocateShadows( lights );
  12975. maxBones = allocateBones( object );
  12976. parameters = {
  12977. map: !!material.map,
  12978. envMap: !!material.envMap,
  12979. lightMap: !!material.lightMap,
  12980. bumpMap: !!material.bumpMap,
  12981. normalMap: !!material.normalMap,
  12982. specularMap: !!material.specularMap,
  12983. vertexColors: material.vertexColors,
  12984. fog: fog,
  12985. useFog: material.fog,
  12986. fogExp: fog instanceof THREE.FogExp2,
  12987. sizeAttenuation: material.sizeAttenuation,
  12988. skinning: material.skinning,
  12989. maxBones: maxBones,
  12990. useVertexTexture: _supportsBoneTextures && object && object.useVertexTexture,
  12991. boneTextureWidth: object && object.boneTextureWidth,
  12992. boneTextureHeight: object && object.boneTextureHeight,
  12993. morphTargets: material.morphTargets,
  12994. morphNormals: material.morphNormals,
  12995. maxMorphTargets: this.maxMorphTargets,
  12996. maxMorphNormals: this.maxMorphNormals,
  12997. maxDirLights: maxLightCount.directional,
  12998. maxPointLights: maxLightCount.point,
  12999. maxSpotLights: maxLightCount.spot,
  13000. maxHemiLights: maxLightCount.hemi,
  13001. maxShadows: maxShadows,
  13002. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  13003. shadowMapSoft: this.shadowMapSoft,
  13004. shadowMapDebug: this.shadowMapDebug,
  13005. shadowMapCascade: this.shadowMapCascade,
  13006. alphaTest: material.alphaTest,
  13007. metal: material.metal,
  13008. perPixel: material.perPixel,
  13009. wrapAround: material.wrapAround,
  13010. doubleSided: material.side === THREE.DoubleSide,
  13011. flipSided: material.side === THREE.BackSide
  13012. };
  13013. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, material.defines, parameters );
  13014. var attributes = material.program.attributes;
  13015. if ( material.morphTargets ) {
  13016. material.numSupportedMorphTargets = 0;
  13017. var id, base = "morphTarget";
  13018. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  13019. id = base + i;
  13020. if ( attributes[ id ] >= 0 ) {
  13021. material.numSupportedMorphTargets ++;
  13022. }
  13023. }
  13024. }
  13025. if ( material.morphNormals ) {
  13026. material.numSupportedMorphNormals = 0;
  13027. var id, base = "morphNormal";
  13028. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  13029. id = base + i;
  13030. if ( attributes[ id ] >= 0 ) {
  13031. material.numSupportedMorphNormals ++;
  13032. }
  13033. }
  13034. }
  13035. material.uniformsList = [];
  13036. for ( u in material.uniforms ) {
  13037. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  13038. }
  13039. };
  13040. function setMaterialShaders( material, shaders ) {
  13041. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  13042. material.vertexShader = shaders.vertexShader;
  13043. material.fragmentShader = shaders.fragmentShader;
  13044. };
  13045. function setProgram( camera, lights, fog, material, object ) {
  13046. _usedTextureUnits = 0;
  13047. if ( material.needsUpdate ) {
  13048. if ( material.program ) _this.deallocateMaterial( material );
  13049. _this.initMaterial( material, lights, fog, object );
  13050. material.needsUpdate = false;
  13051. }
  13052. if ( material.morphTargets ) {
  13053. if ( ! object.__webglMorphTargetInfluences ) {
  13054. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  13055. }
  13056. }
  13057. var refreshMaterial = false;
  13058. var program = material.program,
  13059. p_uniforms = program.uniforms,
  13060. m_uniforms = material.uniforms;
  13061. if ( program !== _currentProgram ) {
  13062. _gl.useProgram( program );
  13063. _currentProgram = program;
  13064. refreshMaterial = true;
  13065. }
  13066. if ( material.id !== _currentMaterialId ) {
  13067. _currentMaterialId = material.id;
  13068. refreshMaterial = true;
  13069. }
  13070. if ( refreshMaterial || camera !== _currentCamera ) {
  13071. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  13072. if ( camera !== _currentCamera ) _currentCamera = camera;
  13073. }
  13074. // skinning uniforms must be set even if material didn't change
  13075. // auto-setting of texture unit for bone texture must go before other textures
  13076. // not sure why, but otherwise weird things happen
  13077. if ( material.skinning ) {
  13078. if ( _supportsBoneTextures && object.useVertexTexture ) {
  13079. if ( p_uniforms.boneTexture !== null ) {
  13080. var textureUnit = getTextureUnit();
  13081. _gl.uniform1i( p_uniforms.boneTexture, textureUnit );
  13082. _this.setTexture( object.boneTexture, textureUnit );
  13083. }
  13084. } else {
  13085. if ( p_uniforms.boneGlobalMatrices !== null ) {
  13086. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  13087. }
  13088. }
  13089. }
  13090. if ( refreshMaterial ) {
  13091. // refresh uniforms common to several materials
  13092. if ( fog && material.fog ) {
  13093. refreshUniformsFog( m_uniforms, fog );
  13094. }
  13095. if ( material instanceof THREE.MeshPhongMaterial ||
  13096. material instanceof THREE.MeshLambertMaterial ||
  13097. material.lights ) {
  13098. if ( _lightsNeedUpdate ) {
  13099. setupLights( program, lights );
  13100. _lightsNeedUpdate = false;
  13101. }
  13102. refreshUniformsLights( m_uniforms, _lights );
  13103. }
  13104. if ( material instanceof THREE.MeshBasicMaterial ||
  13105. material instanceof THREE.MeshLambertMaterial ||
  13106. material instanceof THREE.MeshPhongMaterial ) {
  13107. refreshUniformsCommon( m_uniforms, material );
  13108. }
  13109. // refresh single material specific uniforms
  13110. if ( material instanceof THREE.LineBasicMaterial ) {
  13111. refreshUniformsLine( m_uniforms, material );
  13112. } else if ( material instanceof THREE.LineDashedMaterial ) {
  13113. refreshUniformsLine( m_uniforms, material );
  13114. refreshUniformsDash( m_uniforms, material );
  13115. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  13116. refreshUniformsParticle( m_uniforms, material );
  13117. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  13118. refreshUniformsPhong( m_uniforms, material );
  13119. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  13120. refreshUniformsLambert( m_uniforms, material );
  13121. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  13122. m_uniforms.mNear.value = camera.near;
  13123. m_uniforms.mFar.value = camera.far;
  13124. m_uniforms.opacity.value = material.opacity;
  13125. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  13126. m_uniforms.opacity.value = material.opacity;
  13127. }
  13128. if ( object.receiveShadow && ! material._shadowPass ) {
  13129. refreshUniformsShadow( m_uniforms, lights );
  13130. }
  13131. // load common uniforms
  13132. loadUniformsGeneric( program, material.uniformsList );
  13133. // load material specific uniforms
  13134. // (shader material also gets them for the sake of genericity)
  13135. if ( material instanceof THREE.ShaderMaterial ||
  13136. material instanceof THREE.MeshPhongMaterial ||
  13137. material.envMap ) {
  13138. if ( p_uniforms.cameraPosition !== null ) {
  13139. var position = camera.matrixWorld.getPosition();
  13140. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  13141. }
  13142. }
  13143. if ( material instanceof THREE.MeshPhongMaterial ||
  13144. material instanceof THREE.MeshLambertMaterial ||
  13145. material instanceof THREE.ShaderMaterial ||
  13146. material.skinning ) {
  13147. if ( p_uniforms.viewMatrix !== null ) {
  13148. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera.matrixWorldInverse.elements );
  13149. }
  13150. }
  13151. }
  13152. loadUniformsMatrices( p_uniforms, object );
  13153. if ( p_uniforms.modelMatrix !== null ) {
  13154. _gl.uniformMatrix4fv( p_uniforms.modelMatrix, false, object.matrixWorld.elements );
  13155. }
  13156. return program;
  13157. };
  13158. // Uniforms (refresh uniforms objects)
  13159. function refreshUniformsCommon ( uniforms, material ) {
  13160. uniforms.opacity.value = material.opacity;
  13161. if ( _this.gammaInput ) {
  13162. uniforms.diffuse.value.copyGammaToLinear( material.color );
  13163. } else {
  13164. uniforms.diffuse.value = material.color;
  13165. }
  13166. uniforms.map.value = material.map;
  13167. uniforms.lightMap.value = material.lightMap;
  13168. uniforms.specularMap.value = material.specularMap;
  13169. if ( material.bumpMap ) {
  13170. uniforms.bumpMap.value = material.bumpMap;
  13171. uniforms.bumpScale.value = material.bumpScale;
  13172. }
  13173. if ( material.normalMap ) {
  13174. uniforms.normalMap.value = material.normalMap;
  13175. uniforms.normalScale.value.copy( material.normalScale );
  13176. }
  13177. // uv repeat and offset setting priorities
  13178. // 1. color map
  13179. // 2. specular map
  13180. // 3. normal map
  13181. // 4. bump map
  13182. var uvScaleMap;
  13183. if ( material.map ) {
  13184. uvScaleMap = material.map;
  13185. } else if ( material.specularMap ) {
  13186. uvScaleMap = material.specularMap;
  13187. } else if ( material.normalMap ) {
  13188. uvScaleMap = material.normalMap;
  13189. } else if ( material.bumpMap ) {
  13190. uvScaleMap = material.bumpMap;
  13191. }
  13192. if ( uvScaleMap !== undefined ) {
  13193. var offset = uvScaleMap.offset;
  13194. var repeat = uvScaleMap.repeat;
  13195. uniforms.offsetRepeat.value.set( offset.x, offset.y, repeat.x, repeat.y );
  13196. }
  13197. uniforms.envMap.value = material.envMap;
  13198. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  13199. if ( _this.gammaInput ) {
  13200. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  13201. uniforms.reflectivity.value = material.reflectivity;
  13202. } else {
  13203. uniforms.reflectivity.value = material.reflectivity;
  13204. }
  13205. uniforms.refractionRatio.value = material.refractionRatio;
  13206. uniforms.combine.value = material.combine;
  13207. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  13208. };
  13209. function refreshUniformsLine ( uniforms, material ) {
  13210. uniforms.diffuse.value = material.color;
  13211. uniforms.opacity.value = material.opacity;
  13212. };
  13213. function refreshUniformsDash ( uniforms, material ) {
  13214. uniforms.dashSize.value = material.dashSize;
  13215. uniforms.totalSize.value = material.dashSize + material.gapSize;
  13216. uniforms.scale.value = material.scale;
  13217. };
  13218. function refreshUniformsParticle ( uniforms, material ) {
  13219. uniforms.psColor.value = material.color;
  13220. uniforms.opacity.value = material.opacity;
  13221. uniforms.size.value = material.size;
  13222. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  13223. uniforms.map.value = material.map;
  13224. };
  13225. function refreshUniformsFog ( uniforms, fog ) {
  13226. uniforms.fogColor.value = fog.color;
  13227. if ( fog instanceof THREE.Fog ) {
  13228. uniforms.fogNear.value = fog.near;
  13229. uniforms.fogFar.value = fog.far;
  13230. } else if ( fog instanceof THREE.FogExp2 ) {
  13231. uniforms.fogDensity.value = fog.density;
  13232. }
  13233. };
  13234. function refreshUniformsPhong ( uniforms, material ) {
  13235. uniforms.shininess.value = material.shininess;
  13236. if ( _this.gammaInput ) {
  13237. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13238. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13239. uniforms.specular.value.copyGammaToLinear( material.specular );
  13240. } else {
  13241. uniforms.ambient.value = material.ambient;
  13242. uniforms.emissive.value = material.emissive;
  13243. uniforms.specular.value = material.specular;
  13244. }
  13245. if ( material.wrapAround ) {
  13246. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13247. }
  13248. };
  13249. function refreshUniformsLambert ( uniforms, material ) {
  13250. if ( _this.gammaInput ) {
  13251. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  13252. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  13253. } else {
  13254. uniforms.ambient.value = material.ambient;
  13255. uniforms.emissive.value = material.emissive;
  13256. }
  13257. if ( material.wrapAround ) {
  13258. uniforms.wrapRGB.value.copy( material.wrapRGB );
  13259. }
  13260. };
  13261. function refreshUniformsLights ( uniforms, lights ) {
  13262. uniforms.ambientLightColor.value = lights.ambient;
  13263. uniforms.directionalLightColor.value = lights.directional.colors;
  13264. uniforms.directionalLightDirection.value = lights.directional.positions;
  13265. uniforms.pointLightColor.value = lights.point.colors;
  13266. uniforms.pointLightPosition.value = lights.point.positions;
  13267. uniforms.pointLightDistance.value = lights.point.distances;
  13268. uniforms.spotLightColor.value = lights.spot.colors;
  13269. uniforms.spotLightPosition.value = lights.spot.positions;
  13270. uniforms.spotLightDistance.value = lights.spot.distances;
  13271. uniforms.spotLightDirection.value = lights.spot.directions;
  13272. uniforms.spotLightAngleCos.value = lights.spot.anglesCos;
  13273. uniforms.spotLightExponent.value = lights.spot.exponents;
  13274. uniforms.hemisphereLightSkyColor.value = lights.hemi.skyColors;
  13275. uniforms.hemisphereLightGroundColor.value = lights.hemi.groundColors;
  13276. uniforms.hemisphereLightDirection.value = lights.hemi.positions;
  13277. };
  13278. function refreshUniformsShadow ( uniforms, lights ) {
  13279. if ( uniforms.shadowMatrix ) {
  13280. var j = 0;
  13281. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  13282. var light = lights[ i ];
  13283. if ( ! light.castShadow ) continue;
  13284. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  13285. uniforms.shadowMap.value[ j ] = light.shadowMap;
  13286. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  13287. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  13288. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  13289. uniforms.shadowBias.value[ j ] = light.shadowBias;
  13290. j ++;
  13291. }
  13292. }
  13293. }
  13294. };
  13295. // Uniforms (load to GPU)
  13296. function loadUniformsMatrices ( uniforms, object ) {
  13297. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  13298. if ( uniforms.normalMatrix ) {
  13299. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrix.elements );
  13300. }
  13301. };
  13302. function getTextureUnit() {
  13303. var textureUnit = _usedTextureUnits;
  13304. if ( textureUnit >= _maxTextures ) {
  13305. console.warn( "Trying to use " + textureUnit + " texture units while this GPU supports only " + _maxTextures );
  13306. }
  13307. _usedTextureUnits += 1;
  13308. return textureUnit;
  13309. };
  13310. function loadUniformsGeneric ( program, uniforms ) {
  13311. var uniform, value, type, location, texture, textureUnit, i, il, j, jl, offset;
  13312. for ( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  13313. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  13314. if ( !location ) continue;
  13315. uniform = uniforms[ j ][ 0 ];
  13316. type = uniform.type;
  13317. value = uniform.value;
  13318. if ( type === "i" ) { // single integer
  13319. _gl.uniform1i( location, value );
  13320. } else if ( type === "f" ) { // single float
  13321. _gl.uniform1f( location, value );
  13322. } else if ( type === "v2" ) { // single THREE.Vector2
  13323. _gl.uniform2f( location, value.x, value.y );
  13324. } else if ( type === "v3" ) { // single THREE.Vector3
  13325. _gl.uniform3f( location, value.x, value.y, value.z );
  13326. } else if ( type === "v4" ) { // single THREE.Vector4
  13327. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  13328. } else if ( type === "c" ) { // single THREE.Color
  13329. _gl.uniform3f( location, value.r, value.g, value.b );
  13330. } else if ( type === "iv1" ) { // flat array of integers (JS or typed array)
  13331. _gl.uniform1iv( location, value );
  13332. } else if ( type === "iv" ) { // flat array of integers with 3 x N size (JS or typed array)
  13333. _gl.uniform3iv( location, value );
  13334. } else if ( type === "fv1" ) { // flat array of floats (JS or typed array)
  13335. _gl.uniform1fv( location, value );
  13336. } else if ( type === "fv" ) { // flat array of floats with 3 x N size (JS or typed array)
  13337. _gl.uniform3fv( location, value );
  13338. } else if ( type === "v2v" ) { // array of THREE.Vector2
  13339. if ( uniform._array === undefined ) {
  13340. uniform._array = new Float32Array( 2 * value.length );
  13341. }
  13342. for ( i = 0, il = value.length; i < il; i ++ ) {
  13343. offset = i * 2;
  13344. uniform._array[ offset ] = value[ i ].x;
  13345. uniform._array[ offset + 1 ] = value[ i ].y;
  13346. }
  13347. _gl.uniform2fv( location, uniform._array );
  13348. } else if ( type === "v3v" ) { // array of THREE.Vector3
  13349. if ( uniform._array === undefined ) {
  13350. uniform._array = new Float32Array( 3 * value.length );
  13351. }
  13352. for ( i = 0, il = value.length; i < il; i ++ ) {
  13353. offset = i * 3;
  13354. uniform._array[ offset ] = value[ i ].x;
  13355. uniform._array[ offset + 1 ] = value[ i ].y;
  13356. uniform._array[ offset + 2 ] = value[ i ].z;
  13357. }
  13358. _gl.uniform3fv( location, uniform._array );
  13359. } else if ( type === "v4v" ) { // array of THREE.Vector4
  13360. if ( uniform._array === undefined ) {
  13361. uniform._array = new Float32Array( 4 * value.length );
  13362. }
  13363. for ( i = 0, il = value.length; i < il; i ++ ) {
  13364. offset = i * 4;
  13365. uniform._array[ offset ] = value[ i ].x;
  13366. uniform._array[ offset + 1 ] = value[ i ].y;
  13367. uniform._array[ offset + 2 ] = value[ i ].z;
  13368. uniform._array[ offset + 3 ] = value[ i ].w;
  13369. }
  13370. _gl.uniform4fv( location, uniform._array );
  13371. } else if ( type === "m4") { // single THREE.Matrix4
  13372. if ( uniform._array === undefined ) {
  13373. uniform._array = new Float32Array( 16 );
  13374. }
  13375. value.flattenToArray( uniform._array );
  13376. _gl.uniformMatrix4fv( location, false, uniform._array );
  13377. } else if ( type === "m4v" ) { // array of THREE.Matrix4
  13378. if ( uniform._array === undefined ) {
  13379. uniform._array = new Float32Array( 16 * value.length );
  13380. }
  13381. for ( i = 0, il = value.length; i < il; i ++ ) {
  13382. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  13383. }
  13384. _gl.uniformMatrix4fv( location, false, uniform._array );
  13385. } else if ( type === "t" ) { // single THREE.Texture (2d or cube)
  13386. texture = value;
  13387. textureUnit = getTextureUnit();
  13388. _gl.uniform1i( location, textureUnit );
  13389. if ( !texture ) continue;
  13390. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  13391. setCubeTexture( texture, textureUnit );
  13392. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  13393. setCubeTextureDynamic( texture, textureUnit );
  13394. } else {
  13395. _this.setTexture( texture, textureUnit );
  13396. }
  13397. } else if ( type === "tv" ) { // array of THREE.Texture (2d)
  13398. if ( uniform._array === undefined ) {
  13399. uniform._array = [];
  13400. }
  13401. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13402. uniform._array[ i ] = getTextureUnit();
  13403. }
  13404. _gl.uniform1iv( location, uniform._array );
  13405. for( i = 0, il = uniform.value.length; i < il; i ++ ) {
  13406. texture = uniform.value[ i ];
  13407. textureUnit = uniform._array[ i ];
  13408. if ( !texture ) continue;
  13409. _this.setTexture( texture, textureUnit );
  13410. }
  13411. }
  13412. }
  13413. };
  13414. function setupMatrices ( object, camera ) {
  13415. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  13416. object._normalMatrix.getInverse( object._modelViewMatrix );
  13417. object._normalMatrix.transpose();
  13418. };
  13419. //
  13420. function setColorGamma( array, offset, color, intensitySq ) {
  13421. array[ offset ] = color.r * color.r * intensitySq;
  13422. array[ offset + 1 ] = color.g * color.g * intensitySq;
  13423. array[ offset + 2 ] = color.b * color.b * intensitySq;
  13424. };
  13425. function setColorLinear( array, offset, color, intensity ) {
  13426. array[ offset ] = color.r * intensity;
  13427. array[ offset + 1 ] = color.g * intensity;
  13428. array[ offset + 2 ] = color.b * intensity;
  13429. };
  13430. function setupLights ( program, lights ) {
  13431. var l, ll, light, n,
  13432. r = 0, g = 0, b = 0,
  13433. color, skyColor, groundColor,
  13434. intensity, intensitySq,
  13435. position,
  13436. distance,
  13437. zlights = _lights,
  13438. dirColors = zlights.directional.colors,
  13439. dirPositions = zlights.directional.positions,
  13440. pointColors = zlights.point.colors,
  13441. pointPositions = zlights.point.positions,
  13442. pointDistances = zlights.point.distances,
  13443. spotColors = zlights.spot.colors,
  13444. spotPositions = zlights.spot.positions,
  13445. spotDistances = zlights.spot.distances,
  13446. spotDirections = zlights.spot.directions,
  13447. spotAnglesCos = zlights.spot.anglesCos,
  13448. spotExponents = zlights.spot.exponents,
  13449. hemiSkyColors = zlights.hemi.skyColors,
  13450. hemiGroundColors = zlights.hemi.groundColors,
  13451. hemiPositions = zlights.hemi.positions,
  13452. dirLength = 0,
  13453. pointLength = 0,
  13454. spotLength = 0,
  13455. hemiLength = 0,
  13456. dirCount = 0,
  13457. pointCount = 0,
  13458. spotCount = 0,
  13459. hemiCount = 0,
  13460. dirOffset = 0,
  13461. pointOffset = 0,
  13462. spotOffset = 0,
  13463. hemiOffset = 0;
  13464. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  13465. light = lights[ l ];
  13466. if ( light.onlyShadow ) continue;
  13467. color = light.color;
  13468. intensity = light.intensity;
  13469. distance = light.distance;
  13470. if ( light instanceof THREE.AmbientLight ) {
  13471. if ( ! light.visible ) continue;
  13472. if ( _this.gammaInput ) {
  13473. r += color.r * color.r;
  13474. g += color.g * color.g;
  13475. b += color.b * color.b;
  13476. } else {
  13477. r += color.r;
  13478. g += color.g;
  13479. b += color.b;
  13480. }
  13481. } else if ( light instanceof THREE.DirectionalLight ) {
  13482. dirCount += 1;
  13483. if ( ! light.visible ) continue;
  13484. dirOffset = dirLength * 3;
  13485. if ( _this.gammaInput ) {
  13486. setColorGamma( dirColors, dirOffset, color, intensity * intensity );
  13487. } else {
  13488. setColorLinear( dirColors, dirOffset, color, intensity );
  13489. }
  13490. _direction.copy( light.matrixWorld.getPosition() );
  13491. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13492. _direction.normalize();
  13493. dirPositions[ dirOffset ] = _direction.x;
  13494. dirPositions[ dirOffset + 1 ] = _direction.y;
  13495. dirPositions[ dirOffset + 2 ] = _direction.z;
  13496. dirLength += 1;
  13497. } else if ( light instanceof THREE.PointLight ) {
  13498. pointCount += 1;
  13499. if ( ! light.visible ) continue;
  13500. pointOffset = pointLength * 3;
  13501. if ( _this.gammaInput ) {
  13502. setColorGamma( pointColors, pointOffset, color, intensity * intensity );
  13503. } else {
  13504. setColorLinear( pointColors, pointOffset, color, intensity );
  13505. }
  13506. position = light.matrixWorld.getPosition();
  13507. pointPositions[ pointOffset ] = position.x;
  13508. pointPositions[ pointOffset + 1 ] = position.y;
  13509. pointPositions[ pointOffset + 2 ] = position.z;
  13510. pointDistances[ pointLength ] = distance;
  13511. pointLength += 1;
  13512. } else if ( light instanceof THREE.SpotLight ) {
  13513. spotCount += 1;
  13514. if ( ! light.visible ) continue;
  13515. spotOffset = spotLength * 3;
  13516. if ( _this.gammaInput ) {
  13517. setColorGamma( spotColors, spotOffset, color, intensity * intensity );
  13518. } else {
  13519. setColorLinear( spotColors, spotOffset, color, intensity );
  13520. }
  13521. position = light.matrixWorld.getPosition();
  13522. spotPositions[ spotOffset ] = position.x;
  13523. spotPositions[ spotOffset + 1 ] = position.y;
  13524. spotPositions[ spotOffset + 2 ] = position.z;
  13525. spotDistances[ spotLength ] = distance;
  13526. _direction.copy( position );
  13527. _direction.subSelf( light.target.matrixWorld.getPosition() );
  13528. _direction.normalize();
  13529. spotDirections[ spotOffset ] = _direction.x;
  13530. spotDirections[ spotOffset + 1 ] = _direction.y;
  13531. spotDirections[ spotOffset + 2 ] = _direction.z;
  13532. spotAnglesCos[ spotLength ] = Math.cos( light.angle );
  13533. spotExponents[ spotLength ] = light.exponent;
  13534. spotLength += 1;
  13535. } else if ( light instanceof THREE.HemisphereLight ) {
  13536. hemiCount += 1;
  13537. if ( ! light.visible ) continue;
  13538. skyColor = light.color;
  13539. groundColor = light.groundColor;
  13540. hemiOffset = hemiLength * 3;
  13541. if ( _this.gammaInput ) {
  13542. intensitySq = intensity * intensity;
  13543. setColorGamma( hemiSkyColors, hemiOffset, skyColor, intensitySq );
  13544. setColorGamma( hemiGroundColors, hemiOffset, groundColor, intensitySq );
  13545. } else {
  13546. setColorLinear( hemiSkyColors, hemiOffset, skyColor, intensity );
  13547. setColorLinear( hemiGroundColors, hemiOffset, groundColor, intensity );
  13548. }
  13549. _direction.copy( light.matrixWorld.getPosition() );
  13550. _direction.normalize();
  13551. hemiPositions[ hemiOffset ] = _direction.x;
  13552. hemiPositions[ hemiOffset + 1 ] = _direction.y;
  13553. hemiPositions[ hemiOffset + 2 ] = _direction.z;
  13554. hemiLength += 1;
  13555. }
  13556. }
  13557. // null eventual remains from removed lights
  13558. // (this is to avoid if in shader)
  13559. for ( l = dirLength * 3, ll = Math.max( dirColors.length, dirCount * 3 ); l < ll; l ++ ) dirColors[ l ] = 0.0;
  13560. for ( l = dirLength * 3, ll = Math.max( dirPositions.length, dirCount * 3 ); l < ll; l ++ ) dirPositions[ l ] = 0.0;
  13561. for ( l = pointLength * 3, ll = Math.max( pointColors.length, pointCount * 3 ); l < ll; l ++ ) pointColors[ l ] = 0.0;
  13562. for ( l = pointLength * 3, ll = Math.max( pointPositions.length, pointCount * 3 ); l < ll; l ++ ) pointPositions[ l ] = 0.0;
  13563. for ( l = pointLength, ll = Math.max( pointDistances.length, pointCount ); l < ll; l ++ ) pointDistances[ l ] = 0.0;
  13564. for ( l = spotLength * 3, ll = Math.max( spotColors.length, spotCount * 3 ); l < ll; l ++ ) spotColors[ l ] = 0.0;
  13565. for ( l = spotLength * 3, ll = Math.max( spotPositions.length, spotCount * 3 ); l < ll; l ++ ) spotPositions[ l ] = 0.0;
  13566. for ( l = spotLength * 3, ll = Math.max( spotDirections.length, spotCount * 3 ); l < ll; l ++ ) spotDirections[ l ] = 0.0;
  13567. for ( l = spotLength, ll = Math.max( spotAnglesCos.length, spotCount ); l < ll; l ++ ) spotAnglesCos[ l ] = 0.0;
  13568. for ( l = spotLength, ll = Math.max( spotExponents.length, spotCount ); l < ll; l ++ ) spotExponents[ l ] = 0.0;
  13569. for ( l = spotLength, ll = Math.max( spotDistances.length, spotCount ); l < ll; l ++ ) spotDistances[ l ] = 0.0;
  13570. for ( l = hemiLength * 3, ll = Math.max( hemiSkyColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiSkyColors[ l ] = 0.0;
  13571. for ( l = hemiLength * 3, ll = Math.max( hemiGroundColors.length, hemiCount * 3 ); l < ll; l ++ ) hemiGroundColors[ l ] = 0.0;
  13572. for ( l = hemiLength * 3, ll = Math.max( hemiPositions.length, hemiCount * 3 ); l < ll; l ++ ) hemiPositions[ l ] = 0.0;
  13573. zlights.directional.length = dirLength;
  13574. zlights.point.length = pointLength;
  13575. zlights.spot.length = spotLength;
  13576. zlights.hemi.length = hemiLength;
  13577. zlights.ambient[ 0 ] = r;
  13578. zlights.ambient[ 1 ] = g;
  13579. zlights.ambient[ 2 ] = b;
  13580. };
  13581. // GL state setting
  13582. this.setFaceCulling = function ( cullFace, frontFaceDirection ) {
  13583. if ( cullFace === THREE.CullFaceNone ) {
  13584. _gl.disable( _gl.CULL_FACE );
  13585. } else {
  13586. if ( frontFaceDirection === THREE.FrontFaceDirectionCW ) {
  13587. _gl.frontFace( _gl.CW );
  13588. } else {
  13589. _gl.frontFace( _gl.CCW );
  13590. }
  13591. if ( cullFace === THREE.CullFaceBack ) {
  13592. _gl.cullFace( _gl.BACK );
  13593. } else if ( cullFace === THREE.CullFaceFront ) {
  13594. _gl.cullFace( _gl.FRONT );
  13595. } else {
  13596. _gl.cullFace( _gl.FRONT_AND_BACK );
  13597. }
  13598. _gl.enable( _gl.CULL_FACE );
  13599. }
  13600. };
  13601. this.setMaterialFaces = function ( material ) {
  13602. var doubleSided = material.side === THREE.DoubleSide;
  13603. var flipSided = material.side === THREE.BackSide;
  13604. if ( _oldDoubleSided !== doubleSided ) {
  13605. if ( doubleSided ) {
  13606. _gl.disable( _gl.CULL_FACE );
  13607. } else {
  13608. _gl.enable( _gl.CULL_FACE );
  13609. }
  13610. _oldDoubleSided = doubleSided;
  13611. }
  13612. if ( _oldFlipSided !== flipSided ) {
  13613. if ( flipSided ) {
  13614. _gl.frontFace( _gl.CW );
  13615. } else {
  13616. _gl.frontFace( _gl.CCW );
  13617. }
  13618. _oldFlipSided = flipSided;
  13619. }
  13620. };
  13621. this.setDepthTest = function ( depthTest ) {
  13622. if ( _oldDepthTest !== depthTest ) {
  13623. if ( depthTest ) {
  13624. _gl.enable( _gl.DEPTH_TEST );
  13625. } else {
  13626. _gl.disable( _gl.DEPTH_TEST );
  13627. }
  13628. _oldDepthTest = depthTest;
  13629. }
  13630. };
  13631. this.setDepthWrite = function ( depthWrite ) {
  13632. if ( _oldDepthWrite !== depthWrite ) {
  13633. _gl.depthMask( depthWrite );
  13634. _oldDepthWrite = depthWrite;
  13635. }
  13636. };
  13637. function setLineWidth ( width ) {
  13638. if ( width !== _oldLineWidth ) {
  13639. _gl.lineWidth( width );
  13640. _oldLineWidth = width;
  13641. }
  13642. };
  13643. function setPolygonOffset ( polygonoffset, factor, units ) {
  13644. if ( _oldPolygonOffset !== polygonoffset ) {
  13645. if ( polygonoffset ) {
  13646. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  13647. } else {
  13648. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  13649. }
  13650. _oldPolygonOffset = polygonoffset;
  13651. }
  13652. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  13653. _gl.polygonOffset( factor, units );
  13654. _oldPolygonOffsetFactor = factor;
  13655. _oldPolygonOffsetUnits = units;
  13656. }
  13657. };
  13658. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  13659. if ( blending !== _oldBlending ) {
  13660. if ( blending === THREE.NoBlending ) {
  13661. _gl.disable( _gl.BLEND );
  13662. } else if ( blending === THREE.AdditiveBlending ) {
  13663. _gl.enable( _gl.BLEND );
  13664. _gl.blendEquation( _gl.FUNC_ADD );
  13665. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  13666. } else if ( blending === THREE.SubtractiveBlending ) {
  13667. // TODO: Find blendFuncSeparate() combination
  13668. _gl.enable( _gl.BLEND );
  13669. _gl.blendEquation( _gl.FUNC_ADD );
  13670. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  13671. } else if ( blending === THREE.MultiplyBlending ) {
  13672. // TODO: Find blendFuncSeparate() combination
  13673. _gl.enable( _gl.BLEND );
  13674. _gl.blendEquation( _gl.FUNC_ADD );
  13675. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  13676. } else if ( blending === THREE.CustomBlending ) {
  13677. _gl.enable( _gl.BLEND );
  13678. } else {
  13679. _gl.enable( _gl.BLEND );
  13680. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  13681. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  13682. }
  13683. _oldBlending = blending;
  13684. }
  13685. if ( blending === THREE.CustomBlending ) {
  13686. if ( blendEquation !== _oldBlendEquation ) {
  13687. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  13688. _oldBlendEquation = blendEquation;
  13689. }
  13690. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  13691. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  13692. _oldBlendSrc = blendSrc;
  13693. _oldBlendDst = blendDst;
  13694. }
  13695. } else {
  13696. _oldBlendEquation = null;
  13697. _oldBlendSrc = null;
  13698. _oldBlendDst = null;
  13699. }
  13700. };
  13701. // Defines
  13702. function generateDefines ( defines ) {
  13703. var value, chunk, chunks = [];
  13704. for ( var d in defines ) {
  13705. value = defines[ d ];
  13706. if ( value === false ) continue;
  13707. chunk = "#define " + d + " " + value;
  13708. chunks.push( chunk );
  13709. }
  13710. return chunks.join( "\n" );
  13711. };
  13712. // Shaders
  13713. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, defines, parameters ) {
  13714. var p, pl, d, program, code;
  13715. var chunks = [];
  13716. // Generate code
  13717. if ( shaderID ) {
  13718. chunks.push( shaderID );
  13719. } else {
  13720. chunks.push( fragmentShader );
  13721. chunks.push( vertexShader );
  13722. }
  13723. for ( d in defines ) {
  13724. chunks.push( d );
  13725. chunks.push( defines[ d ] );
  13726. }
  13727. for ( p in parameters ) {
  13728. chunks.push( p );
  13729. chunks.push( parameters[ p ] );
  13730. }
  13731. code = chunks.join();
  13732. // Check if code has been already compiled
  13733. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  13734. var programInfo = _programs[ p ];
  13735. if ( programInfo.code === code ) {
  13736. //console.log( "Code already compiled." /*: \n\n" + code*/ );
  13737. programInfo.usedTimes ++;
  13738. return programInfo.program;
  13739. }
  13740. }
  13741. //console.log( "building new program " );
  13742. //
  13743. var customDefines = generateDefines( defines );
  13744. //
  13745. program = _gl.createProgram();
  13746. var prefix_vertex = [
  13747. "precision " + _precision + " float;",
  13748. customDefines,
  13749. _supportsVertexTextures ? "#define VERTEX_TEXTURES" : "",
  13750. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13751. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13752. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13753. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13754. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13755. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13756. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13757. "#define MAX_SHADOWS " + parameters.maxShadows,
  13758. "#define MAX_BONES " + parameters.maxBones,
  13759. parameters.map ? "#define USE_MAP" : "",
  13760. parameters.envMap ? "#define USE_ENVMAP" : "",
  13761. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13762. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13763. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13764. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13765. parameters.vertexColors ? "#define USE_COLOR" : "",
  13766. parameters.skinning ? "#define USE_SKINNING" : "",
  13767. parameters.useVertexTexture ? "#define BONE_TEXTURE" : "",
  13768. parameters.boneTextureWidth ? "#define N_BONE_PIXEL_X " + parameters.boneTextureWidth.toFixed( 1 ) : "",
  13769. parameters.boneTextureHeight ? "#define N_BONE_PIXEL_Y " + parameters.boneTextureHeight.toFixed( 1 ) : "",
  13770. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  13771. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  13772. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13773. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13774. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13775. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13776. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13777. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13778. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13779. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13780. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  13781. "uniform mat4 modelMatrix;",
  13782. "uniform mat4 modelViewMatrix;",
  13783. "uniform mat4 projectionMatrix;",
  13784. "uniform mat4 viewMatrix;",
  13785. "uniform mat3 normalMatrix;",
  13786. "uniform vec3 cameraPosition;",
  13787. "attribute vec3 position;",
  13788. "attribute vec3 normal;",
  13789. "attribute vec2 uv;",
  13790. "attribute vec2 uv2;",
  13791. "#ifdef USE_COLOR",
  13792. "attribute vec3 color;",
  13793. "#endif",
  13794. "#ifdef USE_MORPHTARGETS",
  13795. "attribute vec3 morphTarget0;",
  13796. "attribute vec3 morphTarget1;",
  13797. "attribute vec3 morphTarget2;",
  13798. "attribute vec3 morphTarget3;",
  13799. "#ifdef USE_MORPHNORMALS",
  13800. "attribute vec3 morphNormal0;",
  13801. "attribute vec3 morphNormal1;",
  13802. "attribute vec3 morphNormal2;",
  13803. "attribute vec3 morphNormal3;",
  13804. "#else",
  13805. "attribute vec3 morphTarget4;",
  13806. "attribute vec3 morphTarget5;",
  13807. "attribute vec3 morphTarget6;",
  13808. "attribute vec3 morphTarget7;",
  13809. "#endif",
  13810. "#endif",
  13811. "#ifdef USE_SKINNING",
  13812. "attribute vec4 skinIndex;",
  13813. "attribute vec4 skinWeight;",
  13814. "#endif",
  13815. ""
  13816. ].join("\n");
  13817. var prefix_fragment = [
  13818. "precision " + _precision + " float;",
  13819. ( parameters.bumpMap || parameters.normalMap ) ? "#extension GL_OES_standard_derivatives : enable" : "",
  13820. customDefines,
  13821. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  13822. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  13823. "#define MAX_SPOT_LIGHTS " + parameters.maxSpotLights,
  13824. "#define MAX_HEMI_LIGHTS " + parameters.maxHemiLights,
  13825. "#define MAX_SHADOWS " + parameters.maxShadows,
  13826. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  13827. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  13828. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  13829. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  13830. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  13831. ( parameters.useFog && parameters.fogExp ) ? "#define FOG_EXP2" : "",
  13832. parameters.map ? "#define USE_MAP" : "",
  13833. parameters.envMap ? "#define USE_ENVMAP" : "",
  13834. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  13835. parameters.bumpMap ? "#define USE_BUMPMAP" : "",
  13836. parameters.normalMap ? "#define USE_NORMALMAP" : "",
  13837. parameters.specularMap ? "#define USE_SPECULARMAP" : "",
  13838. parameters.vertexColors ? "#define USE_COLOR" : "",
  13839. parameters.metal ? "#define METAL" : "",
  13840. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  13841. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  13842. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  13843. parameters.flipSided ? "#define FLIP_SIDED" : "",
  13844. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  13845. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  13846. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  13847. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  13848. "uniform mat4 viewMatrix;",
  13849. "uniform vec3 cameraPosition;",
  13850. ""
  13851. ].join("\n");
  13852. var glFragmentShader = getShader( "fragment", prefix_fragment + fragmentShader );
  13853. var glVertexShader = getShader( "vertex", prefix_vertex + vertexShader );
  13854. _gl.attachShader( program, glVertexShader );
  13855. _gl.attachShader( program, glFragmentShader );
  13856. _gl.linkProgram( program );
  13857. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  13858. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  13859. }
  13860. // clean up
  13861. _gl.deleteShader( glFragmentShader );
  13862. _gl.deleteShader( glVertexShader );
  13863. //console.log( prefix_fragment + fragmentShader );
  13864. //console.log( prefix_vertex + vertexShader );
  13865. program.uniforms = {};
  13866. program.attributes = {};
  13867. var identifiers, u, a, i;
  13868. // cache uniform locations
  13869. identifiers = [
  13870. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'modelMatrix', 'cameraPosition',
  13871. 'morphTargetInfluences'
  13872. ];
  13873. if ( parameters.useVertexTexture ) {
  13874. identifiers.push( 'boneTexture' );
  13875. } else {
  13876. identifiers.push( 'boneGlobalMatrices' );
  13877. }
  13878. for ( u in uniforms ) {
  13879. identifiers.push( u );
  13880. }
  13881. cacheUniformLocations( program, identifiers );
  13882. // cache attributes locations
  13883. identifiers = [
  13884. "position", "normal", "uv", "uv2", "tangent", "color",
  13885. "skinIndex", "skinWeight", "lineDistance"
  13886. ];
  13887. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  13888. identifiers.push( "morphTarget" + i );
  13889. }
  13890. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  13891. identifiers.push( "morphNormal" + i );
  13892. }
  13893. for ( a in attributes ) {
  13894. identifiers.push( a );
  13895. }
  13896. cacheAttributeLocations( program, identifiers );
  13897. program.id = _programs_counter ++;
  13898. _programs.push( { program: program, code: code, usedTimes: 1 } );
  13899. _this.info.memory.programs = _programs.length;
  13900. return program;
  13901. };
  13902. // Shader parameters cache
  13903. function cacheUniformLocations ( program, identifiers ) {
  13904. var i, l, id;
  13905. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13906. id = identifiers[ i ];
  13907. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  13908. }
  13909. };
  13910. function cacheAttributeLocations ( program, identifiers ) {
  13911. var i, l, id;
  13912. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  13913. id = identifiers[ i ];
  13914. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  13915. }
  13916. };
  13917. function addLineNumbers ( string ) {
  13918. var chunks = string.split( "\n" );
  13919. for ( var i = 0, il = chunks.length; i < il; i ++ ) {
  13920. // Chrome reports shader errors on lines
  13921. // starting counting from 1
  13922. chunks[ i ] = ( i + 1 ) + ": " + chunks[ i ];
  13923. }
  13924. return chunks.join( "\n" );
  13925. };
  13926. function getShader ( type, string ) {
  13927. var shader;
  13928. if ( type === "fragment" ) {
  13929. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  13930. } else if ( type === "vertex" ) {
  13931. shader = _gl.createShader( _gl.VERTEX_SHADER );
  13932. }
  13933. _gl.shaderSource( shader, string );
  13934. _gl.compileShader( shader );
  13935. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  13936. console.error( _gl.getShaderInfoLog( shader ) );
  13937. console.error( addLineNumbers( string ) );
  13938. return null;
  13939. }
  13940. return shader;
  13941. };
  13942. // Textures
  13943. function isPowerOfTwo ( value ) {
  13944. return ( value & ( value - 1 ) ) === 0;
  13945. };
  13946. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  13947. if ( isImagePowerOfTwo ) {
  13948. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  13949. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  13950. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  13951. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  13952. } else {
  13953. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  13954. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  13955. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  13956. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  13957. }
  13958. if ( _glExtensionTextureFilterAnisotropic && texture.type !== THREE.FloatType ) {
  13959. if ( texture.anisotropy > 1 || texture.__oldAnisotropy ) {
  13960. _gl.texParameterf( textureType, _glExtensionTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, Math.min( texture.anisotropy, _maxAnisotropy ) );
  13961. texture.__oldAnisotropy = texture.anisotropy;
  13962. }
  13963. }
  13964. };
  13965. this.setTexture = function ( texture, slot ) {
  13966. if ( texture.needsUpdate ) {
  13967. if ( ! texture.__webglInit ) {
  13968. texture.__webglInit = true;
  13969. texture.__webglTexture = _gl.createTexture();
  13970. _this.info.memory.textures ++;
  13971. }
  13972. _gl.activeTexture( _gl.TEXTURE0 + slot );
  13973. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  13974. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  13975. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  13976. _gl.pixelStorei( _gl.UNPACK_ALIGNMENT, texture.unpackAlignment );
  13977. var image = texture.image,
  13978. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  13979. glFormat = paramThreeToGL( texture.format ),
  13980. glType = paramThreeToGL( texture.type );
  13981. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  13982. var mipmap, mipmaps = texture.mipmaps;
  13983. if ( texture instanceof THREE.DataTexture ) {
  13984. // use manually created mipmaps if available
  13985. // if there are no manual mipmaps
  13986. // set 0 level mipmap and then use GL to generate other mipmap levels
  13987. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  13988. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  13989. mipmap = mipmaps[ i ];
  13990. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, glFormat, glType, mipmap.data );
  13991. }
  13992. texture.generateMipmaps = false;
  13993. } else {
  13994. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  13995. }
  13996. } else if ( texture instanceof THREE.CompressedTexture ) {
  13997. // compressed textures can only use manually created mipmaps
  13998. // WebGL can't generate mipmaps for DDS textures
  13999. for( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14000. mipmap = mipmaps[ i ];
  14001. _gl.compressedTexImage2D( _gl.TEXTURE_2D, i, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14002. }
  14003. } else { // regular Texture (image, video, canvas)
  14004. // use manually created mipmaps if available
  14005. // if there are no manual mipmaps
  14006. // set 0 level mipmap and then use GL to generate other mipmap levels
  14007. if ( mipmaps.length > 0 && isImagePowerOfTwo ) {
  14008. for ( var i = 0, il = mipmaps.length; i < il; i ++ ) {
  14009. mipmap = mipmaps[ i ];
  14010. _gl.texImage2D( _gl.TEXTURE_2D, i, glFormat, glFormat, glType, mipmap );
  14011. }
  14012. texture.generateMipmaps = false;
  14013. } else {
  14014. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  14015. }
  14016. }
  14017. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14018. texture.needsUpdate = false;
  14019. if ( texture.onUpdate ) texture.onUpdate();
  14020. } else {
  14021. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14022. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  14023. }
  14024. };
  14025. function clampToMaxSize ( image, maxSize ) {
  14026. if ( image.width <= maxSize && image.height <= maxSize ) {
  14027. return image;
  14028. }
  14029. // Warning: Scaling through the canvas will only work with images that use
  14030. // premultiplied alpha.
  14031. var maxDimension = Math.max( image.width, image.height );
  14032. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  14033. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  14034. var canvas = document.createElement( 'canvas' );
  14035. canvas.width = newWidth;
  14036. canvas.height = newHeight;
  14037. var ctx = canvas.getContext( "2d" );
  14038. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  14039. return canvas;
  14040. }
  14041. function setCubeTexture ( texture, slot ) {
  14042. if ( texture.image.length === 6 ) {
  14043. if ( texture.needsUpdate ) {
  14044. if ( ! texture.image.__webglTextureCube ) {
  14045. texture.image.__webglTextureCube = _gl.createTexture();
  14046. _this.info.memory.textures ++;
  14047. }
  14048. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14049. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14050. _gl.pixelStorei( _gl.UNPACK_FLIP_Y_WEBGL, texture.flipY );
  14051. var isCompressed = texture instanceof THREE.CompressedTexture;
  14052. var cubeImage = [];
  14053. for ( var i = 0; i < 6; i ++ ) {
  14054. if ( _this.autoScaleCubemaps && ! isCompressed ) {
  14055. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  14056. } else {
  14057. cubeImage[ i ] = texture.image[ i ];
  14058. }
  14059. }
  14060. var image = cubeImage[ 0 ],
  14061. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  14062. glFormat = paramThreeToGL( texture.format ),
  14063. glType = paramThreeToGL( texture.type );
  14064. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  14065. for ( var i = 0; i < 6; i ++ ) {
  14066. if ( isCompressed ) {
  14067. var mipmap, mipmaps = cubeImage[ i ].mipmaps;
  14068. for( var j = 0, jl = mipmaps.length; j < jl; j ++ ) {
  14069. mipmap = mipmaps[ j ];
  14070. _gl.compressedTexImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, j, glFormat, mipmap.width, mipmap.height, 0, mipmap.data );
  14071. }
  14072. } else {
  14073. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  14074. }
  14075. }
  14076. if ( texture.generateMipmaps && isImagePowerOfTwo ) {
  14077. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14078. }
  14079. texture.needsUpdate = false;
  14080. if ( texture.onUpdate ) texture.onUpdate();
  14081. } else {
  14082. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14083. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  14084. }
  14085. }
  14086. };
  14087. function setCubeTextureDynamic ( texture, slot ) {
  14088. _gl.activeTexture( _gl.TEXTURE0 + slot );
  14089. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  14090. };
  14091. // Render targets
  14092. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  14093. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14094. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  14095. };
  14096. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  14097. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  14098. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  14099. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  14100. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14101. /* For some reason this is not working. Defaulting to RGBA4.
  14102. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14103. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  14104. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14105. */
  14106. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  14107. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  14108. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  14109. } else {
  14110. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  14111. }
  14112. };
  14113. this.setRenderTarget = function ( renderTarget ) {
  14114. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  14115. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  14116. if ( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  14117. if ( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  14118. renderTarget.__webglTexture = _gl.createTexture();
  14119. _this.info.memory.textures ++;
  14120. // Setup texture, create render and frame buffers
  14121. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  14122. glFormat = paramThreeToGL( renderTarget.format ),
  14123. glType = paramThreeToGL( renderTarget.type );
  14124. if ( isCube ) {
  14125. renderTarget.__webglFramebuffer = [];
  14126. renderTarget.__webglRenderbuffer = [];
  14127. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14128. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  14129. for ( var i = 0; i < 6; i ++ ) {
  14130. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  14131. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  14132. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14133. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  14134. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  14135. }
  14136. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14137. } else {
  14138. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  14139. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  14140. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14141. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  14142. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  14143. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  14144. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  14145. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  14146. }
  14147. // Release everything
  14148. if ( isCube ) {
  14149. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14150. } else {
  14151. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14152. }
  14153. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  14154. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null );
  14155. }
  14156. var framebuffer, width, height, vx, vy;
  14157. if ( renderTarget ) {
  14158. if ( isCube ) {
  14159. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  14160. } else {
  14161. framebuffer = renderTarget.__webglFramebuffer;
  14162. }
  14163. width = renderTarget.width;
  14164. height = renderTarget.height;
  14165. vx = 0;
  14166. vy = 0;
  14167. } else {
  14168. framebuffer = null;
  14169. width = _viewportWidth;
  14170. height = _viewportHeight;
  14171. vx = _viewportX;
  14172. vy = _viewportY;
  14173. }
  14174. if ( framebuffer !== _currentFramebuffer ) {
  14175. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  14176. _gl.viewport( vx, vy, width, height );
  14177. _currentFramebuffer = framebuffer;
  14178. }
  14179. _currentWidth = width;
  14180. _currentHeight = height;
  14181. };
  14182. function updateRenderTargetMipmap ( renderTarget ) {
  14183. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  14184. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  14185. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  14186. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  14187. } else {
  14188. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  14189. _gl.generateMipmap( _gl.TEXTURE_2D );
  14190. _gl.bindTexture( _gl.TEXTURE_2D, null );
  14191. }
  14192. };
  14193. // Fallback filters for non-power-of-2 textures
  14194. function filterFallback ( f ) {
  14195. if ( f === THREE.NearestFilter || f === THREE.NearestMipMapNearestFilter || f === THREE.NearestMipMapLinearFilter ) {
  14196. return _gl.NEAREST;
  14197. }
  14198. return _gl.LINEAR;
  14199. };
  14200. // Map three.js constants to WebGL constants
  14201. function paramThreeToGL ( p ) {
  14202. if ( p === THREE.RepeatWrapping ) return _gl.REPEAT;
  14203. if ( p === THREE.ClampToEdgeWrapping ) return _gl.CLAMP_TO_EDGE;
  14204. if ( p === THREE.MirroredRepeatWrapping ) return _gl.MIRRORED_REPEAT;
  14205. if ( p === THREE.NearestFilter ) return _gl.NEAREST;
  14206. if ( p === THREE.NearestMipMapNearestFilter ) return _gl.NEAREST_MIPMAP_NEAREST;
  14207. if ( p === THREE.NearestMipMapLinearFilter ) return _gl.NEAREST_MIPMAP_LINEAR;
  14208. if ( p === THREE.LinearFilter ) return _gl.LINEAR;
  14209. if ( p === THREE.LinearMipMapNearestFilter ) return _gl.LINEAR_MIPMAP_NEAREST;
  14210. if ( p === THREE.LinearMipMapLinearFilter ) return _gl.LINEAR_MIPMAP_LINEAR;
  14211. if ( p === THREE.UnsignedByteType ) return _gl.UNSIGNED_BYTE;
  14212. if ( p === THREE.UnsignedShort4444Type ) return _gl.UNSIGNED_SHORT_4_4_4_4;
  14213. if ( p === THREE.UnsignedShort5551Type ) return _gl.UNSIGNED_SHORT_5_5_5_1;
  14214. if ( p === THREE.UnsignedShort565Type ) return _gl.UNSIGNED_SHORT_5_6_5;
  14215. if ( p === THREE.ByteType ) return _gl.BYTE;
  14216. if ( p === THREE.ShortType ) return _gl.SHORT;
  14217. if ( p === THREE.UnsignedShortType ) return _gl.UNSIGNED_SHORT;
  14218. if ( p === THREE.IntType ) return _gl.INT;
  14219. if ( p === THREE.UnsignedIntType ) return _gl.UNSIGNED_INT;
  14220. if ( p === THREE.FloatType ) return _gl.FLOAT;
  14221. if ( p === THREE.AlphaFormat ) return _gl.ALPHA;
  14222. if ( p === THREE.RGBFormat ) return _gl.RGB;
  14223. if ( p === THREE.RGBAFormat ) return _gl.RGBA;
  14224. if ( p === THREE.LuminanceFormat ) return _gl.LUMINANCE;
  14225. if ( p === THREE.LuminanceAlphaFormat ) return _gl.LUMINANCE_ALPHA;
  14226. if ( p === THREE.AddEquation ) return _gl.FUNC_ADD;
  14227. if ( p === THREE.SubtractEquation ) return _gl.FUNC_SUBTRACT;
  14228. if ( p === THREE.ReverseSubtractEquation ) return _gl.FUNC_REVERSE_SUBTRACT;
  14229. if ( p === THREE.ZeroFactor ) return _gl.ZERO;
  14230. if ( p === THREE.OneFactor ) return _gl.ONE;
  14231. if ( p === THREE.SrcColorFactor ) return _gl.SRC_COLOR;
  14232. if ( p === THREE.OneMinusSrcColorFactor ) return _gl.ONE_MINUS_SRC_COLOR;
  14233. if ( p === THREE.SrcAlphaFactor ) return _gl.SRC_ALPHA;
  14234. if ( p === THREE.OneMinusSrcAlphaFactor ) return _gl.ONE_MINUS_SRC_ALPHA;
  14235. if ( p === THREE.DstAlphaFactor ) return _gl.DST_ALPHA;
  14236. if ( p === THREE.OneMinusDstAlphaFactor ) return _gl.ONE_MINUS_DST_ALPHA;
  14237. if ( p === THREE.DstColorFactor ) return _gl.DST_COLOR;
  14238. if ( p === THREE.OneMinusDstColorFactor ) return _gl.ONE_MINUS_DST_COLOR;
  14239. if ( p === THREE.SrcAlphaSaturateFactor ) return _gl.SRC_ALPHA_SATURATE;
  14240. if ( _glExtensionCompressedTextureS3TC !== undefined ) {
  14241. if ( p === THREE.RGB_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT;
  14242. if ( p === THREE.RGBA_S3TC_DXT1_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  14243. if ( p === THREE.RGBA_S3TC_DXT3_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  14244. if ( p === THREE.RGBA_S3TC_DXT5_Format ) return _glExtensionCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  14245. }
  14246. return 0;
  14247. };
  14248. // Allocations
  14249. function allocateBones ( object ) {
  14250. if ( _supportsBoneTextures && object && object.useVertexTexture ) {
  14251. return 1024;
  14252. } else {
  14253. // default for when object is not specified
  14254. // ( for example when prebuilding shader
  14255. // to be used with multiple objects )
  14256. //
  14257. // - leave some extra space for other uniforms
  14258. // - limit here is ANGLE's 254 max uniform vectors
  14259. // (up to 54 should be safe)
  14260. var nVertexUniforms = _gl.getParameter( _gl.MAX_VERTEX_UNIFORM_VECTORS );
  14261. var nVertexMatrices = Math.floor( ( nVertexUniforms - 20 ) / 4 );
  14262. var maxBones = nVertexMatrices;
  14263. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  14264. maxBones = Math.min( object.bones.length, maxBones );
  14265. if ( maxBones < object.bones.length ) {
  14266. console.warn( "WebGLRenderer: too many bones - " + object.bones.length + ", this GPU supports just " + maxBones + " (try OpenGL instead of ANGLE)" );
  14267. }
  14268. }
  14269. return maxBones;
  14270. }
  14271. };
  14272. function allocateLights ( lights ) {
  14273. var l, ll, light, dirLights, pointLights, spotLights, hemiLights;
  14274. dirLights = pointLights = spotLights = hemiLights = 0;
  14275. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  14276. light = lights[ l ];
  14277. if ( light.onlyShadow ) continue;
  14278. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  14279. if ( light instanceof THREE.PointLight ) pointLights ++;
  14280. if ( light instanceof THREE.SpotLight ) spotLights ++;
  14281. if ( light instanceof THREE.HemisphereLight ) hemiLights ++;
  14282. }
  14283. return { 'directional' : dirLights, 'point' : pointLights, 'spot': spotLights, 'hemi': hemiLights };
  14284. };
  14285. function allocateShadows ( lights ) {
  14286. var l, ll, light, maxShadows = 0;
  14287. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  14288. light = lights[ l ];
  14289. if ( ! light.castShadow ) continue;
  14290. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  14291. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  14292. }
  14293. return maxShadows;
  14294. };
  14295. // Initialization
  14296. function initGL () {
  14297. try {
  14298. if ( ! ( _gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  14299. throw 'Error creating WebGL context.';
  14300. }
  14301. } catch ( error ) {
  14302. console.error( error );
  14303. }
  14304. _glExtensionTextureFloat = _gl.getExtension( 'OES_texture_float' );
  14305. _glExtensionStandardDerivatives = _gl.getExtension( 'OES_standard_derivatives' );
  14306. _glExtensionTextureFilterAnisotropic = _gl.getExtension( 'EXT_texture_filter_anisotropic' ) ||
  14307. _gl.getExtension( 'MOZ_EXT_texture_filter_anisotropic' ) ||
  14308. _gl.getExtension( 'WEBKIT_EXT_texture_filter_anisotropic' );
  14309. _glExtensionCompressedTextureS3TC = _gl.getExtension( 'WEBGL_compressed_texture_s3tc' ) ||
  14310. _gl.getExtension( 'MOZ_WEBGL_compressed_texture_s3tc' ) ||
  14311. _gl.getExtension( 'WEBKIT_WEBGL_compressed_texture_s3tc' );
  14312. if ( ! _glExtensionTextureFloat ) {
  14313. console.log( 'THREE.WebGLRenderer: Float textures not supported.' );
  14314. }
  14315. if ( ! _glExtensionStandardDerivatives ) {
  14316. console.log( 'THREE.WebGLRenderer: Standard derivatives not supported.' );
  14317. }
  14318. if ( ! _glExtensionTextureFilterAnisotropic ) {
  14319. console.log( 'THREE.WebGLRenderer: Anisotropic texture filtering not supported.' );
  14320. }
  14321. if ( ! _glExtensionCompressedTextureS3TC ) {
  14322. console.log( 'THREE.WebGLRenderer: S3TC compressed textures not supported.' );
  14323. }
  14324. };
  14325. function setDefaultGLState () {
  14326. _gl.clearColor( 0, 0, 0, 1 );
  14327. _gl.clearDepth( 1 );
  14328. _gl.clearStencil( 0 );
  14329. _gl.enable( _gl.DEPTH_TEST );
  14330. _gl.depthFunc( _gl.LEQUAL );
  14331. _gl.frontFace( _gl.CCW );
  14332. _gl.cullFace( _gl.BACK );
  14333. _gl.enable( _gl.CULL_FACE );
  14334. _gl.enable( _gl.BLEND );
  14335. _gl.blendEquation( _gl.FUNC_ADD );
  14336. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  14337. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  14338. };
  14339. // default plugins (order is important)
  14340. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  14341. this.addPrePlugin( this.shadowMapPlugin );
  14342. this.addPostPlugin( new THREE.SpritePlugin() );
  14343. this.addPostPlugin( new THREE.LensFlarePlugin() );
  14344. };
  14345. /**
  14346. * @author szimek / https://github.com/szimek/
  14347. * @author alteredq / http://alteredqualia.com/
  14348. */
  14349. THREE.WebGLRenderTarget = function ( width, height, options ) {
  14350. this.width = width;
  14351. this.height = height;
  14352. options = options || {};
  14353. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  14354. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  14355. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  14356. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  14357. this.anisotropy = options.anisotropy !== undefined ? options.anisotropy : 1;
  14358. this.offset = new THREE.Vector2( 0, 0 );
  14359. this.repeat = new THREE.Vector2( 1, 1 );
  14360. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  14361. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  14362. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  14363. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  14364. this.generateMipmaps = true;
  14365. };
  14366. THREE.WebGLRenderTarget.prototype.clone = function() {
  14367. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  14368. tmp.wrapS = this.wrapS;
  14369. tmp.wrapT = this.wrapT;
  14370. tmp.magFilter = this.magFilter;
  14371. tmp.minFilter = this.minFilter;
  14372. tmp.anisotropy = this.anisotropy;
  14373. tmp.offset.copy( this.offset );
  14374. tmp.repeat.copy( this.repeat );
  14375. tmp.format = this.format;
  14376. tmp.type = this.type;
  14377. tmp.depthBuffer = this.depthBuffer;
  14378. tmp.stencilBuffer = this.stencilBuffer;
  14379. tmp.generateMipmaps = this.generateMipmaps;
  14380. return tmp;
  14381. };
  14382. /**
  14383. * @author alteredq / http://alteredqualia.com
  14384. */
  14385. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  14386. THREE.WebGLRenderTarget.call( this, width, height, options );
  14387. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  14388. };
  14389. THREE.WebGLRenderTargetCube.prototype = Object.create( THREE.WebGLRenderTarget.prototype );
  14390. /**
  14391. * @author mrdoob / http://mrdoob.com/
  14392. */
  14393. THREE.RenderableVertex = function () {
  14394. this.positionWorld = new THREE.Vector3();
  14395. this.positionScreen = new THREE.Vector4();
  14396. this.visible = true;
  14397. };
  14398. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  14399. this.positionWorld.copy( vertex.positionWorld );
  14400. this.positionScreen.copy( vertex.positionScreen );
  14401. }
  14402. /**
  14403. * @author mrdoob / http://mrdoob.com/
  14404. */
  14405. THREE.RenderableFace3 = function () {
  14406. this.v1 = new THREE.RenderableVertex();
  14407. this.v2 = new THREE.RenderableVertex();
  14408. this.v3 = new THREE.RenderableVertex();
  14409. this.centroidWorld = new THREE.Vector3();
  14410. this.centroidScreen = new THREE.Vector3();
  14411. this.normalWorld = new THREE.Vector3();
  14412. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14413. this.vertexNormalsLength = 0;
  14414. this.color = null;
  14415. this.material = null;
  14416. this.uvs = [[]];
  14417. this.z = null;
  14418. };
  14419. /**
  14420. * @author mrdoob / http://mrdoob.com/
  14421. */
  14422. THREE.RenderableFace4 = function () {
  14423. this.v1 = new THREE.RenderableVertex();
  14424. this.v2 = new THREE.RenderableVertex();
  14425. this.v3 = new THREE.RenderableVertex();
  14426. this.v4 = new THREE.RenderableVertex();
  14427. this.centroidWorld = new THREE.Vector3();
  14428. this.centroidScreen = new THREE.Vector3();
  14429. this.normalWorld = new THREE.Vector3();
  14430. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  14431. this.vertexNormalsLength = 0;
  14432. this.color = null;
  14433. this.material = null;
  14434. this.uvs = [[]];
  14435. this.z = null;
  14436. };
  14437. /**
  14438. * @author mrdoob / http://mrdoob.com/
  14439. */
  14440. THREE.RenderableObject = function () {
  14441. this.object = null;
  14442. this.z = null;
  14443. };
  14444. /**
  14445. * @author mrdoob / http://mrdoob.com/
  14446. */
  14447. THREE.RenderableParticle = function () {
  14448. this.object = null;
  14449. this.x = null;
  14450. this.y = null;
  14451. this.z = null;
  14452. this.rotation = null;
  14453. this.scale = new THREE.Vector2();
  14454. this.material = null;
  14455. };
  14456. /**
  14457. * @author mrdoob / http://mrdoob.com/
  14458. */
  14459. THREE.RenderableLine = function () {
  14460. this.z = null;
  14461. this.v1 = new THREE.RenderableVertex();
  14462. this.v2 = new THREE.RenderableVertex();
  14463. this.material = null;
  14464. };
  14465. /**
  14466. * @author alteredq / http://alteredqualia.com/
  14467. */
  14468. THREE.ColorUtils = {
  14469. adjustHSV : function ( color, h, s, v ) {
  14470. var hsv = THREE.ColorUtils.__hsv;
  14471. color.getHSV( hsv );
  14472. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  14473. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  14474. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  14475. color.setHSV( hsv.h, hsv.s, hsv.v );
  14476. }
  14477. };
  14478. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  14479. * @author mrdoob / http://mrdoob.com/
  14480. * @author alteredq / http://alteredqualia.com/
  14481. */
  14482. THREE.GeometryUtils = {
  14483. // Merge two geometries or geometry and geometry from object (using object's transform)
  14484. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  14485. var matrix, matrixRotation,
  14486. vertexOffset = geometry1.vertices.length,
  14487. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  14488. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  14489. vertices1 = geometry1.vertices,
  14490. vertices2 = geometry2.vertices,
  14491. faces1 = geometry1.faces,
  14492. faces2 = geometry2.faces,
  14493. uvs1 = geometry1.faceVertexUvs[ 0 ],
  14494. uvs2 = geometry2.faceVertexUvs[ 0 ];
  14495. if ( object2 instanceof THREE.Mesh ) {
  14496. object2.matrixAutoUpdate && object2.updateMatrix();
  14497. matrix = object2.matrix;
  14498. matrixRotation = new THREE.Matrix4();
  14499. matrixRotation.extractRotation( matrix, object2.scale );
  14500. }
  14501. // vertices
  14502. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  14503. var vertex = vertices2[ i ];
  14504. var vertexCopy = vertex.clone();
  14505. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  14506. vertices1.push( vertexCopy );
  14507. }
  14508. // faces
  14509. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  14510. var face = faces2[ i ], faceCopy, normal, color,
  14511. faceVertexNormals = face.vertexNormals,
  14512. faceVertexColors = face.vertexColors;
  14513. if ( face instanceof THREE.Face3 ) {
  14514. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  14515. } else if ( face instanceof THREE.Face4 ) {
  14516. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  14517. }
  14518. faceCopy.normal.copy( face.normal );
  14519. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  14520. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  14521. normal = faceVertexNormals[ j ].clone();
  14522. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  14523. faceCopy.vertexNormals.push( normal );
  14524. }
  14525. faceCopy.color.copy( face.color );
  14526. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  14527. color = faceVertexColors[ j ];
  14528. faceCopy.vertexColors.push( color.clone() );
  14529. }
  14530. faceCopy.materialIndex = face.materialIndex;
  14531. faceCopy.centroid.copy( face.centroid );
  14532. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  14533. faces1.push( faceCopy );
  14534. }
  14535. // uvs
  14536. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  14537. var uv = uvs2[ i ], uvCopy = [];
  14538. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  14539. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  14540. }
  14541. uvs1.push( uvCopy );
  14542. }
  14543. },
  14544. removeMaterials: function ( geometry, materialIndexArray ) {
  14545. var materialIndexMap = {};
  14546. for ( var i = 0, il = materialIndexArray.length; i < il; i ++ ) {
  14547. materialIndexMap[ materialIndexArray[i] ] = true;
  14548. }
  14549. var face, newFaces = [];
  14550. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14551. face = geometry.faces[ i ];
  14552. if ( ! ( face.materialIndex in materialIndexMap ) ) newFaces.push( face );
  14553. }
  14554. geometry.faces = newFaces;
  14555. },
  14556. // Get random point in triangle (via barycentric coordinates)
  14557. // (uniform distribution)
  14558. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  14559. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  14560. var a, b, c,
  14561. point = new THREE.Vector3(),
  14562. tmp = THREE.GeometryUtils.__v1;
  14563. a = THREE.GeometryUtils.random();
  14564. b = THREE.GeometryUtils.random();
  14565. if ( ( a + b ) > 1 ) {
  14566. a = 1 - a;
  14567. b = 1 - b;
  14568. }
  14569. c = 1 - a - b;
  14570. point.copy( vectorA );
  14571. point.multiplyScalar( a );
  14572. tmp.copy( vectorB );
  14573. tmp.multiplyScalar( b );
  14574. point.addSelf( tmp );
  14575. tmp.copy( vectorC );
  14576. tmp.multiplyScalar( c );
  14577. point.addSelf( tmp );
  14578. return point;
  14579. },
  14580. // Get random point in face (triangle / quad)
  14581. // (uniform distribution)
  14582. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  14583. var vA, vB, vC, vD;
  14584. if ( face instanceof THREE.Face3 ) {
  14585. vA = geometry.vertices[ face.a ];
  14586. vB = geometry.vertices[ face.b ];
  14587. vC = geometry.vertices[ face.c ];
  14588. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  14589. } else if ( face instanceof THREE.Face4 ) {
  14590. vA = geometry.vertices[ face.a ];
  14591. vB = geometry.vertices[ face.b ];
  14592. vC = geometry.vertices[ face.c ];
  14593. vD = geometry.vertices[ face.d ];
  14594. var area1, area2;
  14595. if ( useCachedAreas ) {
  14596. if ( face._area1 && face._area2 ) {
  14597. area1 = face._area1;
  14598. area2 = face._area2;
  14599. } else {
  14600. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14601. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14602. face._area1 = area1;
  14603. face._area2 = area2;
  14604. }
  14605. } else {
  14606. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  14607. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14608. }
  14609. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  14610. if ( r < area1 ) {
  14611. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  14612. } else {
  14613. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  14614. }
  14615. }
  14616. },
  14617. // Get uniformly distributed random points in mesh
  14618. // - create array with cumulative sums of face areas
  14619. // - pick random number from 0 to total area
  14620. // - find corresponding place in area array by binary search
  14621. // - get random point in face
  14622. randomPointsInGeometry: function ( geometry, n ) {
  14623. var face, i,
  14624. faces = geometry.faces,
  14625. vertices = geometry.vertices,
  14626. il = faces.length,
  14627. totalArea = 0,
  14628. cumulativeAreas = [],
  14629. vA, vB, vC, vD;
  14630. // precompute face areas
  14631. for ( i = 0; i < il; i ++ ) {
  14632. face = faces[ i ];
  14633. if ( face instanceof THREE.Face3 ) {
  14634. vA = vertices[ face.a ];
  14635. vB = vertices[ face.b ];
  14636. vC = vertices[ face.c ];
  14637. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  14638. } else if ( face instanceof THREE.Face4 ) {
  14639. vA = vertices[ face.a ];
  14640. vB = vertices[ face.b ];
  14641. vC = vertices[ face.c ];
  14642. vD = vertices[ face.d ];
  14643. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  14644. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  14645. face._area = face._area1 + face._area2;
  14646. }
  14647. totalArea += face._area;
  14648. cumulativeAreas[ i ] = totalArea;
  14649. }
  14650. // binary search cumulative areas array
  14651. function binarySearchIndices( value ) {
  14652. function binarySearch( start, end ) {
  14653. // return closest larger index
  14654. // if exact number is not found
  14655. if ( end < start )
  14656. return start;
  14657. var mid = start + Math.floor( ( end - start ) / 2 );
  14658. if ( cumulativeAreas[ mid ] > value ) {
  14659. return binarySearch( start, mid - 1 );
  14660. } else if ( cumulativeAreas[ mid ] < value ) {
  14661. return binarySearch( mid + 1, end );
  14662. } else {
  14663. return mid;
  14664. }
  14665. }
  14666. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  14667. return result;
  14668. }
  14669. // pick random face weighted by face area
  14670. var r, index,
  14671. result = [];
  14672. var stats = {};
  14673. for ( i = 0; i < n; i ++ ) {
  14674. r = THREE.GeometryUtils.random() * totalArea;
  14675. index = binarySearchIndices( r );
  14676. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  14677. if ( ! stats[ index ] ) {
  14678. stats[ index ] = 1;
  14679. } else {
  14680. stats[ index ] += 1;
  14681. }
  14682. }
  14683. return result;
  14684. },
  14685. // Get triangle area (half of parallelogram)
  14686. // http://mathworld.wolfram.com/TriangleArea.html
  14687. triangleArea: function ( vectorA, vectorB, vectorC ) {
  14688. var tmp1 = THREE.GeometryUtils.__v1,
  14689. tmp2 = THREE.GeometryUtils.__v2;
  14690. tmp1.sub( vectorB, vectorA );
  14691. tmp2.sub( vectorC, vectorA );
  14692. tmp1.crossSelf( tmp2 );
  14693. return 0.5 * tmp1.length();
  14694. },
  14695. // Center geometry so that 0,0,0 is in center of bounding box
  14696. center: function ( geometry ) {
  14697. geometry.computeBoundingBox();
  14698. var bb = geometry.boundingBox;
  14699. var offset = new THREE.Vector3();
  14700. offset.add( bb.min, bb.max );
  14701. offset.multiplyScalar( -0.5 );
  14702. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  14703. geometry.computeBoundingBox();
  14704. return offset;
  14705. },
  14706. // Normalize UVs to be from <0,1>
  14707. // (for now just the first set of UVs)
  14708. normalizeUVs: function ( geometry ) {
  14709. var uvSet = geometry.faceVertexUvs[ 0 ];
  14710. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  14711. var uvs = uvSet[ i ];
  14712. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  14713. // texture repeat
  14714. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  14715. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  14716. }
  14717. }
  14718. },
  14719. triangulateQuads: function ( geometry ) {
  14720. var i, il, j, jl;
  14721. var faces = [];
  14722. var faceUvs = [];
  14723. var faceVertexUvs = [];
  14724. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  14725. faceUvs[ i ] = [];
  14726. }
  14727. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14728. faceVertexUvs[ i ] = [];
  14729. }
  14730. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14731. var face = geometry.faces[ i ];
  14732. if ( face instanceof THREE.Face4 ) {
  14733. var a = face.a;
  14734. var b = face.b;
  14735. var c = face.c;
  14736. var d = face.d;
  14737. var triA = new THREE.Face3();
  14738. var triB = new THREE.Face3();
  14739. triA.color.copy( face.color );
  14740. triB.color.copy( face.color );
  14741. triA.materialIndex = face.materialIndex;
  14742. triB.materialIndex = face.materialIndex;
  14743. triA.a = a;
  14744. triA.b = b;
  14745. triA.c = d;
  14746. triB.a = b;
  14747. triB.b = c;
  14748. triB.c = d;
  14749. if ( face.vertexColors.length === 4 ) {
  14750. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  14751. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  14752. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14753. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  14754. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  14755. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  14756. }
  14757. faces.push( triA, triB );
  14758. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14759. if ( geometry.faceVertexUvs[ j ].length ) {
  14760. var uvs = geometry.faceVertexUvs[ j ][ i ];
  14761. var uvA = uvs[ 0 ];
  14762. var uvB = uvs[ 1 ];
  14763. var uvC = uvs[ 2 ];
  14764. var uvD = uvs[ 3 ];
  14765. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  14766. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  14767. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14768. }
  14769. }
  14770. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14771. if ( geometry.faceUvs[ j ].length ) {
  14772. var faceUv = geometry.faceUvs[ j ][ i ];
  14773. faceUvs[ j ].push( faceUv, faceUv );
  14774. }
  14775. }
  14776. } else {
  14777. faces.push( face );
  14778. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  14779. faceUvs[ j ].push( geometry.faceUvs[ j ][ i ] );
  14780. }
  14781. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14782. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14783. }
  14784. }
  14785. }
  14786. geometry.faces = faces;
  14787. geometry.faceUvs = faceUvs;
  14788. geometry.faceVertexUvs = faceVertexUvs;
  14789. geometry.computeCentroids();
  14790. geometry.computeFaceNormals();
  14791. geometry.computeVertexNormals();
  14792. if ( geometry.hasTangents ) geometry.computeTangents();
  14793. },
  14794. // Make all faces use unique vertices
  14795. // so that each face can be separated from others
  14796. explode: function( geometry ) {
  14797. var vertices = [];
  14798. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14799. var n = vertices.length;
  14800. var face = geometry.faces[ i ];
  14801. if ( face instanceof THREE.Face4 ) {
  14802. var a = face.a;
  14803. var b = face.b;
  14804. var c = face.c;
  14805. var d = face.d;
  14806. var va = geometry.vertices[ a ];
  14807. var vb = geometry.vertices[ b ];
  14808. var vc = geometry.vertices[ c ];
  14809. var vd = geometry.vertices[ d ];
  14810. vertices.push( va.clone() );
  14811. vertices.push( vb.clone() );
  14812. vertices.push( vc.clone() );
  14813. vertices.push( vd.clone() );
  14814. face.a = n;
  14815. face.b = n + 1;
  14816. face.c = n + 2;
  14817. face.d = n + 3;
  14818. } else {
  14819. var a = face.a;
  14820. var b = face.b;
  14821. var c = face.c;
  14822. var va = geometry.vertices[ a ];
  14823. var vb = geometry.vertices[ b ];
  14824. var vc = geometry.vertices[ c ];
  14825. vertices.push( va.clone() );
  14826. vertices.push( vb.clone() );
  14827. vertices.push( vc.clone() );
  14828. face.a = n;
  14829. face.b = n + 1;
  14830. face.c = n + 2;
  14831. }
  14832. }
  14833. geometry.vertices = vertices;
  14834. delete geometry.__tmpVertices;
  14835. },
  14836. // Break faces with edges longer than maxEdgeLength
  14837. // - not recursive
  14838. tessellate: function ( geometry, maxEdgeLength ) {
  14839. var i, il, face,
  14840. a, b, c, d,
  14841. va, vb, vc, vd,
  14842. dab, dbc, dac, dcd, dad,
  14843. m, m1, m2,
  14844. vm, vm1, vm2,
  14845. vnm, vnm1, vnm2,
  14846. vcm, vcm1, vcm2,
  14847. triA, triB,
  14848. quadA, quadB,
  14849. edge;
  14850. var faces = [];
  14851. var faceVertexUvs = [];
  14852. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  14853. faceVertexUvs[ i ] = [];
  14854. }
  14855. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  14856. face = geometry.faces[ i ];
  14857. if ( face instanceof THREE.Face3 ) {
  14858. a = face.a;
  14859. b = face.b;
  14860. c = face.c;
  14861. va = geometry.vertices[ a ];
  14862. vb = geometry.vertices[ b ];
  14863. vc = geometry.vertices[ c ];
  14864. dab = va.distanceTo( vb );
  14865. dbc = vb.distanceTo( vc );
  14866. dac = va.distanceTo( vc );
  14867. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  14868. m = geometry.vertices.length;
  14869. triA = face.clone();
  14870. triB = face.clone();
  14871. if ( dab >= dbc && dab >= dac ) {
  14872. vm = va.clone();
  14873. vm.lerpSelf( vb, 0.5 );
  14874. triA.a = a;
  14875. triA.b = m;
  14876. triA.c = c;
  14877. triB.a = m;
  14878. triB.b = b;
  14879. triB.c = c;
  14880. if ( face.vertexNormals.length === 3 ) {
  14881. vnm = face.vertexNormals[ 0 ].clone();
  14882. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  14883. triA.vertexNormals[ 1 ].copy( vnm );
  14884. triB.vertexNormals[ 0 ].copy( vnm );
  14885. }
  14886. if ( face.vertexColors.length === 3 ) {
  14887. vcm = face.vertexColors[ 0 ].clone();
  14888. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  14889. triA.vertexColors[ 1 ].copy( vcm );
  14890. triB.vertexColors[ 0 ].copy( vcm );
  14891. }
  14892. edge = 0;
  14893. } else if ( dbc >= dab && dbc >= dac ) {
  14894. vm = vb.clone();
  14895. vm.lerpSelf( vc, 0.5 );
  14896. triA.a = a;
  14897. triA.b = b;
  14898. triA.c = m;
  14899. triB.a = m;
  14900. triB.b = c;
  14901. triB.c = a;
  14902. if ( face.vertexNormals.length === 3 ) {
  14903. vnm = face.vertexNormals[ 1 ].clone();
  14904. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14905. triA.vertexNormals[ 2 ].copy( vnm );
  14906. triB.vertexNormals[ 0 ].copy( vnm );
  14907. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  14908. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  14909. }
  14910. if ( face.vertexColors.length === 3 ) {
  14911. vcm = face.vertexColors[ 1 ].clone();
  14912. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14913. triA.vertexColors[ 2 ].copy( vcm );
  14914. triB.vertexColors[ 0 ].copy( vcm );
  14915. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  14916. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  14917. }
  14918. edge = 1;
  14919. } else {
  14920. vm = va.clone();
  14921. vm.lerpSelf( vc, 0.5 );
  14922. triA.a = a;
  14923. triA.b = b;
  14924. triA.c = m;
  14925. triB.a = m;
  14926. triB.b = b;
  14927. triB.c = c;
  14928. if ( face.vertexNormals.length === 3 ) {
  14929. vnm = face.vertexNormals[ 0 ].clone();
  14930. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  14931. triA.vertexNormals[ 2 ].copy( vnm );
  14932. triB.vertexNormals[ 0 ].copy( vnm );
  14933. }
  14934. if ( face.vertexColors.length === 3 ) {
  14935. vcm = face.vertexColors[ 0 ].clone();
  14936. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  14937. triA.vertexColors[ 2 ].copy( vcm );
  14938. triB.vertexColors[ 0 ].copy( vcm );
  14939. }
  14940. edge = 2;
  14941. }
  14942. faces.push( triA, triB );
  14943. geometry.vertices.push( vm );
  14944. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  14945. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14946. if ( geometry.faceVertexUvs[ j ].length ) {
  14947. uvs = geometry.faceVertexUvs[ j ][ i ];
  14948. uvA = uvs[ 0 ];
  14949. uvB = uvs[ 1 ];
  14950. uvC = uvs[ 2 ];
  14951. // AB
  14952. if ( edge === 0 ) {
  14953. uvM = uvA.clone();
  14954. uvM.lerpSelf( uvB, 0.5 );
  14955. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  14956. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14957. // BC
  14958. } else if ( edge === 1 ) {
  14959. uvM = uvB.clone();
  14960. uvM.lerpSelf( uvC, 0.5 );
  14961. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14962. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  14963. // AC
  14964. } else {
  14965. uvM = uvA.clone();
  14966. uvM.lerpSelf( uvC, 0.5 );
  14967. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  14968. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  14969. }
  14970. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  14971. }
  14972. }
  14973. } else {
  14974. faces.push( face );
  14975. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  14976. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  14977. }
  14978. }
  14979. } else {
  14980. a = face.a;
  14981. b = face.b;
  14982. c = face.c;
  14983. d = face.d;
  14984. va = geometry.vertices[ a ];
  14985. vb = geometry.vertices[ b ];
  14986. vc = geometry.vertices[ c ];
  14987. vd = geometry.vertices[ d ];
  14988. dab = va.distanceTo( vb );
  14989. dbc = vb.distanceTo( vc );
  14990. dcd = vc.distanceTo( vd );
  14991. dad = va.distanceTo( vd );
  14992. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  14993. m1 = geometry.vertices.length;
  14994. m2 = geometry.vertices.length + 1;
  14995. quadA = face.clone();
  14996. quadB = face.clone();
  14997. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  14998. vm1 = va.clone();
  14999. vm1.lerpSelf( vb, 0.5 );
  15000. vm2 = vc.clone();
  15001. vm2.lerpSelf( vd, 0.5 );
  15002. quadA.a = a;
  15003. quadA.b = m1;
  15004. quadA.c = m2;
  15005. quadA.d = d;
  15006. quadB.a = m1;
  15007. quadB.b = b;
  15008. quadB.c = c;
  15009. quadB.d = m2;
  15010. if ( face.vertexNormals.length === 4 ) {
  15011. vnm1 = face.vertexNormals[ 0 ].clone();
  15012. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  15013. vnm2 = face.vertexNormals[ 2 ].clone();
  15014. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  15015. quadA.vertexNormals[ 1 ].copy( vnm1 );
  15016. quadA.vertexNormals[ 2 ].copy( vnm2 );
  15017. quadB.vertexNormals[ 0 ].copy( vnm1 );
  15018. quadB.vertexNormals[ 3 ].copy( vnm2 );
  15019. }
  15020. if ( face.vertexColors.length === 4 ) {
  15021. vcm1 = face.vertexColors[ 0 ].clone();
  15022. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  15023. vcm2 = face.vertexColors[ 2 ].clone();
  15024. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  15025. quadA.vertexColors[ 1 ].copy( vcm1 );
  15026. quadA.vertexColors[ 2 ].copy( vcm2 );
  15027. quadB.vertexColors[ 0 ].copy( vcm1 );
  15028. quadB.vertexColors[ 3 ].copy( vcm2 );
  15029. }
  15030. edge = 0;
  15031. } else {
  15032. vm1 = vb.clone();
  15033. vm1.lerpSelf( vc, 0.5 );
  15034. vm2 = vd.clone();
  15035. vm2.lerpSelf( va, 0.5 );
  15036. quadA.a = a;
  15037. quadA.b = b;
  15038. quadA.c = m1;
  15039. quadA.d = m2;
  15040. quadB.a = m2;
  15041. quadB.b = m1;
  15042. quadB.c = c;
  15043. quadB.d = d;
  15044. if ( face.vertexNormals.length === 4 ) {
  15045. vnm1 = face.vertexNormals[ 1 ].clone();
  15046. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  15047. vnm2 = face.vertexNormals[ 3 ].clone();
  15048. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  15049. quadA.vertexNormals[ 2 ].copy( vnm1 );
  15050. quadA.vertexNormals[ 3 ].copy( vnm2 );
  15051. quadB.vertexNormals[ 0 ].copy( vnm2 );
  15052. quadB.vertexNormals[ 1 ].copy( vnm1 );
  15053. }
  15054. if ( face.vertexColors.length === 4 ) {
  15055. vcm1 = face.vertexColors[ 1 ].clone();
  15056. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  15057. vcm2 = face.vertexColors[ 3 ].clone();
  15058. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  15059. quadA.vertexColors[ 2 ].copy( vcm1 );
  15060. quadA.vertexColors[ 3 ].copy( vcm2 );
  15061. quadB.vertexColors[ 0 ].copy( vcm2 );
  15062. quadB.vertexColors[ 1 ].copy( vcm1 );
  15063. }
  15064. edge = 1;
  15065. }
  15066. faces.push( quadA, quadB );
  15067. geometry.vertices.push( vm1, vm2 );
  15068. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  15069. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15070. if ( geometry.faceVertexUvs[ j ].length ) {
  15071. uvs = geometry.faceVertexUvs[ j ][ i ];
  15072. uvA = uvs[ 0 ];
  15073. uvB = uvs[ 1 ];
  15074. uvC = uvs[ 2 ];
  15075. uvD = uvs[ 3 ];
  15076. // AB + CD
  15077. if ( edge === 0 ) {
  15078. uvM1 = uvA.clone();
  15079. uvM1.lerpSelf( uvB, 0.5 );
  15080. uvM2 = uvC.clone();
  15081. uvM2.lerpSelf( uvD, 0.5 );
  15082. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  15083. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  15084. // BC + AD
  15085. } else {
  15086. uvM1 = uvB.clone();
  15087. uvM1.lerpSelf( uvC, 0.5 );
  15088. uvM2 = uvD.clone();
  15089. uvM2.lerpSelf( uvA, 0.5 );
  15090. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  15091. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  15092. }
  15093. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  15094. }
  15095. }
  15096. } else {
  15097. faces.push( face );
  15098. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  15099. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  15100. }
  15101. }
  15102. }
  15103. }
  15104. geometry.faces = faces;
  15105. geometry.faceVertexUvs = faceVertexUvs;
  15106. }
  15107. };
  15108. THREE.GeometryUtils.random = THREE.Math.random16;
  15109. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  15110. THREE.GeometryUtils.__v2 = new THREE.Vector3();
  15111. /**
  15112. * @author alteredq / http://alteredqualia.com/
  15113. * @author mrdoob / http://mrdoob.com/
  15114. */
  15115. THREE.ImageUtils = {
  15116. crossOrigin: 'anonymous',
  15117. loadTexture: function ( url, mapping, onLoad, onError ) {
  15118. var image = new Image();
  15119. var texture = new THREE.Texture( image, mapping );
  15120. var loader = new THREE.ImageLoader();
  15121. loader.addEventListener( 'load', function ( event ) {
  15122. texture.image = event.content;
  15123. texture.needsUpdate = true;
  15124. if ( onLoad ) onLoad( texture );
  15125. } );
  15126. loader.addEventListener( 'error', function ( event ) {
  15127. if ( onError ) onError( event.message );
  15128. } );
  15129. loader.crossOrigin = this.crossOrigin;
  15130. loader.load( url, image );
  15131. texture.sourceFile = url;
  15132. return texture;
  15133. },
  15134. loadCompressedTexture: function ( url, mapping, onLoad, onError ) {
  15135. var texture = new THREE.CompressedTexture();
  15136. texture.mapping = mapping;
  15137. var request = new XMLHttpRequest();
  15138. request.onload = function () {
  15139. var buffer = request.response;
  15140. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15141. texture.format = dds.format;
  15142. texture.mipmaps = dds.mipmaps;
  15143. texture.image.width = dds.width;
  15144. texture.image.height = dds.height;
  15145. // gl.generateMipmap fails for compressed textures
  15146. // mipmaps must be embedded in the DDS file
  15147. // or texture filters must not use mipmapping
  15148. texture.generateMipmaps = false;
  15149. texture.needsUpdate = true;
  15150. if ( onLoad ) onLoad( texture );
  15151. }
  15152. request.onerror = onError;
  15153. request.open( 'GET', url, true );
  15154. request.responseType = "arraybuffer";
  15155. request.send( null );
  15156. return texture;
  15157. },
  15158. loadTextureCube: function ( array, mapping, onLoad, onError ) {
  15159. var images = [];
  15160. images.loadCount = 0;
  15161. var texture = new THREE.Texture();
  15162. texture.image = images;
  15163. if ( mapping !== undefined ) texture.mapping = mapping;
  15164. // no flipping needed for cube textures
  15165. texture.flipY = false;
  15166. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15167. var cubeImage = new Image();
  15168. images[ i ] = cubeImage;
  15169. cubeImage.onload = function () {
  15170. images.loadCount += 1;
  15171. if ( images.loadCount === 6 ) {
  15172. texture.needsUpdate = true;
  15173. if ( onLoad ) onLoad( texture );
  15174. }
  15175. };
  15176. cubeImage.onerror = onError;
  15177. cubeImage.crossOrigin = this.crossOrigin;
  15178. cubeImage.src = array[ i ];
  15179. }
  15180. return texture;
  15181. },
  15182. loadCompressedTextureCube: function ( array, mapping, onLoad, onError ) {
  15183. var images = [];
  15184. images.loadCount = 0;
  15185. var texture = new THREE.CompressedTexture();
  15186. texture.image = images;
  15187. if ( mapping !== undefined ) texture.mapping = mapping;
  15188. // no flipping for cube textures
  15189. // (also flipping doesn't work for compressed textures )
  15190. texture.flipY = false;
  15191. // can't generate mipmaps for compressed textures
  15192. // mips must be embedded in DDS files
  15193. texture.generateMipmaps = false;
  15194. var generateCubeFaceCallback = function ( rq, img ) {
  15195. return function () {
  15196. var buffer = rq.response;
  15197. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15198. img.format = dds.format;
  15199. img.mipmaps = dds.mipmaps;
  15200. img.width = dds.width;
  15201. img.height = dds.height;
  15202. images.loadCount += 1;
  15203. if ( images.loadCount === 6 ) {
  15204. texture.format = dds.format;
  15205. texture.needsUpdate = true;
  15206. if ( onLoad ) onLoad( texture );
  15207. }
  15208. }
  15209. }
  15210. // compressed cubemap textures as 6 separate DDS files
  15211. if ( array instanceof Array ) {
  15212. for ( var i = 0, il = array.length; i < il; ++ i ) {
  15213. var cubeImage = {};
  15214. images[ i ] = cubeImage;
  15215. var request = new XMLHttpRequest();
  15216. request.onload = generateCubeFaceCallback( request, cubeImage );
  15217. request.onerror = onError;
  15218. var url = array[ i ];
  15219. request.open( 'GET', url, true );
  15220. request.responseType = "arraybuffer";
  15221. request.send( null );
  15222. }
  15223. // compressed cubemap texture stored in a single DDS file
  15224. } else {
  15225. var url = array;
  15226. var request = new XMLHttpRequest();
  15227. request.onload = function( ) {
  15228. var buffer = request.response;
  15229. var dds = THREE.ImageUtils.parseDDS( buffer, true );
  15230. if ( dds.isCubemap ) {
  15231. var faces = dds.mipmaps.length / dds.mipmapCount;
  15232. for ( var f = 0; f < faces; f ++ ) {
  15233. images[ f ] = { mipmaps : [] };
  15234. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15235. images[ f ].mipmaps.push( dds.mipmaps[ f * dds.mipmapCount + i ] );
  15236. images[ f ].format = dds.format;
  15237. images[ f ].width = dds.width;
  15238. images[ f ].height = dds.height;
  15239. }
  15240. }
  15241. texture.format = dds.format;
  15242. texture.needsUpdate = true;
  15243. if ( onLoad ) onLoad( texture );
  15244. }
  15245. }
  15246. request.onerror = onError;
  15247. request.open( 'GET', url, true );
  15248. request.responseType = "arraybuffer";
  15249. request.send( null );
  15250. }
  15251. return texture;
  15252. },
  15253. parseDDS: function ( buffer, loadMipmaps ) {
  15254. var dds = { mipmaps: [], width: 0, height: 0, format: null, mipmapCount: 1 };
  15255. // Adapted from @toji's DDS utils
  15256. // https://github.com/toji/webgl-texture-utils/blob/master/texture-util/dds.js
  15257. // All values and structures referenced from:
  15258. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  15259. var DDS_MAGIC = 0x20534444;
  15260. var DDSD_CAPS = 0x1,
  15261. DDSD_HEIGHT = 0x2,
  15262. DDSD_WIDTH = 0x4,
  15263. DDSD_PITCH = 0x8,
  15264. DDSD_PIXELFORMAT = 0x1000,
  15265. DDSD_MIPMAPCOUNT = 0x20000,
  15266. DDSD_LINEARSIZE = 0x80000,
  15267. DDSD_DEPTH = 0x800000;
  15268. var DDSCAPS_COMPLEX = 0x8,
  15269. DDSCAPS_MIPMAP = 0x400000,
  15270. DDSCAPS_TEXTURE = 0x1000;
  15271. var DDSCAPS2_CUBEMAP = 0x200,
  15272. DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  15273. DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  15274. DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  15275. DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  15276. DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  15277. DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  15278. DDSCAPS2_VOLUME = 0x200000;
  15279. var DDPF_ALPHAPIXELS = 0x1,
  15280. DDPF_ALPHA = 0x2,
  15281. DDPF_FOURCC = 0x4,
  15282. DDPF_RGB = 0x40,
  15283. DDPF_YUV = 0x200,
  15284. DDPF_LUMINANCE = 0x20000;
  15285. function fourCCToInt32( value ) {
  15286. return value.charCodeAt(0) +
  15287. (value.charCodeAt(1) << 8) +
  15288. (value.charCodeAt(2) << 16) +
  15289. (value.charCodeAt(3) << 24);
  15290. }
  15291. function int32ToFourCC( value ) {
  15292. return String.fromCharCode(
  15293. value & 0xff,
  15294. (value >> 8) & 0xff,
  15295. (value >> 16) & 0xff,
  15296. (value >> 24) & 0xff
  15297. );
  15298. }
  15299. var FOURCC_DXT1 = fourCCToInt32("DXT1");
  15300. var FOURCC_DXT3 = fourCCToInt32("DXT3");
  15301. var FOURCC_DXT5 = fourCCToInt32("DXT5");
  15302. var headerLengthInt = 31; // The header length in 32 bit ints
  15303. // Offsets into the header array
  15304. var off_magic = 0;
  15305. var off_size = 1;
  15306. var off_flags = 2;
  15307. var off_height = 3;
  15308. var off_width = 4;
  15309. var off_mipmapCount = 7;
  15310. var off_pfFlags = 20;
  15311. var off_pfFourCC = 21;
  15312. var off_caps = 27;
  15313. var off_caps2 = 28;
  15314. var off_caps3 = 29;
  15315. var off_caps4 = 30;
  15316. // Parse header
  15317. var header = new Int32Array( buffer, 0, headerLengthInt );
  15318. if ( header[ off_magic ] !== DDS_MAGIC ) {
  15319. console.error( "ImageUtils.parseDDS(): Invalid magic number in DDS header" );
  15320. return dds;
  15321. }
  15322. if ( ! header[ off_pfFlags ] & DDPF_FOURCC ) {
  15323. console.error( "ImageUtils.parseDDS(): Unsupported format, must contain a FourCC code" );
  15324. return dds;
  15325. }
  15326. var blockBytes;
  15327. var fourCC = header[ off_pfFourCC ];
  15328. switch ( fourCC ) {
  15329. case FOURCC_DXT1:
  15330. blockBytes = 8;
  15331. dds.format = THREE.RGB_S3TC_DXT1_Format;
  15332. break;
  15333. case FOURCC_DXT3:
  15334. blockBytes = 16;
  15335. dds.format = THREE.RGBA_S3TC_DXT3_Format;
  15336. break;
  15337. case FOURCC_DXT5:
  15338. blockBytes = 16;
  15339. dds.format = THREE.RGBA_S3TC_DXT5_Format;
  15340. break;
  15341. default:
  15342. console.error( "ImageUtils.parseDDS(): Unsupported FourCC code: ", int32ToFourCC( fourCC ) );
  15343. return dds;
  15344. }
  15345. dds.mipmapCount = 1;
  15346. if ( header[ off_flags ] & DDSD_MIPMAPCOUNT && loadMipmaps !== false ) {
  15347. dds.mipmapCount = Math.max( 1, header[ off_mipmapCount ] );
  15348. }
  15349. //TODO: Verify that all faces of the cubemap are present with DDSCAPS2_CUBEMAP_POSITIVEX, etc.
  15350. dds.isCubemap = header[ off_caps2 ] & DDSCAPS2_CUBEMAP ? true : false;
  15351. dds.width = header[ off_width ];
  15352. dds.height = header[ off_height ];
  15353. var dataOffset = header[ off_size ] + 4;
  15354. // Extract mipmaps buffers
  15355. var width = dds.width;
  15356. var height = dds.height;
  15357. var faces = dds.isCubemap ? 6 : 1;
  15358. for ( var face = 0; face < faces; face ++ ) {
  15359. for ( var i = 0; i < dds.mipmapCount; i ++ ) {
  15360. var dataLength = Math.max( 4, width ) / 4 * Math.max( 4, height ) / 4 * blockBytes;
  15361. var byteArray = new Uint8Array( buffer, dataOffset, dataLength );
  15362. var mipmap = { "data": byteArray, "width": width, "height": height };
  15363. dds.mipmaps.push( mipmap );
  15364. dataOffset += dataLength;
  15365. width = Math.max( width * 0.5, 1 );
  15366. height = Math.max( height * 0.5, 1 );
  15367. }
  15368. width = dds.width;
  15369. height = dds.height;
  15370. }
  15371. return dds;
  15372. },
  15373. getNormalMap: function ( image, depth ) {
  15374. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  15375. var cross = function ( a, b ) {
  15376. 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 ] ];
  15377. }
  15378. var subtract = function ( a, b ) {
  15379. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  15380. }
  15381. var normalize = function ( a ) {
  15382. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  15383. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  15384. }
  15385. depth = depth | 1;
  15386. var width = image.width;
  15387. var height = image.height;
  15388. var canvas = document.createElement( 'canvas' );
  15389. canvas.width = width;
  15390. canvas.height = height;
  15391. var context = canvas.getContext( '2d' );
  15392. context.drawImage( image, 0, 0 );
  15393. var data = context.getImageData( 0, 0, width, height ).data;
  15394. var imageData = context.createImageData( width, height );
  15395. var output = imageData.data;
  15396. for ( var x = 0; x < width; x ++ ) {
  15397. for ( var y = 0; y < height; y ++ ) {
  15398. var ly = y - 1 < 0 ? 0 : y - 1;
  15399. var uy = y + 1 > height - 1 ? height - 1 : y + 1;
  15400. var lx = x - 1 < 0 ? 0 : x - 1;
  15401. var ux = x + 1 > width - 1 ? width - 1 : x + 1;
  15402. var points = [];
  15403. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  15404. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  15405. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  15406. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  15407. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  15408. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  15409. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  15410. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  15411. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  15412. var normals = [];
  15413. var num_points = points.length;
  15414. for ( var i = 0; i < num_points; i ++ ) {
  15415. var v1 = points[ i ];
  15416. var v2 = points[ ( i + 1 ) % num_points ];
  15417. v1 = subtract( v1, origin );
  15418. v2 = subtract( v2, origin );
  15419. normals.push( normalize( cross( v1, v2 ) ) );
  15420. }
  15421. var normal = [ 0, 0, 0 ];
  15422. for ( var i = 0; i < normals.length; i ++ ) {
  15423. normal[ 0 ] += normals[ i ][ 0 ];
  15424. normal[ 1 ] += normals[ i ][ 1 ];
  15425. normal[ 2 ] += normals[ i ][ 2 ];
  15426. }
  15427. normal[ 0 ] /= normals.length;
  15428. normal[ 1 ] /= normals.length;
  15429. normal[ 2 ] /= normals.length;
  15430. var idx = ( y * width + x ) * 4;
  15431. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15432. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 ) / 2.0 * 255 ) | 0;
  15433. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  15434. output[ idx + 3 ] = 255;
  15435. }
  15436. }
  15437. context.putImageData( imageData, 0, 0 );
  15438. return canvas;
  15439. },
  15440. generateDataTexture: function ( width, height, color ) {
  15441. var size = width * height;
  15442. var data = new Uint8Array( 3 * size );
  15443. var r = Math.floor( color.r * 255 );
  15444. var g = Math.floor( color.g * 255 );
  15445. var b = Math.floor( color.b * 255 );
  15446. for ( var i = 0; i < size; i ++ ) {
  15447. data[ i * 3 ] = r;
  15448. data[ i * 3 + 1 ] = g;
  15449. data[ i * 3 + 2 ] = b;
  15450. }
  15451. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  15452. texture.needsUpdate = true;
  15453. return texture;
  15454. }
  15455. };
  15456. /**
  15457. * @author alteredq / http://alteredqualia.com/
  15458. */
  15459. THREE.SceneUtils = {
  15460. createMultiMaterialObject: function ( geometry, materials ) {
  15461. var group = new THREE.Object3D();
  15462. for ( var i = 0, l = materials.length; i < l; i ++ ) {
  15463. group.add( new THREE.Mesh( geometry, materials[ i ] ) );
  15464. }
  15465. return group;
  15466. },
  15467. detach : function ( child, parent, scene ) {
  15468. child.applyMatrix( parent.matrixWorld );
  15469. parent.remove( child );
  15470. scene.add( child );
  15471. },
  15472. attach: function ( child, scene, parent ) {
  15473. var matrixWorldInverse = new THREE.Matrix4();
  15474. matrixWorldInverse.getInverse( parent.matrixWorld );
  15475. child.applyMatrix( matrixWorldInverse );
  15476. scene.remove( child );
  15477. parent.add( child );
  15478. }
  15479. };
  15480. /**
  15481. * @author alteredq / http://alteredqualia.com/
  15482. * @author mrdoob / http://mrdoob.com/
  15483. *
  15484. * ShaderUtils currently contains:
  15485. *
  15486. * fresnel
  15487. * normal
  15488. * cube
  15489. *
  15490. */
  15491. THREE.ShaderUtils = {
  15492. lib: {
  15493. /* -------------------------------------------------------------------------
  15494. // Fresnel shader
  15495. // - based on Nvidia Cg tutorial
  15496. ------------------------------------------------------------------------- */
  15497. 'fresnel': {
  15498. uniforms: {
  15499. "mRefractionRatio": { type: "f", value: 1.02 },
  15500. "mFresnelBias": { type: "f", value: 0.1 },
  15501. "mFresnelPower": { type: "f", value: 2.0 },
  15502. "mFresnelScale": { type: "f", value: 1.0 },
  15503. "tCube": { type: "t", value: null }
  15504. },
  15505. fragmentShader: [
  15506. "uniform samplerCube tCube;",
  15507. "varying vec3 vReflect;",
  15508. "varying vec3 vRefract[3];",
  15509. "varying float vReflectionFactor;",
  15510. "void main() {",
  15511. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15512. "vec4 refractedColor = vec4( 1.0 );",
  15513. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  15514. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  15515. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  15516. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  15517. "}"
  15518. ].join("\n"),
  15519. vertexShader: [
  15520. "uniform float mRefractionRatio;",
  15521. "uniform float mFresnelBias;",
  15522. "uniform float mFresnelScale;",
  15523. "uniform float mFresnelPower;",
  15524. "varying vec3 vReflect;",
  15525. "varying vec3 vRefract[3];",
  15526. "varying float vReflectionFactor;",
  15527. "void main() {",
  15528. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  15529. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15530. "vec3 worldNormal = normalize( mat3( modelMatrix[0].xyz, modelMatrix[1].xyz, modelMatrix[2].xyz ) * normal );",
  15531. "vec3 I = worldPosition.xyz - cameraPosition;",
  15532. "vReflect = reflect( I, worldNormal );",
  15533. "vRefract[0] = refract( normalize( I ), worldNormal, mRefractionRatio );",
  15534. "vRefract[1] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.99 );",
  15535. "vRefract[2] = refract( normalize( I ), worldNormal, mRefractionRatio * 0.98 );",
  15536. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), worldNormal ), mFresnelPower );",
  15537. "gl_Position = projectionMatrix * mvPosition;",
  15538. "}"
  15539. ].join("\n")
  15540. },
  15541. /* -------------------------------------------------------------------------
  15542. // Normal map shader
  15543. // - Blinn-Phong
  15544. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  15545. // - point and directional lights (use with "lights: true" material option)
  15546. ------------------------------------------------------------------------- */
  15547. 'normal' : {
  15548. uniforms: THREE.UniformsUtils.merge( [
  15549. THREE.UniformsLib[ "fog" ],
  15550. THREE.UniformsLib[ "lights" ],
  15551. THREE.UniformsLib[ "shadowmap" ],
  15552. {
  15553. "enableAO" : { type: "i", value: 0 },
  15554. "enableDiffuse" : { type: "i", value: 0 },
  15555. "enableSpecular" : { type: "i", value: 0 },
  15556. "enableReflection": { type: "i", value: 0 },
  15557. "enableDisplacement": { type: "i", value: 0 },
  15558. "tDisplacement": { type: "t", value: null }, // must go first as this is vertex texture
  15559. "tDiffuse" : { type: "t", value: null },
  15560. "tCube" : { type: "t", value: null },
  15561. "tNormal" : { type: "t", value: null },
  15562. "tSpecular" : { type: "t", value: null },
  15563. "tAO" : { type: "t", value: null },
  15564. "uNormalScale": { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15565. "uDisplacementBias": { type: "f", value: 0.0 },
  15566. "uDisplacementScale": { type: "f", value: 1.0 },
  15567. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15568. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  15569. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  15570. "uShininess": { type: "f", value: 30 },
  15571. "uOpacity": { type: "f", value: 1 },
  15572. "useRefract": { type: "i", value: 0 },
  15573. "uRefractionRatio": { type: "f", value: 0.98 },
  15574. "uReflectivity": { type: "f", value: 0.5 },
  15575. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  15576. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  15577. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  15578. }
  15579. ] ),
  15580. fragmentShader: [
  15581. "uniform vec3 uAmbientColor;",
  15582. "uniform vec3 uDiffuseColor;",
  15583. "uniform vec3 uSpecularColor;",
  15584. "uniform float uShininess;",
  15585. "uniform float uOpacity;",
  15586. "uniform bool enableDiffuse;",
  15587. "uniform bool enableSpecular;",
  15588. "uniform bool enableAO;",
  15589. "uniform bool enableReflection;",
  15590. "uniform sampler2D tDiffuse;",
  15591. "uniform sampler2D tNormal;",
  15592. "uniform sampler2D tSpecular;",
  15593. "uniform sampler2D tAO;",
  15594. "uniform samplerCube tCube;",
  15595. "uniform vec2 uNormalScale;",
  15596. "uniform bool useRefract;",
  15597. "uniform float uRefractionRatio;",
  15598. "uniform float uReflectivity;",
  15599. "varying vec3 vTangent;",
  15600. "varying vec3 vBinormal;",
  15601. "varying vec3 vNormal;",
  15602. "varying vec2 vUv;",
  15603. "uniform vec3 ambientLightColor;",
  15604. "#if MAX_DIR_LIGHTS > 0",
  15605. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  15606. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  15607. "#endif",
  15608. "#if MAX_HEMI_LIGHTS > 0",
  15609. "uniform vec3 hemisphereLightSkyColor[ MAX_HEMI_LIGHTS ];",
  15610. "uniform vec3 hemisphereLightGroundColor[ MAX_HEMI_LIGHTS ];",
  15611. "uniform vec3 hemisphereLightDirection[ MAX_HEMI_LIGHTS ];",
  15612. "#endif",
  15613. "#if MAX_POINT_LIGHTS > 0",
  15614. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  15615. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  15616. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  15617. "#endif",
  15618. "#if MAX_SPOT_LIGHTS > 0",
  15619. "uniform vec3 spotLightColor[ MAX_SPOT_LIGHTS ];",
  15620. "uniform vec3 spotLightPosition[ MAX_SPOT_LIGHTS ];",
  15621. "uniform vec3 spotLightDirection[ MAX_SPOT_LIGHTS ];",
  15622. "uniform float spotLightAngleCos[ MAX_SPOT_LIGHTS ];",
  15623. "uniform float spotLightExponent[ MAX_SPOT_LIGHTS ];",
  15624. "uniform float spotLightDistance[ MAX_SPOT_LIGHTS ];",
  15625. "#endif",
  15626. "#ifdef WRAP_AROUND",
  15627. "uniform vec3 wrapRGB;",
  15628. "#endif",
  15629. "varying vec3 vWorldPosition;",
  15630. "varying vec3 vViewPosition;",
  15631. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  15632. THREE.ShaderChunk[ "fog_pars_fragment" ],
  15633. "void main() {",
  15634. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  15635. "vec3 specularTex = vec3( 1.0 );",
  15636. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  15637. "normalTex.xy *= uNormalScale;",
  15638. "normalTex = normalize( normalTex );",
  15639. "if( enableDiffuse ) {",
  15640. "#ifdef GAMMA_INPUT",
  15641. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  15642. "texelColor.xyz *= texelColor.xyz;",
  15643. "gl_FragColor = gl_FragColor * texelColor;",
  15644. "#else",
  15645. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  15646. "#endif",
  15647. "}",
  15648. "if( enableAO ) {",
  15649. "#ifdef GAMMA_INPUT",
  15650. "vec4 aoColor = texture2D( tAO, vUv );",
  15651. "aoColor.xyz *= aoColor.xyz;",
  15652. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  15653. "#else",
  15654. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  15655. "#endif",
  15656. "}",
  15657. "if( enableSpecular )",
  15658. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  15659. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  15660. "vec3 finalNormal = tsb * normalTex;",
  15661. "#ifdef FLIP_SIDED",
  15662. "finalNormal = -finalNormal;",
  15663. "#endif",
  15664. "vec3 normal = normalize( finalNormal );",
  15665. "vec3 viewPosition = normalize( vViewPosition );",
  15666. // point lights
  15667. "#if MAX_POINT_LIGHTS > 0",
  15668. "vec3 pointDiffuse = vec3( 0.0 );",
  15669. "vec3 pointSpecular = vec3( 0.0 );",
  15670. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  15671. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  15672. "vec3 pointVector = lPosition.xyz + vViewPosition.xyz;",
  15673. "float pointDistance = 1.0;",
  15674. "if ( pointLightDistance[ i ] > 0.0 )",
  15675. "pointDistance = 1.0 - min( ( length( pointVector ) / pointLightDistance[ i ] ), 1.0 );",
  15676. "pointVector = normalize( pointVector );",
  15677. // diffuse
  15678. "#ifdef WRAP_AROUND",
  15679. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  15680. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  15681. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  15682. "#else",
  15683. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  15684. "#endif",
  15685. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  15686. // specular
  15687. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  15688. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  15689. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  15690. "#ifdef PHYSICALLY_BASED_SHADING",
  15691. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15692. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15693. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  15694. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  15695. "#else",
  15696. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  15697. "#endif",
  15698. "}",
  15699. "#endif",
  15700. // spot lights
  15701. "#if MAX_SPOT_LIGHTS > 0",
  15702. "vec3 spotDiffuse = vec3( 0.0 );",
  15703. "vec3 spotSpecular = vec3( 0.0 );",
  15704. "for ( int i = 0; i < MAX_SPOT_LIGHTS; i ++ ) {",
  15705. "vec4 lPosition = viewMatrix * vec4( spotLightPosition[ i ], 1.0 );",
  15706. "vec3 spotVector = lPosition.xyz + vViewPosition.xyz;",
  15707. "float spotDistance = 1.0;",
  15708. "if ( spotLightDistance[ i ] > 0.0 )",
  15709. "spotDistance = 1.0 - min( ( length( spotVector ) / spotLightDistance[ i ] ), 1.0 );",
  15710. "spotVector = normalize( spotVector );",
  15711. "float spotEffect = dot( spotLightDirection[ i ], normalize( spotLightPosition[ i ] - vWorldPosition ) );",
  15712. "if ( spotEffect > spotLightAngleCos[ i ] ) {",
  15713. "spotEffect = max( pow( spotEffect, spotLightExponent[ i ] ), 0.0 );",
  15714. // diffuse
  15715. "#ifdef WRAP_AROUND",
  15716. "float spotDiffuseWeightFull = max( dot( normal, spotVector ), 0.0 );",
  15717. "float spotDiffuseWeightHalf = max( 0.5 * dot( normal, spotVector ) + 0.5, 0.0 );",
  15718. "vec3 spotDiffuseWeight = mix( vec3 ( spotDiffuseWeightFull ), vec3( spotDiffuseWeightHalf ), wrapRGB );",
  15719. "#else",
  15720. "float spotDiffuseWeight = max( dot( normal, spotVector ), 0.0 );",
  15721. "#endif",
  15722. "spotDiffuse += spotDistance * spotLightColor[ i ] * uDiffuseColor * spotDiffuseWeight * spotEffect;",
  15723. // specular
  15724. "vec3 spotHalfVector = normalize( spotVector + viewPosition );",
  15725. "float spotDotNormalHalf = max( dot( normal, spotHalfVector ), 0.0 );",
  15726. "float spotSpecularWeight = specularTex.r * max( pow( spotDotNormalHalf, uShininess ), 0.0 );",
  15727. "#ifdef PHYSICALLY_BASED_SHADING",
  15728. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15729. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15730. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( spotVector, spotHalfVector ), 5.0 );",
  15731. "spotSpecular += schlick * spotLightColor[ i ] * spotSpecularWeight * spotDiffuseWeight * spotDistance * specularNormalization * spotEffect;",
  15732. "#else",
  15733. "spotSpecular += spotDistance * spotLightColor[ i ] * uSpecularColor * spotSpecularWeight * spotDiffuseWeight * spotEffect;",
  15734. "#endif",
  15735. "}",
  15736. "}",
  15737. "#endif",
  15738. // directional lights
  15739. "#if MAX_DIR_LIGHTS > 0",
  15740. "vec3 dirDiffuse = vec3( 0.0 );",
  15741. "vec3 dirSpecular = vec3( 0.0 );",
  15742. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  15743. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  15744. "vec3 dirVector = normalize( lDirection.xyz );",
  15745. // diffuse
  15746. "#ifdef WRAP_AROUND",
  15747. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  15748. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  15749. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  15750. "#else",
  15751. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  15752. "#endif",
  15753. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  15754. // specular
  15755. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  15756. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  15757. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  15758. "#ifdef PHYSICALLY_BASED_SHADING",
  15759. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15760. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15761. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  15762. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  15763. "#else",
  15764. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  15765. "#endif",
  15766. "}",
  15767. "#endif",
  15768. // hemisphere lights
  15769. "#if MAX_HEMI_LIGHTS > 0",
  15770. "vec3 hemiDiffuse = vec3( 0.0 );",
  15771. "vec3 hemiSpecular = vec3( 0.0 );" ,
  15772. "for( int i = 0; i < MAX_HEMI_LIGHTS; i ++ ) {",
  15773. "vec4 lDirection = viewMatrix * vec4( hemisphereLightDirection[ i ], 0.0 );",
  15774. "vec3 lVector = normalize( lDirection.xyz );",
  15775. // diffuse
  15776. "float dotProduct = dot( normal, lVector );",
  15777. "float hemiDiffuseWeight = 0.5 * dotProduct + 0.5;",
  15778. "vec3 hemiColor = mix( hemisphereLightGroundColor[ i ], hemisphereLightSkyColor[ i ], hemiDiffuseWeight );",
  15779. "hemiDiffuse += uDiffuseColor * hemiColor;",
  15780. // specular (sky light)
  15781. "vec3 hemiHalfVectorSky = normalize( lVector + viewPosition );",
  15782. "float hemiDotNormalHalfSky = 0.5 * dot( normal, hemiHalfVectorSky ) + 0.5;",
  15783. "float hemiSpecularWeightSky = specularTex.r * max( pow( hemiDotNormalHalfSky, uShininess ), 0.0 );",
  15784. // specular (ground light)
  15785. "vec3 lVectorGround = -lVector;",
  15786. "vec3 hemiHalfVectorGround = normalize( lVectorGround + viewPosition );",
  15787. "float hemiDotNormalHalfGround = 0.5 * dot( normal, hemiHalfVectorGround ) + 0.5;",
  15788. "float hemiSpecularWeightGround = specularTex.r * max( pow( hemiDotNormalHalfGround, uShininess ), 0.0 );",
  15789. "#ifdef PHYSICALLY_BASED_SHADING",
  15790. "float dotProductGround = dot( normal, lVectorGround );",
  15791. // 2.0 => 2.0001 is hack to work around ANGLE bug
  15792. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  15793. "vec3 schlickSky = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVector, hemiHalfVectorSky ), 5.0 );",
  15794. "vec3 schlickGround = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( lVectorGround, hemiHalfVectorGround ), 5.0 );",
  15795. "hemiSpecular += hemiColor * specularNormalization * ( schlickSky * hemiSpecularWeightSky * max( dotProduct, 0.0 ) + schlickGround * hemiSpecularWeightGround * max( dotProductGround, 0.0 ) );",
  15796. "#else",
  15797. "hemiSpecular += uSpecularColor * hemiColor * ( hemiSpecularWeightSky + hemiSpecularWeightGround ) * hemiDiffuseWeight;",
  15798. "#endif",
  15799. "}",
  15800. "#endif",
  15801. // all lights contribution summation
  15802. "vec3 totalDiffuse = vec3( 0.0 );",
  15803. "vec3 totalSpecular = vec3( 0.0 );",
  15804. "#if MAX_DIR_LIGHTS > 0",
  15805. "totalDiffuse += dirDiffuse;",
  15806. "totalSpecular += dirSpecular;",
  15807. "#endif",
  15808. "#if MAX_HEMI_LIGHTS > 0",
  15809. "totalDiffuse += hemiDiffuse;",
  15810. "totalSpecular += hemiSpecular;",
  15811. "#endif",
  15812. "#if MAX_POINT_LIGHTS > 0",
  15813. "totalDiffuse += pointDiffuse;",
  15814. "totalSpecular += pointSpecular;",
  15815. "#endif",
  15816. "#if MAX_SPOT_LIGHTS > 0",
  15817. "totalDiffuse += spotDiffuse;",
  15818. "totalSpecular += spotSpecular;",
  15819. "#endif",
  15820. "#ifdef METAL",
  15821. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor + totalSpecular );",
  15822. "#else",
  15823. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor ) + totalSpecular;",
  15824. "#endif",
  15825. "if ( enableReflection ) {",
  15826. "vec3 vReflect;",
  15827. "vec3 cameraToVertex = normalize( vWorldPosition - cameraPosition );",
  15828. "if ( useRefract ) {",
  15829. "vReflect = refract( cameraToVertex, normal, uRefractionRatio );",
  15830. "} else {",
  15831. "vReflect = reflect( cameraToVertex, normal );",
  15832. "}",
  15833. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  15834. "#ifdef GAMMA_INPUT",
  15835. "cubeColor.xyz *= cubeColor.xyz;",
  15836. "#endif",
  15837. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  15838. "}",
  15839. THREE.ShaderChunk[ "shadowmap_fragment" ],
  15840. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  15841. THREE.ShaderChunk[ "fog_fragment" ],
  15842. "}"
  15843. ].join("\n"),
  15844. vertexShader: [
  15845. "attribute vec4 tangent;",
  15846. "uniform vec2 uOffset;",
  15847. "uniform vec2 uRepeat;",
  15848. "uniform bool enableDisplacement;",
  15849. "#ifdef VERTEX_TEXTURES",
  15850. "uniform sampler2D tDisplacement;",
  15851. "uniform float uDisplacementScale;",
  15852. "uniform float uDisplacementBias;",
  15853. "#endif",
  15854. "varying vec3 vTangent;",
  15855. "varying vec3 vBinormal;",
  15856. "varying vec3 vNormal;",
  15857. "varying vec2 vUv;",
  15858. "varying vec3 vWorldPosition;",
  15859. "varying vec3 vViewPosition;",
  15860. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  15861. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  15862. "void main() {",
  15863. THREE.ShaderChunk[ "skinbase_vertex" ],
  15864. THREE.ShaderChunk[ "skinnormal_vertex" ],
  15865. // normal, tangent and binormal vectors
  15866. "#ifdef USE_SKINNING",
  15867. "vNormal = normalize( normalMatrix * skinnedNormal.xyz );",
  15868. "vec4 skinnedTangent = skinMatrix * vec4( tangent.xyz, 0.0 );",
  15869. "vTangent = normalize( normalMatrix * skinnedTangent.xyz );",
  15870. "#else",
  15871. "vNormal = normalize( normalMatrix * normal );",
  15872. "vTangent = normalize( normalMatrix * tangent.xyz );",
  15873. "#endif",
  15874. "vBinormal = normalize( cross( vNormal, vTangent ) * tangent.w );",
  15875. "vUv = uv * uRepeat + uOffset;",
  15876. // displacement mapping
  15877. "vec3 displacedPosition;",
  15878. "#ifdef VERTEX_TEXTURES",
  15879. "if ( enableDisplacement ) {",
  15880. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  15881. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  15882. "displacedPosition = position + normalize( normal ) * df;",
  15883. "} else {",
  15884. "#ifdef USE_SKINNING",
  15885. "vec4 skinVertex = vec4( position, 1.0 );",
  15886. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15887. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15888. "displacedPosition = skinned.xyz;",
  15889. "#else",
  15890. "displacedPosition = position;",
  15891. "#endif",
  15892. "}",
  15893. "#else",
  15894. "#ifdef USE_SKINNING",
  15895. "vec4 skinVertex = vec4( position, 1.0 );",
  15896. "vec4 skinned = boneMatX * skinVertex * skinWeight.x;",
  15897. "skinned += boneMatY * skinVertex * skinWeight.y;",
  15898. "displacedPosition = skinned.xyz;",
  15899. "#else",
  15900. "displacedPosition = position;",
  15901. "#endif",
  15902. "#endif",
  15903. //
  15904. "vec4 mvPosition = modelViewMatrix * vec4( displacedPosition, 1.0 );",
  15905. "vec4 worldPosition = modelMatrix * vec4( displacedPosition, 1.0 );",
  15906. "gl_Position = projectionMatrix * mvPosition;",
  15907. //
  15908. "vWorldPosition = worldPosition.xyz;",
  15909. "vViewPosition = -mvPosition.xyz;",
  15910. // shadows
  15911. "#ifdef USE_SHADOWMAP",
  15912. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  15913. "vShadowCoord[ i ] = shadowMatrix[ i ] * worldPosition;",
  15914. "}",
  15915. "#endif",
  15916. "}"
  15917. ].join("\n")
  15918. },
  15919. /* -------------------------------------------------------------------------
  15920. // Cube map shader
  15921. ------------------------------------------------------------------------- */
  15922. 'cube': {
  15923. uniforms: { "tCube": { type: "t", value: null },
  15924. "tFlip": { type: "f", value: -1 } },
  15925. vertexShader: [
  15926. "varying vec3 vWorldPosition;",
  15927. "void main() {",
  15928. "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );",
  15929. "vWorldPosition = worldPosition.xyz;",
  15930. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  15931. "}"
  15932. ].join("\n"),
  15933. fragmentShader: [
  15934. "uniform samplerCube tCube;",
  15935. "uniform float tFlip;",
  15936. "varying vec3 vWorldPosition;",
  15937. "void main() {",
  15938. "gl_FragColor = textureCube( tCube, vec3( tFlip * vWorldPosition.x, vWorldPosition.yz ) );",
  15939. "}"
  15940. ].join("\n")
  15941. }
  15942. }
  15943. };
  15944. /**
  15945. * @author zz85 / http://www.lab4games.net/zz85/blog
  15946. * @author alteredq / http://alteredqualia.com/
  15947. *
  15948. * For Text operations in three.js (See TextGeometry)
  15949. *
  15950. * It uses techniques used in:
  15951. *
  15952. * typeface.js and canvastext
  15953. * For converting fonts and rendering with javascript
  15954. * http://typeface.neocracy.org
  15955. *
  15956. * Triangulation ported from AS3
  15957. * Simple Polygon Triangulation
  15958. * http://actionsnippet.com/?p=1462
  15959. *
  15960. * A Method to triangulate shapes with holes
  15961. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15962. *
  15963. */
  15964. THREE.FontUtils = {
  15965. faces : {},
  15966. // Just for now. face[weight][style]
  15967. face : "helvetiker",
  15968. weight: "normal",
  15969. style : "normal",
  15970. size : 150,
  15971. divisions : 10,
  15972. getFace : function() {
  15973. return this.faces[ this.face ][ this.weight ][ this.style ];
  15974. },
  15975. loadFace : function( data ) {
  15976. var family = data.familyName.toLowerCase();
  15977. var ThreeFont = this;
  15978. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15979. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15980. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15981. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15982. return data;
  15983. },
  15984. drawText : function( text ) {
  15985. var characterPts = [], allPts = [];
  15986. // RenderText
  15987. var i, p,
  15988. face = this.getFace(),
  15989. scale = this.size / face.resolution,
  15990. offset = 0,
  15991. chars = String( text ).split( '' ),
  15992. length = chars.length;
  15993. var fontPaths = [];
  15994. for ( i = 0; i < length; i ++ ) {
  15995. var path = new THREE.Path();
  15996. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15997. offset += ret.offset;
  15998. fontPaths.push( ret.path );
  15999. }
  16000. // get the width
  16001. var width = offset / 2;
  16002. //
  16003. // for ( p = 0; p < allPts.length; p++ ) {
  16004. //
  16005. // allPts[ p ].x -= width;
  16006. //
  16007. // }
  16008. //var extract = this.extractPoints( allPts, characterPts );
  16009. //extract.contour = allPts;
  16010. //extract.paths = fontPaths;
  16011. //extract.offset = width;
  16012. return { paths : fontPaths, offset : width };
  16013. },
  16014. extractGlyphPoints : function( c, face, scale, offset, path ) {
  16015. var pts = [];
  16016. var i, i2, divisions,
  16017. outline, action, length,
  16018. scaleX, scaleY,
  16019. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  16020. laste,
  16021. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  16022. if ( !glyph ) return;
  16023. if ( glyph.o ) {
  16024. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  16025. length = outline.length;
  16026. scaleX = scale;
  16027. scaleY = scale;
  16028. for ( i = 0; i < length; ) {
  16029. action = outline[ i ++ ];
  16030. //console.log( action );
  16031. switch( action ) {
  16032. case 'm':
  16033. // Move To
  16034. x = outline[ i++ ] * scaleX + offset;
  16035. y = outline[ i++ ] * scaleY;
  16036. path.moveTo( x, y );
  16037. break;
  16038. case 'l':
  16039. // Line To
  16040. x = outline[ i++ ] * scaleX + offset;
  16041. y = outline[ i++ ] * scaleY;
  16042. path.lineTo(x,y);
  16043. break;
  16044. case 'q':
  16045. // QuadraticCurveTo
  16046. cpx = outline[ i++ ] * scaleX + offset;
  16047. cpy = outline[ i++ ] * scaleY;
  16048. cpx1 = outline[ i++ ] * scaleX + offset;
  16049. cpy1 = outline[ i++ ] * scaleY;
  16050. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  16051. laste = pts[ pts.length - 1 ];
  16052. if ( laste ) {
  16053. cpx0 = laste.x;
  16054. cpy0 = laste.y;
  16055. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16056. var t = i2 / divisions;
  16057. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  16058. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  16059. }
  16060. }
  16061. break;
  16062. case 'b':
  16063. // Cubic Bezier Curve
  16064. cpx = outline[ i++ ] * scaleX + offset;
  16065. cpy = outline[ i++ ] * scaleY;
  16066. cpx1 = outline[ i++ ] * scaleX + offset;
  16067. cpy1 = outline[ i++ ] * -scaleY;
  16068. cpx2 = outline[ i++ ] * scaleX + offset;
  16069. cpy2 = outline[ i++ ] * -scaleY;
  16070. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  16071. laste = pts[ pts.length - 1 ];
  16072. if ( laste ) {
  16073. cpx0 = laste.x;
  16074. cpy0 = laste.y;
  16075. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  16076. var t = i2 / divisions;
  16077. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  16078. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  16079. }
  16080. }
  16081. break;
  16082. }
  16083. }
  16084. }
  16085. return { offset: glyph.ha*scale, path:path};
  16086. }
  16087. };
  16088. THREE.FontUtils.generateShapes = function( text, parameters ) {
  16089. // Parameters
  16090. parameters = parameters || {};
  16091. var size = parameters.size !== undefined ? parameters.size : 100;
  16092. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  16093. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  16094. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  16095. var style = parameters.style !== undefined ? parameters.style : "normal";
  16096. THREE.FontUtils.size = size;
  16097. THREE.FontUtils.divisions = curveSegments;
  16098. THREE.FontUtils.face = font;
  16099. THREE.FontUtils.weight = weight;
  16100. THREE.FontUtils.style = style;
  16101. // Get a Font data json object
  16102. var data = THREE.FontUtils.drawText( text );
  16103. var paths = data.paths;
  16104. var shapes = [];
  16105. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  16106. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  16107. }
  16108. return shapes;
  16109. };
  16110. /**
  16111. * This code is a quick port of code written in C++ which was submitted to
  16112. * flipcode.com by John W. Ratcliff // July 22, 2000
  16113. * See original code and more information here:
  16114. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  16115. *
  16116. * ported to actionscript by Zevan Rosser
  16117. * www.actionsnippet.com
  16118. *
  16119. * ported to javascript by Joshua Koo
  16120. * http://www.lab4games.net/zz85/blog
  16121. *
  16122. */
  16123. ( function( namespace ) {
  16124. var EPSILON = 0.0000000001;
  16125. // takes in an contour array and returns
  16126. var process = function( contour, indices ) {
  16127. var n = contour.length;
  16128. if ( n < 3 ) return null;
  16129. var result = [],
  16130. verts = [],
  16131. vertIndices = [];
  16132. /* we want a counter-clockwise polygon in verts */
  16133. var u, v, w;
  16134. if ( area( contour ) > 0.0 ) {
  16135. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  16136. } else {
  16137. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  16138. }
  16139. var nv = n;
  16140. /* remove nv - 2 vertices, creating 1 triangle every time */
  16141. var count = 2 * nv; /* error detection */
  16142. for( v = nv - 1; nv > 2; ) {
  16143. /* if we loop, it is probably a non-simple polygon */
  16144. if ( ( count-- ) <= 0 ) {
  16145. //** Triangulate: ERROR - probable bad polygon!
  16146. //throw ( "Warning, unable to triangulate polygon!" );
  16147. //return null;
  16148. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  16149. console.log( "Warning, unable to triangulate polygon!" );
  16150. if ( indices ) return vertIndices;
  16151. return result;
  16152. }
  16153. /* three consecutive vertices in current polygon, <u,v,w> */
  16154. u = v; if ( nv <= u ) u = 0; /* previous */
  16155. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  16156. w = v + 1; if ( nv <= w ) w = 0; /* next */
  16157. if ( snip( contour, u, v, w, nv, verts ) ) {
  16158. var a, b, c, s, t;
  16159. /* true names of the vertices */
  16160. a = verts[ u ];
  16161. b = verts[ v ];
  16162. c = verts[ w ];
  16163. /* output Triangle */
  16164. /*
  16165. result.push( contour[ a ] );
  16166. result.push( contour[ b ] );
  16167. result.push( contour[ c ] );
  16168. */
  16169. result.push( [ contour[ a ],
  16170. contour[ b ],
  16171. contour[ c ] ] );
  16172. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  16173. /* remove v from the remaining polygon */
  16174. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  16175. verts[ s ] = verts[ t ];
  16176. }
  16177. nv--;
  16178. /* reset error detection counter */
  16179. count = 2 * nv;
  16180. }
  16181. }
  16182. if ( indices ) return vertIndices;
  16183. return result;
  16184. };
  16185. // calculate area of the contour polygon
  16186. var area = function ( contour ) {
  16187. var n = contour.length;
  16188. var a = 0.0;
  16189. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  16190. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  16191. }
  16192. return a * 0.5;
  16193. };
  16194. // see if p is inside triangle abc
  16195. var insideTriangle = function( ax, ay,
  16196. bx, by,
  16197. cx, cy,
  16198. px, py ) {
  16199. var aX, aY, bX, bY;
  16200. var cX, cY, apx, apy;
  16201. var bpx, bpy, cpx, cpy;
  16202. var cCROSSap, bCROSScp, aCROSSbp;
  16203. aX = cx - bx; aY = cy - by;
  16204. bX = ax - cx; bY = ay - cy;
  16205. cX = bx - ax; cY = by - ay;
  16206. apx= px -ax; apy= py - ay;
  16207. bpx= px - bx; bpy= py - by;
  16208. cpx= px - cx; cpy= py - cy;
  16209. aCROSSbp = aX*bpy - aY*bpx;
  16210. cCROSSap = cX*apy - cY*apx;
  16211. bCROSScp = bX*cpy - bY*cpx;
  16212. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  16213. };
  16214. var snip = function ( contour, u, v, w, n, verts ) {
  16215. var p;
  16216. var ax, ay, bx, by;
  16217. var cx, cy, px, py;
  16218. ax = contour[ verts[ u ] ].x;
  16219. ay = contour[ verts[ u ] ].y;
  16220. bx = contour[ verts[ v ] ].x;
  16221. by = contour[ verts[ v ] ].y;
  16222. cx = contour[ verts[ w ] ].x;
  16223. cy = contour[ verts[ w ] ].y;
  16224. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  16225. for ( p = 0; p < n; p++ ) {
  16226. if( (p == u) || (p == v) || (p == w) ) continue;
  16227. px = contour[ verts[ p ] ].x
  16228. py = contour[ verts[ p ] ].y
  16229. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  16230. }
  16231. return true;
  16232. };
  16233. namespace.Triangulate = process;
  16234. namespace.Triangulate.area = area;
  16235. return namespace;
  16236. })(THREE.FontUtils);
  16237. // To use the typeface.js face files, hook up the API
  16238. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };/**
  16239. * @author zz85 / http://www.lab4games.net/zz85/blog
  16240. * Extensible curve object
  16241. *
  16242. * Some common of Curve methods
  16243. * .getPoint(t), getTangent(t)
  16244. * .getPointAt(u), getTagentAt(u)
  16245. * .getPoints(), .getSpacedPoints()
  16246. * .getLength()
  16247. * .updateArcLengths()
  16248. *
  16249. * This file contains following classes:
  16250. *
  16251. * -- 2d classes --
  16252. * THREE.Curve
  16253. * THREE.LineCurve
  16254. * THREE.QuadraticBezierCurve
  16255. * THREE.CubicBezierCurve
  16256. * THREE.SplineCurve
  16257. * THREE.ArcCurve
  16258. * THREE.EllipseCurve
  16259. *
  16260. * -- 3d classes --
  16261. * THREE.LineCurve3
  16262. * THREE.QuadraticBezierCurve3
  16263. * THREE.CubicBezierCurve3
  16264. * THREE.SplineCurve3
  16265. * THREE.ClosedSplineCurve3
  16266. *
  16267. * A series of curves can be represented as a THREE.CurvePath
  16268. *
  16269. **/
  16270. /**************************************************************
  16271. * Abstract Curve base class
  16272. **************************************************************/
  16273. THREE.Curve = function () {
  16274. };
  16275. // Virtual base class method to overwrite and implement in subclasses
  16276. // - t [0 .. 1]
  16277. THREE.Curve.prototype.getPoint = function ( t ) {
  16278. console.log( "Warning, getPoint() not implemented!" );
  16279. return null;
  16280. };
  16281. // Get point at relative position in curve according to arc length
  16282. // - u [0 .. 1]
  16283. THREE.Curve.prototype.getPointAt = function ( u ) {
  16284. var t = this.getUtoTmapping( u );
  16285. return this.getPoint( t );
  16286. };
  16287. // Get sequence of points using getPoint( t )
  16288. THREE.Curve.prototype.getPoints = function ( divisions ) {
  16289. if ( !divisions ) divisions = 5;
  16290. var d, pts = [];
  16291. for ( d = 0; d <= divisions; d ++ ) {
  16292. pts.push( this.getPoint( d / divisions ) );
  16293. }
  16294. return pts;
  16295. };
  16296. // Get sequence of points using getPointAt( u )
  16297. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  16298. if ( !divisions ) divisions = 5;
  16299. var d, pts = [];
  16300. for ( d = 0; d <= divisions; d ++ ) {
  16301. pts.push( this.getPointAt( d / divisions ) );
  16302. }
  16303. return pts;
  16304. };
  16305. // Get total curve arc length
  16306. THREE.Curve.prototype.getLength = function () {
  16307. var lengths = this.getLengths();
  16308. return lengths[ lengths.length - 1 ];
  16309. };
  16310. // Get list of cumulative segment lengths
  16311. THREE.Curve.prototype.getLengths = function ( divisions ) {
  16312. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  16313. if ( this.cacheArcLengths
  16314. && ( this.cacheArcLengths.length == divisions + 1 )
  16315. && !this.needsUpdate) {
  16316. //console.log( "cached", this.cacheArcLengths );
  16317. return this.cacheArcLengths;
  16318. }
  16319. this.needsUpdate = false;
  16320. var cache = [];
  16321. var current, last = this.getPoint( 0 );
  16322. var p, sum = 0;
  16323. cache.push( 0 );
  16324. for ( p = 1; p <= divisions; p ++ ) {
  16325. current = this.getPoint ( p / divisions );
  16326. sum += current.distanceTo( last );
  16327. cache.push( sum );
  16328. last = current;
  16329. }
  16330. this.cacheArcLengths = cache;
  16331. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  16332. };
  16333. THREE.Curve.prototype.updateArcLengths = function() {
  16334. this.needsUpdate = true;
  16335. this.getLengths();
  16336. };
  16337. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  16338. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  16339. var arcLengths = this.getLengths();
  16340. var i = 0, il = arcLengths.length;
  16341. var targetArcLength; // The targeted u distance value to get
  16342. if ( distance ) {
  16343. targetArcLength = distance;
  16344. } else {
  16345. targetArcLength = u * arcLengths[ il - 1 ];
  16346. }
  16347. //var time = Date.now();
  16348. // binary search for the index with largest value smaller than target u distance
  16349. var low = 0, high = il - 1, comparison;
  16350. while ( low <= high ) {
  16351. 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
  16352. comparison = arcLengths[ i ] - targetArcLength;
  16353. if ( comparison < 0 ) {
  16354. low = i + 1;
  16355. continue;
  16356. } else if ( comparison > 0 ) {
  16357. high = i - 1;
  16358. continue;
  16359. } else {
  16360. high = i;
  16361. break;
  16362. // DONE
  16363. }
  16364. }
  16365. i = high;
  16366. //console.log('b' , i, low, high, Date.now()- time);
  16367. if ( arcLengths[ i ] == targetArcLength ) {
  16368. var t = i / ( il - 1 );
  16369. return t;
  16370. }
  16371. // we could get finer grain at lengths, or use simple interpolatation between two points
  16372. var lengthBefore = arcLengths[ i ];
  16373. var lengthAfter = arcLengths[ i + 1 ];
  16374. var segmentLength = lengthAfter - lengthBefore;
  16375. // determine where we are between the 'before' and 'after' points
  16376. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  16377. // add that fractional amount to t
  16378. var t = ( i + segmentFraction ) / ( il -1 );
  16379. return t;
  16380. };
  16381. // In 2D space, there are actually 2 normal vectors,
  16382. // and in 3D space, infinte
  16383. // TODO this should be depreciated.
  16384. THREE.Curve.prototype.getNormalVector = function( t ) {
  16385. var vec = this.getTangent( t );
  16386. return new THREE.Vector2( -vec.y , vec.x );
  16387. };
  16388. // Returns a unit vector tangent at t
  16389. // In case any sub curve does not implement its tangent / normal finding,
  16390. // we get 2 points with a small delta and find a gradient of the 2 points
  16391. // which seems to make a reasonable approximation
  16392. THREE.Curve.prototype.getTangent = function( t ) {
  16393. var delta = 0.0001;
  16394. var t1 = t - delta;
  16395. var t2 = t + delta;
  16396. // Capping in case of danger
  16397. if ( t1 < 0 ) t1 = 0;
  16398. if ( t2 > 1 ) t2 = 1;
  16399. var pt1 = this.getPoint( t1 );
  16400. var pt2 = this.getPoint( t2 );
  16401. var vec = pt2.clone().subSelf(pt1);
  16402. return vec.normalize();
  16403. };
  16404. THREE.Curve.prototype.getTangentAt = function ( u ) {
  16405. var t = this.getUtoTmapping( u );
  16406. return this.getTangent( t );
  16407. };
  16408. /**************************************************************
  16409. * Line
  16410. **************************************************************/
  16411. THREE.LineCurve = function ( v1, v2 ) {
  16412. this.v1 = v1;
  16413. this.v2 = v2;
  16414. };
  16415. THREE.LineCurve.prototype = Object.create( THREE.Curve.prototype );
  16416. THREE.LineCurve.prototype.getPoint = function ( t ) {
  16417. var point = this.v2.clone().subSelf(this.v1);
  16418. point.multiplyScalar( t ).addSelf( this.v1 );
  16419. return point;
  16420. };
  16421. // Line curve is linear, so we can overwrite default getPointAt
  16422. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  16423. return this.getPoint( u );
  16424. };
  16425. THREE.LineCurve.prototype.getTangent = function( t ) {
  16426. var tangent = this.v2.clone().subSelf(this.v1);
  16427. return tangent.normalize();
  16428. };
  16429. /**************************************************************
  16430. * Quadratic Bezier curve
  16431. **************************************************************/
  16432. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  16433. this.v0 = v0;
  16434. this.v1 = v1;
  16435. this.v2 = v2;
  16436. };
  16437. THREE.QuadraticBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16438. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  16439. var tx, ty;
  16440. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16441. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16442. return new THREE.Vector2( tx, ty );
  16443. };
  16444. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  16445. var tx, ty;
  16446. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  16447. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  16448. // returns unit vector
  16449. var tangent = new THREE.Vector2( tx, ty );
  16450. tangent.normalize();
  16451. return tangent;
  16452. };
  16453. /**************************************************************
  16454. * Cubic Bezier curve
  16455. **************************************************************/
  16456. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  16457. this.v0 = v0;
  16458. this.v1 = v1;
  16459. this.v2 = v2;
  16460. this.v3 = v3;
  16461. };
  16462. THREE.CubicBezierCurve.prototype = Object.create( THREE.Curve.prototype );
  16463. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  16464. var tx, ty;
  16465. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16466. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16467. return new THREE.Vector2( tx, ty );
  16468. };
  16469. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  16470. var tx, ty;
  16471. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16472. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16473. var tangent = new THREE.Vector2( tx, ty );
  16474. tangent.normalize();
  16475. return tangent;
  16476. };
  16477. /**************************************************************
  16478. * Spline curve
  16479. **************************************************************/
  16480. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  16481. this.points = (points == undefined) ? [] : points;
  16482. };
  16483. THREE.SplineCurve.prototype = Object.create( THREE.Curve.prototype );
  16484. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  16485. var v = new THREE.Vector2();
  16486. var c = [];
  16487. var points = this.points, point, intPoint, weight;
  16488. point = ( points.length - 1 ) * t;
  16489. intPoint = Math.floor( point );
  16490. weight = point - intPoint;
  16491. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16492. c[ 1 ] = intPoint;
  16493. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  16494. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  16495. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16496. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16497. return v;
  16498. };
  16499. /**************************************************************
  16500. * Ellipse curve
  16501. **************************************************************/
  16502. THREE.EllipseCurve = function ( aX, aY, xRadius, yRadius,
  16503. aStartAngle, aEndAngle,
  16504. aClockwise ) {
  16505. this.aX = aX;
  16506. this.aY = aY;
  16507. this.xRadius = xRadius;
  16508. this.yRadius = yRadius;
  16509. this.aStartAngle = aStartAngle;
  16510. this.aEndAngle = aEndAngle;
  16511. this.aClockwise = aClockwise;
  16512. };
  16513. THREE.EllipseCurve.prototype = Object.create( THREE.Curve.prototype );
  16514. THREE.EllipseCurve.prototype.getPoint = function ( t ) {
  16515. var deltaAngle = this.aEndAngle - this.aStartAngle;
  16516. if ( !this.aClockwise ) {
  16517. t = 1 - t;
  16518. }
  16519. var angle = this.aStartAngle + t * deltaAngle;
  16520. var tx = this.aX + this.xRadius * Math.cos( angle );
  16521. var ty = this.aY + this.yRadius * Math.sin( angle );
  16522. return new THREE.Vector2( tx, ty );
  16523. };
  16524. /**************************************************************
  16525. * Arc curve
  16526. **************************************************************/
  16527. THREE.ArcCurve = function ( aX, aY, aRadius, aStartAngle, aEndAngle, aClockwise ) {
  16528. THREE.EllipseCurve.call( this, aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise );
  16529. };
  16530. THREE.ArcCurve.prototype = Object.create( THREE.EllipseCurve.prototype );
  16531. /**************************************************************
  16532. * Utils
  16533. **************************************************************/
  16534. THREE.Curve.Utils = {
  16535. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  16536. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  16537. },
  16538. // Puay Bing, thanks for helping with this derivative!
  16539. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  16540. return -3 * p0 * (1 - t) * (1 - t) +
  16541. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  16542. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  16543. 3 * t * t * p3;
  16544. },
  16545. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  16546. // To check if my formulas are correct
  16547. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  16548. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  16549. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  16550. var h11 = 3 * t * t - 2 * t; // t3 − t2
  16551. return h00 + h10 + h01 + h11;
  16552. },
  16553. // Catmull-Rom
  16554. interpolate: function( p0, p1, p2, p3, t ) {
  16555. var v0 = ( p2 - p0 ) * 0.5;
  16556. var v1 = ( p3 - p1 ) * 0.5;
  16557. var t2 = t * t;
  16558. var t3 = t * t2;
  16559. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  16560. }
  16561. };
  16562. // TODO: Transformation for Curves?
  16563. /**************************************************************
  16564. * 3D Curves
  16565. **************************************************************/
  16566. // A Factory method for creating new curve subclasses
  16567. THREE.Curve.create = function ( constructor, getPointFunc ) {
  16568. constructor.prototype = Object.create( THREE.Curve.prototype );
  16569. constructor.prototype.getPoint = getPointFunc;
  16570. return constructor;
  16571. };
  16572. /**************************************************************
  16573. * Line3D
  16574. **************************************************************/
  16575. THREE.LineCurve3 = THREE.Curve.create(
  16576. function ( v1, v2 ) {
  16577. this.v1 = v1;
  16578. this.v2 = v2;
  16579. },
  16580. function ( t ) {
  16581. var r = new THREE.Vector3();
  16582. r.sub( this.v2, this.v1 ); // diff
  16583. r.multiplyScalar( t );
  16584. r.addSelf( this.v1 );
  16585. return r;
  16586. }
  16587. );
  16588. /**************************************************************
  16589. * Quadratic Bezier 3D curve
  16590. **************************************************************/
  16591. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  16592. function ( v0, v1, v2 ) {
  16593. this.v0 = v0;
  16594. this.v1 = v1;
  16595. this.v2 = v2;
  16596. },
  16597. function ( t ) {
  16598. var tx, ty, tz;
  16599. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  16600. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  16601. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  16602. return new THREE.Vector3( tx, ty, tz );
  16603. }
  16604. );
  16605. /**************************************************************
  16606. * Cubic Bezier 3D curve
  16607. **************************************************************/
  16608. THREE.CubicBezierCurve3 = THREE.Curve.create(
  16609. function ( v0, v1, v2, v3 ) {
  16610. this.v0 = v0;
  16611. this.v1 = v1;
  16612. this.v2 = v2;
  16613. this.v3 = v3;
  16614. },
  16615. function ( t ) {
  16616. var tx, ty, tz;
  16617. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  16618. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  16619. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  16620. return new THREE.Vector3( tx, ty, tz );
  16621. }
  16622. );
  16623. /**************************************************************
  16624. * Spline 3D curve
  16625. **************************************************************/
  16626. THREE.SplineCurve3 = THREE.Curve.create(
  16627. function ( points /* array of Vector3 */) {
  16628. this.points = (points == undefined) ? [] : points;
  16629. },
  16630. function ( t ) {
  16631. var v = new THREE.Vector3();
  16632. var c = [];
  16633. var points = this.points, point, intPoint, weight;
  16634. point = ( points.length - 1 ) * t;
  16635. intPoint = Math.floor( point );
  16636. weight = point - intPoint;
  16637. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16638. c[ 1 ] = intPoint;
  16639. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16640. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16641. var pt0 = points[ c[0] ],
  16642. pt1 = points[ c[1] ],
  16643. pt2 = points[ c[2] ],
  16644. pt3 = points[ c[3] ];
  16645. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  16646. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  16647. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  16648. return v;
  16649. }
  16650. );
  16651. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  16652. // var v = new THREE.Vector3();
  16653. // var c = [];
  16654. // var points = this.points, point, intPoint, weight;
  16655. // point = ( points.length - 1 ) * t;
  16656. // intPoint = Math.floor( point );
  16657. // weight = point - intPoint;
  16658. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  16659. // c[ 1 ] = intPoint;
  16660. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  16661. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  16662. // var pt0 = points[ c[0] ],
  16663. // pt1 = points[ c[1] ],
  16664. // pt2 = points[ c[2] ],
  16665. // pt3 = points[ c[3] ];
  16666. // // t = weight;
  16667. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  16668. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  16669. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  16670. // return v;
  16671. // }
  16672. /**************************************************************
  16673. * Closed Spline 3D curve
  16674. **************************************************************/
  16675. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  16676. function ( points /* array of Vector3 */) {
  16677. this.points = (points == undefined) ? [] : points;
  16678. },
  16679. function ( t ) {
  16680. var v = new THREE.Vector3();
  16681. var c = [];
  16682. var points = this.points, point, intPoint, weight;
  16683. point = ( points.length - 0 ) * t;
  16684. // This needs to be from 0-length +1
  16685. intPoint = Math.floor( point );
  16686. weight = point - intPoint;
  16687. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  16688. c[ 0 ] = ( intPoint - 1 ) % points.length;
  16689. c[ 1 ] = ( intPoint ) % points.length;
  16690. c[ 2 ] = ( intPoint + 1 ) % points.length;
  16691. c[ 3 ] = ( intPoint + 2 ) % points.length;
  16692. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  16693. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  16694. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  16695. return v;
  16696. }
  16697. );
  16698. /**
  16699. * @author zz85 / http://www.lab4games.net/zz85/blog
  16700. *
  16701. **/
  16702. /**************************************************************
  16703. * Curved Path - a curve path is simply a array of connected
  16704. * curves, but retains the api of a curve
  16705. **************************************************************/
  16706. THREE.CurvePath = function () {
  16707. this.curves = [];
  16708. this.bends = [];
  16709. this.autoClose = false; // Automatically closes the path
  16710. };
  16711. THREE.CurvePath.prototype = Object.create( THREE.Curve.prototype );
  16712. THREE.CurvePath.prototype.add = function ( curve ) {
  16713. this.curves.push( curve );
  16714. };
  16715. THREE.CurvePath.prototype.checkConnection = function() {
  16716. // TODO
  16717. // If the ending of curve is not connected to the starting
  16718. // or the next curve, then, this is not a real path
  16719. };
  16720. THREE.CurvePath.prototype.closePath = function() {
  16721. // TODO Test
  16722. // and verify for vector3 (needs to implement equals)
  16723. // Add a line curve if start and end of lines are not connected
  16724. var startPoint = this.curves[0].getPoint(0);
  16725. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  16726. if (!startPoint.equals(endPoint)) {
  16727. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  16728. }
  16729. };
  16730. // To get accurate point with reference to
  16731. // entire path distance at time t,
  16732. // following has to be done:
  16733. // 1. Length of each sub path have to be known
  16734. // 2. Locate and identify type of curve
  16735. // 3. Get t for the curve
  16736. // 4. Return curve.getPointAt(t')
  16737. THREE.CurvePath.prototype.getPoint = function( t ) {
  16738. var d = t * this.getLength();
  16739. var curveLengths = this.getCurveLengths();
  16740. var i = 0, diff, curve;
  16741. // To think about boundaries points.
  16742. while ( i < curveLengths.length ) {
  16743. if ( curveLengths[ i ] >= d ) {
  16744. diff = curveLengths[ i ] - d;
  16745. curve = this.curves[ i ];
  16746. var u = 1 - diff / curve.getLength();
  16747. return curve.getPointAt( u );
  16748. break;
  16749. }
  16750. i ++;
  16751. }
  16752. return null;
  16753. // loop where sum != 0, sum > d , sum+1 <d
  16754. };
  16755. /*
  16756. THREE.CurvePath.prototype.getTangent = function( t ) {
  16757. };*/
  16758. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  16759. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  16760. // getPoint() depends on getLength
  16761. THREE.CurvePath.prototype.getLength = function() {
  16762. var lens = this.getCurveLengths();
  16763. return lens[ lens.length - 1 ];
  16764. };
  16765. // Compute lengths and cache them
  16766. // We cannot overwrite getLengths() because UtoT mapping uses it.
  16767. THREE.CurvePath.prototype.getCurveLengths = function() {
  16768. // We use cache values if curves and cache array are same length
  16769. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  16770. return this.cacheLengths;
  16771. };
  16772. // Get length of subsurve
  16773. // Push sums into cached array
  16774. var lengths = [], sums = 0;
  16775. var i, il = this.curves.length;
  16776. for ( i = 0; i < il; i ++ ) {
  16777. sums += this.curves[ i ].getLength();
  16778. lengths.push( sums );
  16779. }
  16780. this.cacheLengths = lengths;
  16781. return lengths;
  16782. };
  16783. // Returns min and max coordinates, as well as centroid
  16784. THREE.CurvePath.prototype.getBoundingBox = function () {
  16785. var points = this.getPoints();
  16786. var maxX, maxY, maxZ;
  16787. var minX, minY, minZ;
  16788. maxX = maxY = Number.NEGATIVE_INFINITY;
  16789. minX = minY = Number.POSITIVE_INFINITY;
  16790. var p, i, il, sum;
  16791. var v3 = points[0] instanceof THREE.Vector3;
  16792. sum = v3 ? new THREE.Vector3() : new THREE.Vector2();
  16793. for ( i = 0, il = points.length; i < il; i ++ ) {
  16794. p = points[ i ];
  16795. if ( p.x > maxX ) maxX = p.x;
  16796. else if ( p.x < minX ) minX = p.x;
  16797. if ( p.y > maxY ) maxY = p.y;
  16798. else if ( p.y < minY ) minY = p.y;
  16799. if (v3) {
  16800. if ( p.z > maxZ ) maxZ = p.z;
  16801. else if ( p.z < minZ ) minZ = p.z;
  16802. }
  16803. sum.addSelf( p );
  16804. }
  16805. var ret = {
  16806. minX: minX,
  16807. minY: minY,
  16808. maxX: maxX,
  16809. maxY: maxY,
  16810. centroid: sum.divideScalar( il )
  16811. };
  16812. if (v3) {
  16813. ret.maxZ = maxZ;
  16814. ret.minZ = minZ;
  16815. }
  16816. return ret;
  16817. };
  16818. /**************************************************************
  16819. * Create Geometries Helpers
  16820. **************************************************************/
  16821. /// Generate geometry from path points (for Line or ParticleSystem objects)
  16822. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  16823. var pts = this.getPoints( divisions, true );
  16824. return this.createGeometry( pts );
  16825. };
  16826. // Generate geometry from equidistance sampling along the path
  16827. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  16828. var pts = this.getSpacedPoints( divisions, true );
  16829. return this.createGeometry( pts );
  16830. };
  16831. THREE.CurvePath.prototype.createGeometry = function( points ) {
  16832. var geometry = new THREE.Geometry();
  16833. for ( var i = 0; i < points.length; i ++ ) {
  16834. geometry.vertices.push( new THREE.Vector3( points[ i ].x, points[ i ].y, points[ i ].z || 0) );
  16835. }
  16836. return geometry;
  16837. };
  16838. /**************************************************************
  16839. * Bend / Wrap Helper Methods
  16840. **************************************************************/
  16841. // Wrap path / Bend modifiers?
  16842. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  16843. this.bends.push( bendpath );
  16844. };
  16845. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  16846. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  16847. var i, il;
  16848. if ( !bends ) {
  16849. bends = this.bends;
  16850. }
  16851. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16852. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16853. }
  16854. return oldPts;
  16855. };
  16856. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  16857. var oldPts = this.getSpacedPoints( segments );
  16858. var i, il;
  16859. if ( !bends ) {
  16860. bends = this.bends;
  16861. }
  16862. for ( i = 0, il = bends.length; i < il; i ++ ) {
  16863. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  16864. }
  16865. return oldPts;
  16866. };
  16867. // This returns getPoints() bend/wrapped around the contour of a path.
  16868. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  16869. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  16870. var bounds = this.getBoundingBox();
  16871. var i, il, p, oldX, oldY, xNorm;
  16872. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  16873. p = oldPts[ i ];
  16874. oldX = p.x;
  16875. oldY = p.y;
  16876. xNorm = oldX / bounds.maxX;
  16877. // If using actual distance, for length > path, requires line extrusions
  16878. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  16879. xNorm = path.getUtoTmapping( xNorm, oldX );
  16880. // check for out of bounds?
  16881. var pathPt = path.getPoint( xNorm );
  16882. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  16883. p.x = pathPt.x + normal.x;
  16884. p.y = pathPt.y + normal.y;
  16885. }
  16886. return oldPts;
  16887. };
  16888. /**
  16889. * @author alteredq / http://alteredqualia.com/
  16890. */
  16891. THREE.Gyroscope = function () {
  16892. THREE.Object3D.call( this );
  16893. };
  16894. THREE.Gyroscope.prototype = Object.create( THREE.Object3D.prototype );
  16895. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  16896. this.matrixAutoUpdate && this.updateMatrix();
  16897. // update matrixWorld
  16898. if ( this.matrixWorldNeedsUpdate || force ) {
  16899. if ( this.parent ) {
  16900. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  16901. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  16902. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  16903. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  16904. } else {
  16905. this.matrixWorld.copy( this.matrix );
  16906. }
  16907. this.matrixWorldNeedsUpdate = false;
  16908. force = true;
  16909. }
  16910. // update children
  16911. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  16912. this.children[ i ].updateMatrixWorld( force );
  16913. }
  16914. };
  16915. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  16916. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  16917. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  16918. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  16919. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  16920. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  16921. /**
  16922. * @author zz85 / http://www.lab4games.net/zz85/blog
  16923. * Creates free form 2d path using series of points, lines or curves.
  16924. *
  16925. **/
  16926. THREE.Path = function ( points ) {
  16927. THREE.CurvePath.call(this);
  16928. this.actions = [];
  16929. if ( points ) {
  16930. this.fromPoints( points );
  16931. }
  16932. };
  16933. THREE.Path.prototype = Object.create( THREE.CurvePath.prototype );
  16934. THREE.PathActions = {
  16935. MOVE_TO: 'moveTo',
  16936. LINE_TO: 'lineTo',
  16937. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  16938. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  16939. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  16940. ARC: 'arc', // Circle
  16941. ELLIPSE: 'ellipse'
  16942. };
  16943. // TODO Clean up PATH API
  16944. // Create path using straight lines to connect all points
  16945. // - vectors: array of Vector2
  16946. THREE.Path.prototype.fromPoints = function ( vectors ) {
  16947. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  16948. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  16949. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  16950. };
  16951. };
  16952. // startPath() endPath()?
  16953. THREE.Path.prototype.moveTo = function ( x, y ) {
  16954. var args = Array.prototype.slice.call( arguments );
  16955. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  16956. };
  16957. THREE.Path.prototype.lineTo = function ( x, y ) {
  16958. var args = Array.prototype.slice.call( arguments );
  16959. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16960. var x0 = lastargs[ lastargs.length - 2 ];
  16961. var y0 = lastargs[ lastargs.length - 1 ];
  16962. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  16963. this.curves.push( curve );
  16964. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  16965. };
  16966. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  16967. var args = Array.prototype.slice.call( arguments );
  16968. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16969. var x0 = lastargs[ lastargs.length - 2 ];
  16970. var y0 = lastargs[ lastargs.length - 1 ];
  16971. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  16972. new THREE.Vector2( aCPx, aCPy ),
  16973. new THREE.Vector2( aX, aY ) );
  16974. this.curves.push( curve );
  16975. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  16976. };
  16977. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  16978. aCP2x, aCP2y,
  16979. aX, aY ) {
  16980. var args = Array.prototype.slice.call( arguments );
  16981. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16982. var x0 = lastargs[ lastargs.length - 2 ];
  16983. var y0 = lastargs[ lastargs.length - 1 ];
  16984. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  16985. new THREE.Vector2( aCP1x, aCP1y ),
  16986. new THREE.Vector2( aCP2x, aCP2y ),
  16987. new THREE.Vector2( aX, aY ) );
  16988. this.curves.push( curve );
  16989. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  16990. };
  16991. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  16992. var args = Array.prototype.slice.call( arguments );
  16993. var lastargs = this.actions[ this.actions.length - 1 ].args;
  16994. var x0 = lastargs[ lastargs.length - 2 ];
  16995. var y0 = lastargs[ lastargs.length - 1 ];
  16996. //---
  16997. var npts = [ new THREE.Vector2( x0, y0 ) ];
  16998. Array.prototype.push.apply( npts, pts );
  16999. var curve = new THREE.SplineCurve( npts );
  17000. this.curves.push( curve );
  17001. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  17002. };
  17003. // FUTURE: Change the API or follow canvas API?
  17004. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  17005. aStartAngle, aEndAngle, aClockwise ) {
  17006. var lastargs = this.actions[ this.actions.length - 1].args;
  17007. var x0 = lastargs[ lastargs.length - 2 ];
  17008. var y0 = lastargs[ lastargs.length - 1 ];
  17009. this.absarc(aX + x0, aY + y0, aRadius,
  17010. aStartAngle, aEndAngle, aClockwise );
  17011. };
  17012. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  17013. aStartAngle, aEndAngle, aClockwise ) {
  17014. this.absellipse(aX, aY, aRadius, aRadius, aStartAngle, aEndAngle, aClockwise);
  17015. };
  17016. THREE.Path.prototype.ellipse = function ( aX, aY, xRadius, yRadius,
  17017. aStartAngle, aEndAngle, aClockwise ) {
  17018. var lastargs = this.actions[ this.actions.length - 1].args;
  17019. var x0 = lastargs[ lastargs.length - 2 ];
  17020. var y0 = lastargs[ lastargs.length - 1 ];
  17021. this.absellipse(aX + x0, aY + y0, xRadius, yRadius,
  17022. aStartAngle, aEndAngle, aClockwise );
  17023. };
  17024. THREE.Path.prototype.absellipse = function ( aX, aY, xRadius, yRadius,
  17025. aStartAngle, aEndAngle, aClockwise ) {
  17026. var args = Array.prototype.slice.call( arguments );
  17027. var curve = new THREE.EllipseCurve( aX, aY, xRadius, yRadius,
  17028. aStartAngle, aEndAngle, aClockwise );
  17029. this.curves.push( curve );
  17030. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  17031. args.push(lastPoint.x);
  17032. args.push(lastPoint.y);
  17033. this.actions.push( { action: THREE.PathActions.ELLIPSE, args: args } );
  17034. };
  17035. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  17036. if ( ! divisions ) divisions = 40;
  17037. var points = [];
  17038. for ( var i = 0; i < divisions; i ++ ) {
  17039. points.push( this.getPoint( i / divisions ) );
  17040. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  17041. }
  17042. // if ( closedPath ) {
  17043. //
  17044. // points.push( points[ 0 ] );
  17045. //
  17046. // }
  17047. return points;
  17048. };
  17049. /* Return an array of vectors based on contour of the path */
  17050. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  17051. if (this.useSpacedPoints) {
  17052. console.log('tata');
  17053. return this.getSpacedPoints( divisions, closedPath );
  17054. }
  17055. divisions = divisions || 12;
  17056. var points = [];
  17057. var i, il, item, action, args;
  17058. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  17059. laste, j,
  17060. t, tx, ty;
  17061. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17062. item = this.actions[ i ];
  17063. action = item.action;
  17064. args = item.args;
  17065. switch( action ) {
  17066. case THREE.PathActions.MOVE_TO:
  17067. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17068. break;
  17069. case THREE.PathActions.LINE_TO:
  17070. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  17071. break;
  17072. case THREE.PathActions.QUADRATIC_CURVE_TO:
  17073. cpx = args[ 2 ];
  17074. cpy = args[ 3 ];
  17075. cpx1 = args[ 0 ];
  17076. cpy1 = args[ 1 ];
  17077. if ( points.length > 0 ) {
  17078. laste = points[ points.length - 1 ];
  17079. cpx0 = laste.x;
  17080. cpy0 = laste.y;
  17081. } else {
  17082. laste = this.actions[ i - 1 ].args;
  17083. cpx0 = laste[ laste.length - 2 ];
  17084. cpy0 = laste[ laste.length - 1 ];
  17085. }
  17086. for ( j = 1; j <= divisions; j ++ ) {
  17087. t = j / divisions;
  17088. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  17089. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  17090. points.push( new THREE.Vector2( tx, ty ) );
  17091. }
  17092. break;
  17093. case THREE.PathActions.BEZIER_CURVE_TO:
  17094. cpx = args[ 4 ];
  17095. cpy = args[ 5 ];
  17096. cpx1 = args[ 0 ];
  17097. cpy1 = args[ 1 ];
  17098. cpx2 = args[ 2 ];
  17099. cpy2 = args[ 3 ];
  17100. if ( points.length > 0 ) {
  17101. laste = points[ points.length - 1 ];
  17102. cpx0 = laste.x;
  17103. cpy0 = laste.y;
  17104. } else {
  17105. laste = this.actions[ i - 1 ].args;
  17106. cpx0 = laste[ laste.length - 2 ];
  17107. cpy0 = laste[ laste.length - 1 ];
  17108. }
  17109. for ( j = 1; j <= divisions; j ++ ) {
  17110. t = j / divisions;
  17111. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  17112. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  17113. points.push( new THREE.Vector2( tx, ty ) );
  17114. }
  17115. break;
  17116. case THREE.PathActions.CSPLINE_THRU:
  17117. laste = this.actions[ i - 1 ].args;
  17118. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  17119. var spts = [ last ];
  17120. var n = divisions * args[ 0 ].length;
  17121. spts = spts.concat( args[ 0 ] );
  17122. var spline = new THREE.SplineCurve( spts );
  17123. for ( j = 1; j <= n; j ++ ) {
  17124. points.push( spline.getPointAt( j / n ) ) ;
  17125. }
  17126. break;
  17127. case THREE.PathActions.ARC:
  17128. var aX = args[ 0 ], aY = args[ 1 ],
  17129. aRadius = args[ 2 ],
  17130. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  17131. aClockwise = !!args[ 5 ];
  17132. var deltaAngle = aEndAngle - aStartAngle;
  17133. var angle;
  17134. var tdivisions = divisions * 2;
  17135. for ( j = 1; j <= tdivisions; j ++ ) {
  17136. t = j / tdivisions;
  17137. if ( ! aClockwise ) {
  17138. t = 1 - t;
  17139. }
  17140. angle = aStartAngle + t * deltaAngle;
  17141. tx = aX + aRadius * Math.cos( angle );
  17142. ty = aY + aRadius * Math.sin( angle );
  17143. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17144. points.push( new THREE.Vector2( tx, ty ) );
  17145. }
  17146. //console.log(points);
  17147. break;
  17148. case THREE.PathActions.ELLIPSE:
  17149. var aX = args[ 0 ], aY = args[ 1 ],
  17150. xRadius = args[ 2 ],
  17151. yRadius = args[ 3 ],
  17152. aStartAngle = args[ 4 ], aEndAngle = args[ 5 ],
  17153. aClockwise = !!args[ 6 ];
  17154. var deltaAngle = aEndAngle - aStartAngle;
  17155. var angle;
  17156. var tdivisions = divisions * 2;
  17157. for ( j = 1; j <= tdivisions; j ++ ) {
  17158. t = j / tdivisions;
  17159. if ( ! aClockwise ) {
  17160. t = 1 - t;
  17161. }
  17162. angle = aStartAngle + t * deltaAngle;
  17163. tx = aX + xRadius * Math.cos( angle );
  17164. ty = aY + yRadius * Math.sin( angle );
  17165. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  17166. points.push( new THREE.Vector2( tx, ty ) );
  17167. }
  17168. //console.log(points);
  17169. break;
  17170. } // end switch
  17171. }
  17172. // Normalize to remove the closing point by default.
  17173. var lastPoint = points[ points.length - 1];
  17174. var EPSILON = 0.0000000001;
  17175. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  17176. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  17177. points.splice( points.length - 1, 1);
  17178. if ( closedPath ) {
  17179. points.push( points[ 0 ] );
  17180. }
  17181. return points;
  17182. };
  17183. // Breaks path into shapes
  17184. THREE.Path.prototype.toShapes = function() {
  17185. var i, il, item, action, args;
  17186. var subPaths = [], lastPath = new THREE.Path();
  17187. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  17188. item = this.actions[ i ];
  17189. args = item.args;
  17190. action = item.action;
  17191. if ( action == THREE.PathActions.MOVE_TO ) {
  17192. if ( lastPath.actions.length != 0 ) {
  17193. subPaths.push( lastPath );
  17194. lastPath = new THREE.Path();
  17195. }
  17196. }
  17197. lastPath[ action ].apply( lastPath, args );
  17198. }
  17199. if ( lastPath.actions.length != 0 ) {
  17200. subPaths.push( lastPath );
  17201. }
  17202. // console.log(subPaths);
  17203. if ( subPaths.length == 0 ) return [];
  17204. var tmpPath, tmpShape, shapes = [];
  17205. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  17206. // console.log("Holes first", holesFirst);
  17207. if ( subPaths.length == 1) {
  17208. tmpPath = subPaths[0];
  17209. tmpShape = new THREE.Shape();
  17210. tmpShape.actions = tmpPath.actions;
  17211. tmpShape.curves = tmpPath.curves;
  17212. shapes.push( tmpShape );
  17213. return shapes;
  17214. };
  17215. if ( holesFirst ) {
  17216. tmpShape = new THREE.Shape();
  17217. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17218. tmpPath = subPaths[ i ];
  17219. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17220. tmpShape.actions = tmpPath.actions;
  17221. tmpShape.curves = tmpPath.curves;
  17222. shapes.push( tmpShape );
  17223. tmpShape = new THREE.Shape();
  17224. //console.log('cw', i);
  17225. } else {
  17226. tmpShape.holes.push( tmpPath );
  17227. //console.log('ccw', i);
  17228. }
  17229. }
  17230. } else {
  17231. // Shapes first
  17232. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  17233. tmpPath = subPaths[ i ];
  17234. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  17235. if ( tmpShape ) shapes.push( tmpShape );
  17236. tmpShape = new THREE.Shape();
  17237. tmpShape.actions = tmpPath.actions;
  17238. tmpShape.curves = tmpPath.curves;
  17239. } else {
  17240. tmpShape.holes.push( tmpPath );
  17241. }
  17242. }
  17243. shapes.push( tmpShape );
  17244. }
  17245. //console.log("shape", shapes);
  17246. return shapes;
  17247. };
  17248. /**
  17249. * @author zz85 / http://www.lab4games.net/zz85/blog
  17250. * Defines a 2d shape plane using paths.
  17251. **/
  17252. // STEP 1 Create a path.
  17253. // STEP 2 Turn path into shape.
  17254. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  17255. // STEP 3a - Extract points from each shape, turn to vertices
  17256. // STEP 3b - Triangulate each shape, add faces.
  17257. THREE.Shape = function ( ) {
  17258. THREE.Path.apply( this, arguments );
  17259. this.holes = [];
  17260. };
  17261. THREE.Shape.prototype = Object.create( THREE.Path.prototype );
  17262. // Convenience method to return ExtrudeGeometry
  17263. THREE.Shape.prototype.extrude = function ( options ) {
  17264. var extruded = new THREE.ExtrudeGeometry( this, options );
  17265. return extruded;
  17266. };
  17267. // Convenience method to return ShapeGeometry
  17268. THREE.Shape.prototype.makeGeometry = function ( options ) {
  17269. var geometry = new THREE.ShapeGeometry( this, options );
  17270. return geometry;
  17271. };
  17272. // Get points of holes
  17273. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  17274. var i, il = this.holes.length, holesPts = [];
  17275. for ( i = 0; i < il; i ++ ) {
  17276. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  17277. }
  17278. return holesPts;
  17279. };
  17280. // Get points of holes (spaced by regular distance)
  17281. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  17282. var i, il = this.holes.length, holesPts = [];
  17283. for ( i = 0; i < il; i ++ ) {
  17284. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  17285. }
  17286. return holesPts;
  17287. };
  17288. // Get points of shape and holes (keypoints based on segments parameter)
  17289. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  17290. return {
  17291. shape: this.getTransformedPoints( divisions ),
  17292. holes: this.getPointsHoles( divisions )
  17293. };
  17294. };
  17295. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  17296. if (this.useSpacedPoints) {
  17297. return this.extractAllSpacedPoints(divisions);
  17298. }
  17299. return this.extractAllPoints(divisions);
  17300. };
  17301. //
  17302. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  17303. //
  17304. // return {
  17305. //
  17306. // shape: this.transform( bend, divisions ),
  17307. // holes: this.getPointsHoles( divisions, bend )
  17308. //
  17309. // };
  17310. //
  17311. // };
  17312. // Get points of shape and holes (spaced by regular distance)
  17313. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  17314. return {
  17315. shape: this.getTransformedSpacedPoints( divisions ),
  17316. holes: this.getSpacedPointsHoles( divisions )
  17317. };
  17318. };
  17319. /**************************************************************
  17320. * Utils
  17321. **************************************************************/
  17322. THREE.Shape.Utils = {
  17323. /*
  17324. contour - array of vector2 for contour
  17325. holes - array of array of vector2
  17326. */
  17327. removeHoles: function ( contour, holes ) {
  17328. var shape = contour.concat(); // work on this shape
  17329. var allpoints = shape.concat();
  17330. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  17331. var prevShapeVert, nextShapeVert,
  17332. prevHoleVert, nextHoleVert,
  17333. holeIndex, shapeIndex,
  17334. shapeId, shapeGroup,
  17335. h, h2,
  17336. hole, shortest, d,
  17337. p, pts1, pts2,
  17338. tmpShape1, tmpShape2,
  17339. tmpHole1, tmpHole2,
  17340. verts = [];
  17341. for ( h = 0; h < holes.length; h ++ ) {
  17342. hole = holes[ h ];
  17343. /*
  17344. shapeholes[ h ].concat(); // preserves original
  17345. holes.push( hole );
  17346. */
  17347. Array.prototype.push.apply( allpoints, hole );
  17348. shortest = Number.POSITIVE_INFINITY;
  17349. // Find the shortest pair of pts between shape and hole
  17350. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  17351. // Using distanceToSquared() intead of distanceTo() should speed a little
  17352. // since running square roots operations are reduced.
  17353. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  17354. pts1 = hole[ h2 ];
  17355. var dist = [];
  17356. for ( p = 0; p < shape.length; p++ ) {
  17357. pts2 = shape[ p ];
  17358. d = pts1.distanceToSquared( pts2 );
  17359. dist.push( d );
  17360. if ( d < shortest ) {
  17361. shortest = d;
  17362. holeIndex = h2;
  17363. shapeIndex = p;
  17364. }
  17365. }
  17366. }
  17367. //console.log("shortest", shortest, dist);
  17368. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17369. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17370. var areaapts = [
  17371. hole[ holeIndex ],
  17372. shape[ shapeIndex ],
  17373. shape[ prevShapeVert ]
  17374. ];
  17375. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  17376. var areabpts = [
  17377. hole[ holeIndex ],
  17378. hole[ prevHoleVert ],
  17379. shape[ shapeIndex ]
  17380. ];
  17381. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  17382. var shapeOffset = 1;
  17383. var holeOffset = -1;
  17384. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  17385. shapeIndex += shapeOffset;
  17386. holeIndex += holeOffset;
  17387. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17388. shapeIndex %= shape.length;
  17389. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17390. holeIndex %= hole.length;
  17391. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17392. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17393. areaapts = [
  17394. hole[ holeIndex ],
  17395. shape[ shapeIndex ],
  17396. shape[ prevShapeVert ]
  17397. ];
  17398. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  17399. areabpts = [
  17400. hole[ holeIndex ],
  17401. hole[ prevHoleVert ],
  17402. shape[ shapeIndex ]
  17403. ];
  17404. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  17405. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  17406. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  17407. // In case areas are not correct.
  17408. //console.log("USE THIS");
  17409. shapeIndex = oldShapeIndex;
  17410. holeIndex = oldHoleIndex ;
  17411. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  17412. shapeIndex %= shape.length;
  17413. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  17414. holeIndex %= hole.length;
  17415. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  17416. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  17417. } else {
  17418. //console.log("USE THAT ")
  17419. }
  17420. tmpShape1 = shape.slice( 0, shapeIndex );
  17421. tmpShape2 = shape.slice( shapeIndex );
  17422. tmpHole1 = hole.slice( holeIndex );
  17423. tmpHole2 = hole.slice( 0, holeIndex );
  17424. // Should check orders here again?
  17425. var trianglea = [
  17426. hole[ holeIndex ],
  17427. shape[ shapeIndex ],
  17428. shape[ prevShapeVert ]
  17429. ];
  17430. var triangleb = [
  17431. hole[ holeIndex ] ,
  17432. hole[ prevHoleVert ],
  17433. shape[ shapeIndex ]
  17434. ];
  17435. verts.push( trianglea );
  17436. verts.push( triangleb );
  17437. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  17438. }
  17439. return {
  17440. shape:shape, /* shape with no holes */
  17441. isolatedPts: verts, /* isolated faces */
  17442. allpoints: allpoints
  17443. }
  17444. },
  17445. triangulateShape: function ( contour, holes ) {
  17446. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  17447. var shape = shapeWithoutHoles.shape,
  17448. allpoints = shapeWithoutHoles.allpoints,
  17449. isolatedPts = shapeWithoutHoles.isolatedPts;
  17450. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  17451. // 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.
  17452. //console.log( "triangles",triangles, triangles.length );
  17453. //console.log( "allpoints",allpoints, allpoints.length );
  17454. var i, il, f, face,
  17455. key, index,
  17456. allPointsMap = {},
  17457. isolatedPointsMap = {};
  17458. // prepare all points map
  17459. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  17460. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  17461. if ( allPointsMap[ key ] !== undefined ) {
  17462. console.log( "Duplicate point", key );
  17463. }
  17464. allPointsMap[ key ] = i;
  17465. }
  17466. // check all face vertices against all points map
  17467. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  17468. face = triangles[ i ];
  17469. for ( f = 0; f < 3; f ++ ) {
  17470. key = face[ f ].x + ":" + face[ f ].y;
  17471. index = allPointsMap[ key ];
  17472. if ( index !== undefined ) {
  17473. face[ f ] = index;
  17474. }
  17475. }
  17476. }
  17477. // check isolated points vertices against all points map
  17478. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  17479. face = isolatedPts[ i ];
  17480. for ( f = 0; f < 3; f ++ ) {
  17481. key = face[ f ].x + ":" + face[ f ].y;
  17482. index = allPointsMap[ key ];
  17483. if ( index !== undefined ) {
  17484. face[ f ] = index;
  17485. }
  17486. }
  17487. }
  17488. return triangles.concat( isolatedPts );
  17489. }, // end triangulate shapes
  17490. /*
  17491. triangulate2 : function( pts, holes ) {
  17492. // For use with Poly2Tri.js
  17493. var allpts = pts.concat();
  17494. var shape = [];
  17495. for (var p in pts) {
  17496. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  17497. }
  17498. var swctx = new js.poly2tri.SweepContext(shape);
  17499. for (var h in holes) {
  17500. var aHole = holes[h];
  17501. var newHole = []
  17502. for (i in aHole) {
  17503. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  17504. allpts.push(aHole[i]);
  17505. }
  17506. swctx.AddHole(newHole);
  17507. }
  17508. var find;
  17509. var findIndexForPt = function (pt) {
  17510. find = new THREE.Vector2(pt.x, pt.y);
  17511. var p;
  17512. for (p=0, pl = allpts.length; p<pl; p++) {
  17513. if (allpts[p].equals(find)) return p;
  17514. }
  17515. return -1;
  17516. };
  17517. // triangulate
  17518. js.poly2tri.sweep.Triangulate(swctx);
  17519. var triangles = swctx.GetTriangles();
  17520. var tr ;
  17521. var facesPts = [];
  17522. for (var t in triangles) {
  17523. tr = triangles[t];
  17524. facesPts.push([
  17525. findIndexForPt(tr.GetPoint(0)),
  17526. findIndexForPt(tr.GetPoint(1)),
  17527. findIndexForPt(tr.GetPoint(2))
  17528. ]);
  17529. }
  17530. // console.log(facesPts);
  17531. // console.log("triangles", triangles.length, triangles);
  17532. // Returns array of faces with 3 element each
  17533. return facesPts;
  17534. },
  17535. */
  17536. isClockWise: function ( pts ) {
  17537. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  17538. },
  17539. // Bezier Curves formulas obtained from
  17540. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  17541. // Quad Bezier Functions
  17542. b2p0: function ( t, p ) {
  17543. var k = 1 - t;
  17544. return k * k * p;
  17545. },
  17546. b2p1: function ( t, p ) {
  17547. return 2 * ( 1 - t ) * t * p;
  17548. },
  17549. b2p2: function ( t, p ) {
  17550. return t * t * p;
  17551. },
  17552. b2: function ( t, p0, p1, p2 ) {
  17553. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  17554. },
  17555. // Cubic Bezier Functions
  17556. b3p0: function ( t, p ) {
  17557. var k = 1 - t;
  17558. return k * k * k * p;
  17559. },
  17560. b3p1: function ( t, p ) {
  17561. var k = 1 - t;
  17562. return 3 * k * k * t * p;
  17563. },
  17564. b3p2: function ( t, p ) {
  17565. var k = 1 - t;
  17566. return 3 * k * t * t * p;
  17567. },
  17568. b3p3: function ( t, p ) {
  17569. return t * t * t * p;
  17570. },
  17571. b3: function ( t, p0, p1, p2, p3 ) {
  17572. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  17573. }
  17574. };
  17575. /**
  17576. * @author mikael emtinger / http://gomo.se/
  17577. */
  17578. THREE.AnimationHandler = (function() {
  17579. var playing = [];
  17580. var library = {};
  17581. var that = {};
  17582. //--- update ---
  17583. that.update = function( deltaTimeMS ) {
  17584. for( var i = 0; i < playing.length; i ++ )
  17585. playing[ i ].update( deltaTimeMS );
  17586. };
  17587. //--- add ---
  17588. that.addToUpdate = function( animation ) {
  17589. if ( playing.indexOf( animation ) === -1 )
  17590. playing.push( animation );
  17591. };
  17592. //--- remove ---
  17593. that.removeFromUpdate = function( animation ) {
  17594. var index = playing.indexOf( animation );
  17595. if( index !== -1 )
  17596. playing.splice( index, 1 );
  17597. };
  17598. //--- add ---
  17599. that.add = function( data ) {
  17600. if ( library[ data.name ] !== undefined )
  17601. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  17602. library[ data.name ] = data;
  17603. initData( data );
  17604. };
  17605. //--- get ---
  17606. that.get = function( name ) {
  17607. if ( typeof name === "string" ) {
  17608. if ( library[ name ] ) {
  17609. return library[ name ];
  17610. } else {
  17611. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  17612. return null;
  17613. }
  17614. } else {
  17615. // todo: add simple tween library
  17616. }
  17617. };
  17618. //--- parse ---
  17619. that.parse = function( root ) {
  17620. // setup hierarchy
  17621. var hierarchy = [];
  17622. if ( root instanceof THREE.SkinnedMesh ) {
  17623. for( var b = 0; b < root.bones.length; b++ ) {
  17624. hierarchy.push( root.bones[ b ] );
  17625. }
  17626. } else {
  17627. parseRecurseHierarchy( root, hierarchy );
  17628. }
  17629. return hierarchy;
  17630. };
  17631. var parseRecurseHierarchy = function( root, hierarchy ) {
  17632. hierarchy.push( root );
  17633. for( var c = 0; c < root.children.length; c++ )
  17634. parseRecurseHierarchy( root.children[ c ], hierarchy );
  17635. }
  17636. //--- init data ---
  17637. var initData = function( data ) {
  17638. if( data.initialized === true )
  17639. return;
  17640. // loop through all keys
  17641. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  17642. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17643. // remove minus times
  17644. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  17645. data.hierarchy[ h ].keys[ k ].time = 0;
  17646. // create quaternions
  17647. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  17648. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  17649. var quat = data.hierarchy[ h ].keys[ k ].rot;
  17650. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  17651. }
  17652. }
  17653. // prepare morph target keys
  17654. if( data.hierarchy[ h ].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  17655. // get all used
  17656. var usedMorphTargets = {};
  17657. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17658. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17659. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  17660. usedMorphTargets[ morphTargetName ] = -1;
  17661. }
  17662. }
  17663. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  17664. // set all used on all frames
  17665. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17666. var influences = {};
  17667. for ( var morphTargetName in usedMorphTargets ) {
  17668. for ( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  17669. if ( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  17670. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  17671. break;
  17672. }
  17673. }
  17674. if ( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  17675. influences[ morphTargetName ] = 0;
  17676. }
  17677. }
  17678. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  17679. }
  17680. }
  17681. // remove all keys that are on the same time
  17682. for ( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17683. if ( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  17684. data.hierarchy[ h ].keys.splice( k, 1 );
  17685. k --;
  17686. }
  17687. }
  17688. // set index
  17689. for ( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  17690. data.hierarchy[ h ].keys[ k ].index = k;
  17691. }
  17692. }
  17693. // JIT
  17694. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  17695. data.JIT = {};
  17696. data.JIT.hierarchy = [];
  17697. for( var h = 0; h < data.hierarchy.length; h ++ )
  17698. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  17699. // done
  17700. data.initialized = true;
  17701. };
  17702. // interpolation types
  17703. that.LINEAR = 0;
  17704. that.CATMULLROM = 1;
  17705. that.CATMULLROM_FORWARD = 2;
  17706. return that;
  17707. }());
  17708. /**
  17709. * @author mikael emtinger / http://gomo.se/
  17710. * @author mrdoob / http://mrdoob.com/
  17711. * @author alteredq / http://alteredqualia.com/
  17712. */
  17713. THREE.Animation = function ( root, name, interpolationType ) {
  17714. this.root = root;
  17715. this.data = THREE.AnimationHandler.get( name );
  17716. this.hierarchy = THREE.AnimationHandler.parse( root );
  17717. this.currentTime = 0;
  17718. this.timeScale = 1;
  17719. this.isPlaying = false;
  17720. this.isPaused = true;
  17721. this.loop = true;
  17722. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  17723. this.points = [];
  17724. this.target = new THREE.Vector3();
  17725. };
  17726. THREE.Animation.prototype.play = function ( loop, startTimeMS ) {
  17727. if ( this.isPlaying === false ) {
  17728. this.isPlaying = true;
  17729. this.loop = loop !== undefined ? loop : true;
  17730. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17731. // reset key cache
  17732. var h, hl = this.hierarchy.length,
  17733. object;
  17734. for ( h = 0; h < hl; h ++ ) {
  17735. object = this.hierarchy[ h ];
  17736. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17737. object.useQuaternion = true;
  17738. }
  17739. object.matrixAutoUpdate = true;
  17740. if ( object.animationCache === undefined ) {
  17741. object.animationCache = {};
  17742. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  17743. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  17744. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17745. }
  17746. var prevKey = object.animationCache.prevKey;
  17747. var nextKey = object.animationCache.nextKey;
  17748. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  17749. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  17750. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  17751. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  17752. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  17753. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  17754. }
  17755. this.update( 0 );
  17756. }
  17757. this.isPaused = false;
  17758. THREE.AnimationHandler.addToUpdate( this );
  17759. };
  17760. THREE.Animation.prototype.pause = function() {
  17761. if ( this.isPaused === true ) {
  17762. THREE.AnimationHandler.addToUpdate( this );
  17763. } else {
  17764. THREE.AnimationHandler.removeFromUpdate( this );
  17765. }
  17766. this.isPaused = !this.isPaused;
  17767. };
  17768. THREE.Animation.prototype.stop = function() {
  17769. this.isPlaying = false;
  17770. this.isPaused = false;
  17771. THREE.AnimationHandler.removeFromUpdate( this );
  17772. };
  17773. THREE.Animation.prototype.update = function ( deltaTimeMS ) {
  17774. // early out
  17775. if ( this.isPlaying === false ) return;
  17776. // vars
  17777. var types = [ "pos", "rot", "scl" ];
  17778. var type;
  17779. var scale;
  17780. var vector;
  17781. var prevXYZ, nextXYZ;
  17782. var prevKey, nextKey;
  17783. var object;
  17784. var animationCache;
  17785. var frame;
  17786. var JIThierarchy = this.data.JIT.hierarchy;
  17787. var currentTime, unloopedCurrentTime;
  17788. var currentPoint, forwardPoint, angle;
  17789. this.currentTime += deltaTimeMS * this.timeScale;
  17790. unloopedCurrentTime = this.currentTime;
  17791. currentTime = this.currentTime = this.currentTime % this.data.length;
  17792. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  17793. for ( var h = 0, hl = this.hierarchy.length; h < hl; h ++ ) {
  17794. object = this.hierarchy[ h ];
  17795. animationCache = object.animationCache;
  17796. // loop through pos/rot/scl
  17797. for ( var t = 0; t < 3; t ++ ) {
  17798. // get keys
  17799. type = types[ t ];
  17800. prevKey = animationCache.prevKey[ type ];
  17801. nextKey = animationCache.nextKey[ type ];
  17802. // switch keys?
  17803. if ( nextKey.time <= unloopedCurrentTime ) {
  17804. // did we loop?
  17805. if ( currentTime < unloopedCurrentTime ) {
  17806. if ( this.loop ) {
  17807. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  17808. nextKey = this.getNextKeyWith( type, h, 1 );
  17809. while( nextKey.time < currentTime ) {
  17810. prevKey = nextKey;
  17811. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17812. }
  17813. } else {
  17814. this.stop();
  17815. return;
  17816. }
  17817. } else {
  17818. do {
  17819. prevKey = nextKey;
  17820. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  17821. } while( nextKey.time < currentTime )
  17822. }
  17823. animationCache.prevKey[ type ] = prevKey;
  17824. animationCache.nextKey[ type ] = nextKey;
  17825. }
  17826. object.matrixAutoUpdate = true;
  17827. object.matrixWorldNeedsUpdate = true;
  17828. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  17829. prevXYZ = prevKey[ type ];
  17830. nextXYZ = nextKey[ type ];
  17831. // check scale error
  17832. if ( scale < 0 || scale > 1 ) {
  17833. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  17834. scale = scale < 0 ? 0 : 1;
  17835. }
  17836. // interpolate
  17837. if ( type === "pos" ) {
  17838. vector = object.position;
  17839. if ( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  17840. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17841. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17842. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17843. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17844. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17845. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  17846. this.points[ 1 ] = prevXYZ;
  17847. this.points[ 2 ] = nextXYZ;
  17848. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  17849. scale = scale * 0.33 + 0.33;
  17850. currentPoint = this.interpolateCatmullRom( this.points, scale );
  17851. vector.x = currentPoint[ 0 ];
  17852. vector.y = currentPoint[ 1 ];
  17853. vector.z = currentPoint[ 2 ];
  17854. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17855. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  17856. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  17857. this.target.subSelf( vector );
  17858. this.target.y = 0;
  17859. this.target.normalize();
  17860. angle = Math.atan2( this.target.x, this.target.z );
  17861. object.rotation.set( 0, angle, 0 );
  17862. }
  17863. }
  17864. } else if ( type === "rot" ) {
  17865. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  17866. } else if ( type === "scl" ) {
  17867. vector = object.scale;
  17868. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  17869. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  17870. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  17871. }
  17872. }
  17873. }
  17874. };
  17875. // Catmull-Rom spline
  17876. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  17877. var c = [], v3 = [],
  17878. point, intPoint, weight, w2, w3,
  17879. pa, pb, pc, pd;
  17880. point = ( points.length - 1 ) * scale;
  17881. intPoint = Math.floor( point );
  17882. weight = point - intPoint;
  17883. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  17884. c[ 1 ] = intPoint;
  17885. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  17886. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  17887. pa = points[ c[ 0 ] ];
  17888. pb = points[ c[ 1 ] ];
  17889. pc = points[ c[ 2 ] ];
  17890. pd = points[ c[ 3 ] ];
  17891. w2 = weight * weight;
  17892. w3 = weight * w2;
  17893. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  17894. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  17895. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  17896. return v3;
  17897. };
  17898. THREE.Animation.prototype.interpolate = function ( p0, p1, p2, p3, t, t2, t3 ) {
  17899. var v0 = ( p2 - p0 ) * 0.5,
  17900. v1 = ( p3 - p1 ) * 0.5;
  17901. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  17902. };
  17903. // Get next key with
  17904. THREE.Animation.prototype.getNextKeyWith = function ( type, h, key ) {
  17905. var keys = this.data.hierarchy[ h ].keys;
  17906. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17907. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17908. key = key < keys.length - 1 ? key : keys.length - 1;
  17909. } else {
  17910. key = key % keys.length;
  17911. }
  17912. for ( ; key < keys.length; key++ ) {
  17913. if ( keys[ key ][ type ] !== undefined ) {
  17914. return keys[ key ];
  17915. }
  17916. }
  17917. return this.data.hierarchy[ h ].keys[ 0 ];
  17918. };
  17919. // Get previous key with
  17920. THREE.Animation.prototype.getPrevKeyWith = function ( type, h, key ) {
  17921. var keys = this.data.hierarchy[ h ].keys;
  17922. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  17923. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  17924. key = key > 0 ? key : 0;
  17925. } else {
  17926. key = key >= 0 ? key : key + keys.length;
  17927. }
  17928. for ( ; key >= 0; key -- ) {
  17929. if ( keys[ key ][ type ] !== undefined ) {
  17930. return keys[ key ];
  17931. }
  17932. }
  17933. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  17934. };
  17935. /**
  17936. * @author mikael emtinger / http://gomo.se/
  17937. * @author mrdoob / http://mrdoob.com/
  17938. * @author alteredq / http://alteredqualia.com/
  17939. * @author khang duong
  17940. * @author erik kitson
  17941. */
  17942. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  17943. this.root = root;
  17944. this.data = THREE.AnimationHandler.get( data );
  17945. this.hierarchy = THREE.AnimationHandler.parse( root );
  17946. this.currentTime = 0;
  17947. this.timeScale = 0.001;
  17948. this.isPlaying = false;
  17949. this.isPaused = true;
  17950. this.loop = true;
  17951. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  17952. // initialize to first keyframes
  17953. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  17954. var keys = this.data.hierarchy[h].keys,
  17955. sids = this.data.hierarchy[h].sids,
  17956. obj = this.hierarchy[h];
  17957. if ( keys.length && sids ) {
  17958. for ( var s = 0; s < sids.length; s++ ) {
  17959. var sid = sids[ s ],
  17960. next = this.getNextKeyWith( sid, h, 0 );
  17961. if ( next ) {
  17962. next.apply( sid );
  17963. }
  17964. }
  17965. obj.matrixAutoUpdate = false;
  17966. this.data.hierarchy[h].node.updateMatrix();
  17967. obj.matrixWorldNeedsUpdate = true;
  17968. }
  17969. }
  17970. };
  17971. // Play
  17972. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  17973. if( !this.isPlaying ) {
  17974. this.isPlaying = true;
  17975. this.loop = loop !== undefined ? loop : true;
  17976. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  17977. this.startTimeMs = startTimeMS;
  17978. this.startTime = 10000000;
  17979. this.endTime = -this.startTime;
  17980. // reset key cache
  17981. var h, hl = this.hierarchy.length,
  17982. object,
  17983. node;
  17984. for ( h = 0; h < hl; h++ ) {
  17985. object = this.hierarchy[ h ];
  17986. node = this.data.hierarchy[ h ];
  17987. object.useQuaternion = true;
  17988. if ( node.animationCache === undefined ) {
  17989. node.animationCache = {};
  17990. node.animationCache.prevKey = null;
  17991. node.animationCache.nextKey = null;
  17992. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  17993. }
  17994. var keys = this.data.hierarchy[h].keys;
  17995. if (keys.length) {
  17996. node.animationCache.prevKey = keys[ 0 ];
  17997. node.animationCache.nextKey = keys[ 1 ];
  17998. this.startTime = Math.min( keys[0].time, this.startTime );
  17999. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  18000. }
  18001. }
  18002. this.update( 0 );
  18003. }
  18004. this.isPaused = false;
  18005. THREE.AnimationHandler.addToUpdate( this );
  18006. };
  18007. // Pause
  18008. THREE.KeyFrameAnimation.prototype.pause = function() {
  18009. if( this.isPaused ) {
  18010. THREE.AnimationHandler.addToUpdate( this );
  18011. } else {
  18012. THREE.AnimationHandler.removeFromUpdate( this );
  18013. }
  18014. this.isPaused = !this.isPaused;
  18015. };
  18016. // Stop
  18017. THREE.KeyFrameAnimation.prototype.stop = function() {
  18018. this.isPlaying = false;
  18019. this.isPaused = false;
  18020. THREE.AnimationHandler.removeFromUpdate( this );
  18021. // reset JIT matrix and remove cache
  18022. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  18023. var obj = this.hierarchy[ h ];
  18024. var node = this.data.hierarchy[ h ];
  18025. if ( node.animationCache !== undefined ) {
  18026. var original = node.animationCache.originalMatrix;
  18027. if( obj instanceof THREE.Bone ) {
  18028. original.copy( obj.skinMatrix );
  18029. obj.skinMatrix = original;
  18030. } else {
  18031. original.copy( obj.matrix );
  18032. obj.matrix = original;
  18033. }
  18034. delete node.animationCache;
  18035. }
  18036. }
  18037. };
  18038. // Update
  18039. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  18040. // early out
  18041. if( !this.isPlaying ) return;
  18042. // vars
  18043. var prevKey, nextKey;
  18044. var object;
  18045. var node;
  18046. var frame;
  18047. var JIThierarchy = this.data.JIT.hierarchy;
  18048. var currentTime, unloopedCurrentTime;
  18049. var looped;
  18050. // update
  18051. this.currentTime += deltaTimeMS * this.timeScale;
  18052. unloopedCurrentTime = this.currentTime;
  18053. currentTime = this.currentTime = this.currentTime % this.data.length;
  18054. // if looped around, the current time should be based on the startTime
  18055. if ( currentTime < this.startTimeMs ) {
  18056. currentTime = this.currentTime = this.startTimeMs + currentTime;
  18057. }
  18058. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  18059. looped = currentTime < unloopedCurrentTime;
  18060. if ( looped && !this.loop ) {
  18061. // Set the animation to the last keyframes and stop
  18062. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18063. var keys = this.data.hierarchy[h].keys,
  18064. sids = this.data.hierarchy[h].sids,
  18065. end = keys.length-1,
  18066. obj = this.hierarchy[h];
  18067. if ( keys.length ) {
  18068. for ( var s = 0; s < sids.length; s++ ) {
  18069. var sid = sids[ s ],
  18070. prev = this.getPrevKeyWith( sid, h, end );
  18071. if ( prev ) {
  18072. prev.apply( sid );
  18073. }
  18074. }
  18075. this.data.hierarchy[h].node.updateMatrix();
  18076. obj.matrixWorldNeedsUpdate = true;
  18077. }
  18078. }
  18079. this.stop();
  18080. return;
  18081. }
  18082. // check pre-infinity
  18083. if ( currentTime < this.startTime ) {
  18084. return;
  18085. }
  18086. // update
  18087. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  18088. object = this.hierarchy[ h ];
  18089. node = this.data.hierarchy[ h ];
  18090. var keys = node.keys,
  18091. animationCache = node.animationCache;
  18092. // use JIT?
  18093. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  18094. if( object instanceof THREE.Bone ) {
  18095. object.skinMatrix = JIThierarchy[ h ][ frame ];
  18096. object.matrixWorldNeedsUpdate = false;
  18097. } else {
  18098. object.matrix = JIThierarchy[ h ][ frame ];
  18099. object.matrixWorldNeedsUpdate = true;
  18100. }
  18101. // use interpolation
  18102. } else if ( keys.length ) {
  18103. // make sure so original matrix and not JIT matrix is set
  18104. if ( this.JITCompile && animationCache ) {
  18105. if( object instanceof THREE.Bone ) {
  18106. object.skinMatrix = animationCache.originalMatrix;
  18107. } else {
  18108. object.matrix = animationCache.originalMatrix;
  18109. }
  18110. }
  18111. prevKey = animationCache.prevKey;
  18112. nextKey = animationCache.nextKey;
  18113. if ( prevKey && nextKey ) {
  18114. // switch keys?
  18115. if ( nextKey.time <= unloopedCurrentTime ) {
  18116. // did we loop?
  18117. if ( looped && this.loop ) {
  18118. prevKey = keys[ 0 ];
  18119. nextKey = keys[ 1 ];
  18120. while ( nextKey.time < currentTime ) {
  18121. prevKey = nextKey;
  18122. nextKey = keys[ prevKey.index + 1 ];
  18123. }
  18124. } else if ( !looped ) {
  18125. var lastIndex = keys.length - 1;
  18126. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  18127. prevKey = nextKey;
  18128. nextKey = keys[ prevKey.index + 1 ];
  18129. }
  18130. }
  18131. animationCache.prevKey = prevKey;
  18132. animationCache.nextKey = nextKey;
  18133. }
  18134. if(nextKey.time >= currentTime)
  18135. prevKey.interpolate( nextKey, currentTime );
  18136. else
  18137. prevKey.interpolate( nextKey, nextKey.time);
  18138. }
  18139. this.data.hierarchy[h].node.updateMatrix();
  18140. object.matrixWorldNeedsUpdate = true;
  18141. }
  18142. }
  18143. // update JIT?
  18144. if ( this.JITCompile ) {
  18145. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  18146. this.hierarchy[ 0 ].updateMatrixWorld( true );
  18147. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  18148. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  18149. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  18150. } else {
  18151. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  18152. }
  18153. }
  18154. }
  18155. }
  18156. };
  18157. // Get next key with
  18158. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  18159. var keys = this.data.hierarchy[ h ].keys;
  18160. key = key % keys.length;
  18161. for ( ; key < keys.length; key++ ) {
  18162. if ( keys[ key ].hasTarget( sid ) ) {
  18163. return keys[ key ];
  18164. }
  18165. }
  18166. return keys[ 0 ];
  18167. };
  18168. // Get previous key with
  18169. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  18170. var keys = this.data.hierarchy[ h ].keys;
  18171. key = key >= 0 ? key : key + keys.length;
  18172. for ( ; key >= 0; key-- ) {
  18173. if ( keys[ key ].hasTarget( sid ) ) {
  18174. return keys[ key ];
  18175. }
  18176. }
  18177. return keys[ keys.length - 1 ];
  18178. };
  18179. /**
  18180. * Camera for rendering cube maps
  18181. * - renders scene into axis-aligned cube
  18182. *
  18183. * @author alteredq / http://alteredqualia.com/
  18184. */
  18185. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  18186. THREE.Object3D.call( this );
  18187. var fov = 90, aspect = 1;
  18188. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18189. cameraPX.up.set( 0, -1, 0 );
  18190. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  18191. this.add( cameraPX );
  18192. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18193. cameraNX.up.set( 0, -1, 0 );
  18194. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  18195. this.add( cameraNX );
  18196. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18197. cameraPY.up.set( 0, 0, 1 );
  18198. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  18199. this.add( cameraPY );
  18200. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18201. cameraNY.up.set( 0, 0, -1 );
  18202. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  18203. this.add( cameraNY );
  18204. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18205. cameraPZ.up.set( 0, -1, 0 );
  18206. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  18207. this.add( cameraPZ );
  18208. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  18209. cameraNZ.up.set( 0, -1, 0 );
  18210. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  18211. this.add( cameraNZ );
  18212. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  18213. this.updateCubeMap = function ( renderer, scene ) {
  18214. var renderTarget = this.renderTarget;
  18215. var generateMipmaps = renderTarget.generateMipmaps;
  18216. renderTarget.generateMipmaps = false;
  18217. renderTarget.activeCubeFace = 0;
  18218. renderer.render( scene, cameraPX, renderTarget );
  18219. renderTarget.activeCubeFace = 1;
  18220. renderer.render( scene, cameraNX, renderTarget );
  18221. renderTarget.activeCubeFace = 2;
  18222. renderer.render( scene, cameraPY, renderTarget );
  18223. renderTarget.activeCubeFace = 3;
  18224. renderer.render( scene, cameraNY, renderTarget );
  18225. renderTarget.activeCubeFace = 4;
  18226. renderer.render( scene, cameraPZ, renderTarget );
  18227. renderTarget.generateMipmaps = generateMipmaps;
  18228. renderTarget.activeCubeFace = 5;
  18229. renderer.render( scene, cameraNZ, renderTarget );
  18230. };
  18231. };
  18232. THREE.CubeCamera.prototype = Object.create( THREE.Object3D.prototype );
  18233. /*
  18234. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  18235. *
  18236. * A general perpose camera, for setting FOV, Lens Focal Length,
  18237. * and switching between perspective and orthographic views easily.
  18238. * Use this only if you do not wish to manage
  18239. * both a Orthographic and Perspective Camera
  18240. *
  18241. */
  18242. THREE.CombinedCamera = function ( width, height, fov, near, far, orthoNear, orthoFar ) {
  18243. THREE.Camera.call( this );
  18244. this.fov = fov;
  18245. this.left = -width / 2;
  18246. this.right = width / 2
  18247. this.top = height / 2;
  18248. this.bottom = -height / 2;
  18249. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  18250. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthoNear, orthoFar );
  18251. this.cameraP = new THREE.PerspectiveCamera( fov, width / height, near, far );
  18252. this.zoom = 1;
  18253. this.toPerspective();
  18254. var aspect = width/height;
  18255. };
  18256. THREE.CombinedCamera.prototype = Object.create( THREE.Camera.prototype );
  18257. THREE.CombinedCamera.prototype.toPerspective = function () {
  18258. // Switches to the Perspective Camera
  18259. this.near = this.cameraP.near;
  18260. this.far = this.cameraP.far;
  18261. this.cameraP.fov = this.fov / this.zoom ;
  18262. this.cameraP.updateProjectionMatrix();
  18263. this.projectionMatrix = this.cameraP.projectionMatrix;
  18264. this.inPerspectiveMode = true;
  18265. this.inOrthographicMode = false;
  18266. };
  18267. THREE.CombinedCamera.prototype.toOrthographic = function () {
  18268. // Switches to the Orthographic camera estimating viewport from Perspective
  18269. var fov = this.fov;
  18270. var aspect = this.cameraP.aspect;
  18271. var near = this.cameraP.near;
  18272. var far = this.cameraP.far;
  18273. // The size that we set is the mid plane of the viewing frustum
  18274. var hyperfocus = ( near + far ) / 2;
  18275. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  18276. var planeHeight = 2 * halfHeight;
  18277. var planeWidth = planeHeight * aspect;
  18278. var halfWidth = planeWidth / 2;
  18279. halfHeight /= this.zoom;
  18280. halfWidth /= this.zoom;
  18281. this.cameraO.left = -halfWidth;
  18282. this.cameraO.right = halfWidth;
  18283. this.cameraO.top = halfHeight;
  18284. this.cameraO.bottom = -halfHeight;
  18285. // this.cameraO.left = -farHalfWidth;
  18286. // this.cameraO.right = farHalfWidth;
  18287. // this.cameraO.top = farHalfHeight;
  18288. // this.cameraO.bottom = -farHalfHeight;
  18289. // this.cameraO.left = this.left / this.zoom;
  18290. // this.cameraO.right = this.right / this.zoom;
  18291. // this.cameraO.top = this.top / this.zoom;
  18292. // this.cameraO.bottom = this.bottom / this.zoom;
  18293. this.cameraO.updateProjectionMatrix();
  18294. this.near = this.cameraO.near;
  18295. this.far = this.cameraO.far;
  18296. this.projectionMatrix = this.cameraO.projectionMatrix;
  18297. this.inPerspectiveMode = false;
  18298. this.inOrthographicMode = true;
  18299. };
  18300. THREE.CombinedCamera.prototype.setSize = function( width, height ) {
  18301. this.cameraP.aspect = width / height;
  18302. this.left = -width / 2;
  18303. this.right = width / 2
  18304. this.top = height / 2;
  18305. this.bottom = -height / 2;
  18306. };
  18307. THREE.CombinedCamera.prototype.setFov = function( fov ) {
  18308. this.fov = fov;
  18309. if ( this.inPerspectiveMode ) {
  18310. this.toPerspective();
  18311. } else {
  18312. this.toOrthographic();
  18313. }
  18314. };
  18315. // For mantaining similar API with PerspectiveCamera
  18316. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  18317. if ( this.inPerspectiveMode ) {
  18318. this.toPerspective();
  18319. } else {
  18320. this.toPerspective();
  18321. this.toOrthographic();
  18322. }
  18323. };
  18324. /*
  18325. * Uses Focal Length (in mm) to estimate and set FOV
  18326. * 35mm (fullframe) camera is used if frame size is not specified;
  18327. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  18328. */
  18329. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  18330. if ( frameHeight === undefined ) frameHeight = 24;
  18331. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  18332. this.setFov( fov );
  18333. return fov;
  18334. };
  18335. THREE.CombinedCamera.prototype.setZoom = function( zoom ) {
  18336. this.zoom = zoom;
  18337. if ( this.inPerspectiveMode ) {
  18338. this.toPerspective();
  18339. } else {
  18340. this.toOrthographic();
  18341. }
  18342. };
  18343. THREE.CombinedCamera.prototype.toFrontView = function() {
  18344. this.rotation.x = 0;
  18345. this.rotation.y = 0;
  18346. this.rotation.z = 0;
  18347. // should we be modifing the matrix instead?
  18348. this.rotationAutoUpdate = false;
  18349. };
  18350. THREE.CombinedCamera.prototype.toBackView = function() {
  18351. this.rotation.x = 0;
  18352. this.rotation.y = Math.PI;
  18353. this.rotation.z = 0;
  18354. this.rotationAutoUpdate = false;
  18355. };
  18356. THREE.CombinedCamera.prototype.toLeftView = function() {
  18357. this.rotation.x = 0;
  18358. this.rotation.y = - Math.PI / 2;
  18359. this.rotation.z = 0;
  18360. this.rotationAutoUpdate = false;
  18361. };
  18362. THREE.CombinedCamera.prototype.toRightView = function() {
  18363. this.rotation.x = 0;
  18364. this.rotation.y = Math.PI / 2;
  18365. this.rotation.z = 0;
  18366. this.rotationAutoUpdate = false;
  18367. };
  18368. THREE.CombinedCamera.prototype.toTopView = function() {
  18369. this.rotation.x = - Math.PI / 2;
  18370. this.rotation.y = 0;
  18371. this.rotation.z = 0;
  18372. this.rotationAutoUpdate = false;
  18373. };
  18374. THREE.CombinedCamera.prototype.toBottomView = function() {
  18375. this.rotation.x = Math.PI / 2;
  18376. this.rotation.y = 0;
  18377. this.rotation.z = 0;
  18378. this.rotationAutoUpdate = false;
  18379. };
  18380. /**
  18381. * @author alteredq / http://alteredqualia.com/
  18382. *
  18383. * - 3d asterisk shape (for line pieces THREE.Line)
  18384. */
  18385. THREE.AsteriskGeometry = function ( innerRadius, outerRadius ) {
  18386. THREE.Geometry.call( this );
  18387. var sd = innerRadius;
  18388. var ed = outerRadius;
  18389. var sd2 = 0.707 * sd;
  18390. var ed2 = 0.707 * ed;
  18391. var rays = [ [ sd, 0, 0 ], [ ed, 0, 0 ], [ -sd, 0, 0 ], [ -ed, 0, 0 ],
  18392. [ 0, sd, 0 ], [ 0, ed, 0 ], [ 0, -sd, 0 ], [ 0, -ed, 0 ],
  18393. [ 0, 0, sd ], [ 0, 0, ed ], [ 0, 0, -sd ], [ 0, 0, -ed ],
  18394. [ sd2, sd2, 0 ], [ ed2, ed2, 0 ], [ -sd2, -sd2, 0 ], [ -ed2, -ed2, 0 ],
  18395. [ sd2, -sd2, 0 ], [ ed2, -ed2, 0 ], [ -sd2, sd2, 0 ], [ -ed2, ed2, 0 ],
  18396. [ sd2, 0, sd2 ], [ ed2, 0, ed2 ], [ -sd2, 0, -sd2 ], [ -ed2, 0, -ed2 ],
  18397. [ sd2, 0, -sd2 ], [ ed2, 0, -ed2 ], [ -sd2, 0, sd2 ], [ -ed2, 0, ed2 ],
  18398. [ 0, sd2, sd2 ], [ 0, ed2, ed2 ], [ 0, -sd2, -sd2 ], [ 0, -ed2, -ed2 ],
  18399. [ 0, sd2, -sd2 ], [ 0, ed2, -ed2 ], [ 0, -sd2, sd2 ], [ 0, -ed2, ed2 ]
  18400. ];
  18401. for ( var i = 0, il = rays.length; i < il; i ++ ) {
  18402. var x = rays[ i ][ 0 ];
  18403. var y = rays[ i ][ 1 ];
  18404. var z = rays[ i ][ 2 ];
  18405. this.vertices.push( new THREE.Vector3( x, y, z ) );
  18406. }
  18407. };
  18408. THREE.AsteriskGeometry.prototype = Object.create( THREE.Geometry.prototype );/**
  18409. * @author hughes
  18410. */
  18411. THREE.CircleGeometry = function ( radius, segments, thetaStart, thetaLength ) {
  18412. THREE.Geometry.call( this );
  18413. radius = radius || 50;
  18414. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  18415. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI * 2;
  18416. segments = segments !== undefined ? Math.max( 3, segments ) : 8;
  18417. var i, uvs = [],
  18418. center = new THREE.Vector3(), centerUV = new THREE.UV( 0.5, 0.5 );
  18419. this.vertices.push(center);
  18420. uvs.push( centerUV );
  18421. for ( i = 0; i <= segments; i ++ ) {
  18422. var vertex = new THREE.Vector3();
  18423. vertex.x = radius * Math.cos( thetaStart + i / segments * thetaLength );
  18424. vertex.y = radius * Math.sin( thetaStart + i / segments * thetaLength );
  18425. this.vertices.push( vertex );
  18426. uvs.push( new THREE.UV( ( vertex.x / radius + 1 ) / 2, - ( vertex.y / radius + 1 ) / 2 + 1 ) );
  18427. }
  18428. var n = new THREE.Vector3( 0, 0, -1 );
  18429. for ( i = 1; i <= segments; i ++ ) {
  18430. var v1 = i;
  18431. var v2 = i + 1 ;
  18432. var v3 = 0;
  18433. this.faces.push( new THREE.Face3( v1, v2, v3, [ n, n, n ] ) );
  18434. this.faceVertexUvs[ 0 ].push( [ uvs[ i ], uvs[ i + 1 ], centerUV ] );
  18435. }
  18436. this.computeCentroids();
  18437. this.computeFaceNormals();
  18438. this.boundingSphere = { radius: radius };
  18439. };
  18440. THREE.CircleGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18441. /**
  18442. * @author mrdoob / http://mrdoob.com/
  18443. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  18444. */
  18445. THREE.CubeGeometry = function ( width, height, depth, widthSegments, heightSegments, depthSegments ) {
  18446. THREE.Geometry.call( this );
  18447. var scope = this;
  18448. this.width = width;
  18449. this.height = height;
  18450. this.depth = depth;
  18451. this.widthSegments = widthSegments || 1;
  18452. this.heightSegments = heightSegments || 1;
  18453. this.depthSegments = depthSegments || 1;
  18454. var width_half = this.width / 2;
  18455. var height_half = this.height / 2;
  18456. var depth_half = this.depth / 2;
  18457. buildPlane( 'z', 'y', - 1, - 1, this.depth, this.height, width_half, 0 ); // px
  18458. buildPlane( 'z', 'y', 1, - 1, this.depth, this.height, - width_half, 1 ); // nx
  18459. buildPlane( 'x', 'z', 1, 1, this.width, this.depth, height_half, 2 ); // py
  18460. buildPlane( 'x', 'z', 1, - 1, this.width, this.depth, - height_half, 3 ); // ny
  18461. buildPlane( 'x', 'y', 1, - 1, this.width, this.height, depth_half, 4 ); // pz
  18462. buildPlane( 'x', 'y', - 1, - 1, this.width, this.height, - depth_half, 5 ); // nz
  18463. function buildPlane( u, v, udir, vdir, width, height, depth, materialIndex ) {
  18464. var w, ix, iy,
  18465. gridX = scope.widthSegments,
  18466. gridY = scope.heightSegments,
  18467. width_half = width / 2,
  18468. height_half = height / 2,
  18469. offset = scope.vertices.length;
  18470. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  18471. w = 'z';
  18472. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  18473. w = 'y';
  18474. gridY = scope.depthSegments;
  18475. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  18476. w = 'x';
  18477. gridX = scope.depthSegments;
  18478. }
  18479. var gridX1 = gridX + 1,
  18480. gridY1 = gridY + 1,
  18481. segment_width = width / gridX,
  18482. segment_height = height / gridY,
  18483. normal = new THREE.Vector3();
  18484. normal[ w ] = depth > 0 ? 1 : - 1;
  18485. for ( iy = 0; iy < gridY1; iy ++ ) {
  18486. for ( ix = 0; ix < gridX1; ix ++ ) {
  18487. var vector = new THREE.Vector3();
  18488. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  18489. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  18490. vector[ w ] = depth;
  18491. scope.vertices.push( vector );
  18492. }
  18493. }
  18494. for ( iy = 0; iy < gridY; iy++ ) {
  18495. for ( ix = 0; ix < gridX; ix++ ) {
  18496. var a = ix + gridX1 * iy;
  18497. var b = ix + gridX1 * ( iy + 1 );
  18498. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  18499. var d = ( ix + 1 ) + gridX1 * iy;
  18500. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  18501. face.normal.copy( normal );
  18502. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  18503. face.materialIndex = materialIndex;
  18504. scope.faces.push( face );
  18505. scope.faceVertexUvs[ 0 ].push( [
  18506. new THREE.UV( ix / gridX, 1 - iy / gridY ),
  18507. new THREE.UV( ix / gridX, 1 - ( iy + 1 ) / gridY ),
  18508. new THREE.UV( ( ix + 1 ) / gridX, 1- ( iy + 1 ) / gridY ),
  18509. new THREE.UV( ( ix + 1 ) / gridX, 1 - iy / gridY )
  18510. ] );
  18511. }
  18512. }
  18513. }
  18514. this.computeCentroids();
  18515. this.mergeVertices();
  18516. };
  18517. THREE.CubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18518. /**
  18519. * @author mrdoob / http://mrdoob.com/
  18520. */
  18521. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, radiusSegments, heightSegments, openEnded ) {
  18522. THREE.Geometry.call( this );
  18523. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  18524. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  18525. height = height !== undefined ? height : 100;
  18526. var heightHalf = height / 2;
  18527. var segmentsX = radiusSegments || 8;
  18528. var segmentsY = heightSegments || 1;
  18529. var x, y, vertices = [], uvs = [];
  18530. for ( y = 0; y <= segmentsY; y ++ ) {
  18531. var verticesRow = [];
  18532. var uvsRow = [];
  18533. var v = y / segmentsY;
  18534. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  18535. for ( x = 0; x <= segmentsX; x ++ ) {
  18536. var u = x / segmentsX;
  18537. var vertex = new THREE.Vector3();
  18538. vertex.x = radius * Math.sin( u * Math.PI * 2 );
  18539. vertex.y = - v * height + heightHalf;
  18540. vertex.z = radius * Math.cos( u * Math.PI * 2 );
  18541. this.vertices.push( vertex );
  18542. verticesRow.push( this.vertices.length - 1 );
  18543. uvsRow.push( new THREE.UV( u, 1 - v ) );
  18544. }
  18545. vertices.push( verticesRow );
  18546. uvs.push( uvsRow );
  18547. }
  18548. var tanTheta = ( radiusBottom - radiusTop ) / height;
  18549. var na, nb;
  18550. for ( x = 0; x < segmentsX; x ++ ) {
  18551. if ( radiusTop !== 0 ) {
  18552. na = this.vertices[ vertices[ 0 ][ x ] ].clone();
  18553. nb = this.vertices[ vertices[ 0 ][ x + 1 ] ].clone();
  18554. } else {
  18555. na = this.vertices[ vertices[ 1 ][ x ] ].clone();
  18556. nb = this.vertices[ vertices[ 1 ][ x + 1 ] ].clone();
  18557. }
  18558. na.setY( Math.sqrt( na.x * na.x + na.z * na.z ) * tanTheta ).normalize();
  18559. nb.setY( Math.sqrt( nb.x * nb.x + nb.z * nb.z ) * tanTheta ).normalize();
  18560. for ( y = 0; y < segmentsY; y ++ ) {
  18561. var v1 = vertices[ y ][ x ];
  18562. var v2 = vertices[ y + 1 ][ x ];
  18563. var v3 = vertices[ y + 1 ][ x + 1 ];
  18564. var v4 = vertices[ y ][ x + 1 ];
  18565. var n1 = na.clone();
  18566. var n2 = na.clone();
  18567. var n3 = nb.clone();
  18568. var n4 = nb.clone();
  18569. var uv1 = uvs[ y ][ x ].clone();
  18570. var uv2 = uvs[ y + 1 ][ x ].clone();
  18571. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  18572. var uv4 = uvs[ y ][ x + 1 ].clone();
  18573. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  18574. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  18575. }
  18576. }
  18577. // top cap
  18578. if ( !openEnded && radiusTop > 0 ) {
  18579. this.vertices.push( new THREE.Vector3( 0, heightHalf, 0 ) );
  18580. for ( x = 0; x < segmentsX; x ++ ) {
  18581. var v1 = vertices[ 0 ][ x ];
  18582. var v2 = vertices[ 0 ][ x + 1 ];
  18583. var v3 = this.vertices.length - 1;
  18584. var n1 = new THREE.Vector3( 0, 1, 0 );
  18585. var n2 = new THREE.Vector3( 0, 1, 0 );
  18586. var n3 = new THREE.Vector3( 0, 1, 0 );
  18587. var uv1 = uvs[ 0 ][ x ].clone();
  18588. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  18589. var uv3 = new THREE.UV( uv2.u, 0 );
  18590. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18591. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18592. }
  18593. }
  18594. // bottom cap
  18595. if ( !openEnded && radiusBottom > 0 ) {
  18596. this.vertices.push( new THREE.Vector3( 0, - heightHalf, 0 ) );
  18597. for ( x = 0; x < segmentsX; x ++ ) {
  18598. var v1 = vertices[ y ][ x + 1 ];
  18599. var v2 = vertices[ y ][ x ];
  18600. var v3 = this.vertices.length - 1;
  18601. var n1 = new THREE.Vector3( 0, - 1, 0 );
  18602. var n2 = new THREE.Vector3( 0, - 1, 0 );
  18603. var n3 = new THREE.Vector3( 0, - 1, 0 );
  18604. var uv1 = uvs[ y ][ x + 1 ].clone();
  18605. var uv2 = uvs[ y ][ x ].clone();
  18606. var uv3 = new THREE.UV( uv2.u, 1 );
  18607. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  18608. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  18609. }
  18610. }
  18611. this.computeCentroids();
  18612. this.computeFaceNormals();
  18613. }
  18614. THREE.CylinderGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18615. /**
  18616. * @author zz85 / http://www.lab4games.net/zz85/blog
  18617. *
  18618. * Creates extruded geometry from a path shape.
  18619. *
  18620. * parameters = {
  18621. *
  18622. * size: <float>, // size of the text
  18623. * height: <float>, // thickness to extrude text
  18624. * curveSegments: <int>, // number of points on the curves
  18625. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  18626. * amount: <int>, // Amount
  18627. *
  18628. * bevelEnabled: <bool>, // turn on bevel
  18629. * bevelThickness: <float>, // how deep into text bevel goes
  18630. * bevelSize: <float>, // how far from text outline is bevel
  18631. * bevelSegments: <int>, // number of bevel layers
  18632. *
  18633. * extrudePath: <THREE.CurvePath> // 3d spline path to extrude shape along. (creates Frames if .frames aren't defined)
  18634. * frames: <THREE.TubeGeometry.FrenetFrames> // containing arrays of tangents, normals, binormals
  18635. *
  18636. * material: <int> // material index for front and back faces
  18637. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  18638. * uvGenerator: <Object> // object that provides UV generator functions
  18639. *
  18640. * }
  18641. **/
  18642. THREE.ExtrudeGeometry = function ( shapes, options ) {
  18643. if ( typeof( shapes ) === "undefined" ) {
  18644. shapes = [];
  18645. return;
  18646. }
  18647. THREE.Geometry.call( this );
  18648. shapes = shapes instanceof Array ? shapes : [ shapes ];
  18649. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  18650. this.addShapeList( shapes, options );
  18651. this.computeCentroids();
  18652. this.computeFaceNormals();
  18653. // can't really use automatic vertex normals
  18654. // as then front and back sides get smoothed too
  18655. // should do separate smoothing just for sides
  18656. //this.computeVertexNormals();
  18657. //console.log( "took", ( Date.now() - startTime ) );
  18658. };
  18659. THREE.ExtrudeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  18660. THREE.ExtrudeGeometry.prototype.addShapeList = function ( shapes, options ) {
  18661. var sl = shapes.length;
  18662. for ( var s = 0; s < sl; s ++ ) {
  18663. var shape = shapes[ s ];
  18664. this.addShape( shape, options );
  18665. }
  18666. };
  18667. THREE.ExtrudeGeometry.prototype.addShape = function ( shape, options ) {
  18668. var amount = options.amount !== undefined ? options.amount : 100;
  18669. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  18670. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  18671. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  18672. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  18673. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  18674. var steps = options.steps !== undefined ? options.steps : 1;
  18675. var extrudePath = options.extrudePath;
  18676. var extrudePts, extrudeByPath = false;
  18677. var material = options.material;
  18678. var extrudeMaterial = options.extrudeMaterial;
  18679. // Use default WorldUVGenerator if no UV generators are specified.
  18680. var uvgen = options.UVGenerator !== undefined ? options.UVGenerator : THREE.ExtrudeGeometry.WorldUVGenerator;
  18681. var shapebb = this.shapebb;
  18682. //shapebb = shape.getBoundingBox();
  18683. var splineTube, binormal, normal, position2;
  18684. if ( extrudePath ) {
  18685. extrudePts = extrudePath.getSpacedPoints( steps );
  18686. extrudeByPath = true;
  18687. bevelEnabled = false; // bevels not supported for path extrusion
  18688. // SETUP TNB variables
  18689. // Reuse TNB from TubeGeomtry for now.
  18690. // TODO1 - have a .isClosed in spline?
  18691. splineTube = options.frames !== undefined ? options.frames : new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  18692. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  18693. binormal = new THREE.Vector3();
  18694. normal = new THREE.Vector3();
  18695. position2 = new THREE.Vector3();
  18696. }
  18697. // Safeguards if bevels are not enabled
  18698. if ( ! bevelEnabled ) {
  18699. bevelSegments = 0;
  18700. bevelThickness = 0;
  18701. bevelSize = 0;
  18702. }
  18703. // Variables initalization
  18704. var ahole, h, hl; // looping of holes
  18705. var scope = this;
  18706. var bevelPoints = [];
  18707. var shapesOffset = this.vertices.length;
  18708. var shapePoints = shape.extractPoints( curveSegments );
  18709. var vertices = shapePoints.shape;
  18710. var holes = shapePoints.holes;
  18711. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  18712. if ( reverse ) {
  18713. vertices = vertices.reverse();
  18714. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  18715. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18716. ahole = holes[ h ];
  18717. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  18718. holes[ h ] = ahole.reverse();
  18719. }
  18720. }
  18721. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  18722. }
  18723. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  18724. /* Vertices */
  18725. var contour = vertices; // vertices has all points but contour has only points of circumference
  18726. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18727. ahole = holes[ h ];
  18728. vertices = vertices.concat( ahole );
  18729. }
  18730. function scalePt2 ( pt, vec, size ) {
  18731. if ( !vec ) console.log( "die" );
  18732. return vec.clone().multiplyScalar( size ).addSelf( pt );
  18733. }
  18734. var b, bs, t, z,
  18735. vert, vlen = vertices.length,
  18736. face, flen = faces.length,
  18737. cont, clen = contour.length;
  18738. // Find directions for point movement
  18739. var RAD_TO_DEGREES = 180 / Math.PI;
  18740. function getBevelVec( pt_i, pt_j, pt_k ) {
  18741. // Algorithm 2
  18742. return getBevelVec2( pt_i, pt_j, pt_k );
  18743. }
  18744. function getBevelVec1( pt_i, pt_j, pt_k ) {
  18745. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  18746. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  18747. if ( anglea > angleb ) {
  18748. angleb += Math.PI * 2;
  18749. }
  18750. var anglec = ( anglea + angleb ) / 2;
  18751. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  18752. var x = - Math.cos( anglec );
  18753. var y = - Math.sin( anglec );
  18754. var vec = new THREE.Vector2( x, y ); //.normalize();
  18755. return vec;
  18756. }
  18757. function getBevelVec2( pt_i, pt_j, pt_k ) {
  18758. var a = THREE.ExtrudeGeometry.__v1,
  18759. b = THREE.ExtrudeGeometry.__v2,
  18760. v_hat = THREE.ExtrudeGeometry.__v3,
  18761. w_hat = THREE.ExtrudeGeometry.__v4,
  18762. p = THREE.ExtrudeGeometry.__v5,
  18763. q = THREE.ExtrudeGeometry.__v6,
  18764. v, w,
  18765. v_dot_w_hat, q_sub_p_dot_w_hat,
  18766. s, intersection;
  18767. // good reading for line-line intersection
  18768. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  18769. // define a as vector j->i
  18770. // define b as vectot k->i
  18771. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  18772. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  18773. // get unit vectors
  18774. v = a.normalize();
  18775. w = b.normalize();
  18776. // normals from pt i
  18777. v_hat.set( -v.y, v.x );
  18778. w_hat.set( w.y, -w.x );
  18779. // pts from i
  18780. p.copy( pt_i ).addSelf( v_hat );
  18781. q.copy( pt_i ).addSelf( w_hat );
  18782. if ( p.equals( q ) ) {
  18783. //console.log("Warning: lines are straight");
  18784. return w_hat.clone();
  18785. }
  18786. // Points from j, k. helps prevents points cross overover most of the time
  18787. p.copy( pt_j ).addSelf( v_hat );
  18788. q.copy( pt_k ).addSelf( w_hat );
  18789. v_dot_w_hat = v.dot( w_hat );
  18790. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  18791. // We should not reach these conditions
  18792. if ( v_dot_w_hat === 0 ) {
  18793. console.log( "Either infinite or no solutions!" );
  18794. if ( q_sub_p_dot_w_hat === 0 ) {
  18795. console.log( "Its finite solutions." );
  18796. } else {
  18797. console.log( "Too bad, no solutions." );
  18798. }
  18799. }
  18800. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  18801. if ( s < 0 ) {
  18802. // in case of emergecy, revert to algorithm 1.
  18803. return getBevelVec1( pt_i, pt_j, pt_k );
  18804. }
  18805. intersection = v.multiplyScalar( s ).addSelf( p );
  18806. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  18807. }
  18808. var contourMovements = [];
  18809. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18810. if ( j === il ) j = 0;
  18811. if ( k === il ) k = 0;
  18812. // (j)---(i)---(k)
  18813. // console.log('i,j,k', i, j , k)
  18814. var pt_i = contour[ i ];
  18815. var pt_j = contour[ j ];
  18816. var pt_k = contour[ k ];
  18817. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  18818. }
  18819. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  18820. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18821. ahole = holes[ h ];
  18822. oneHoleMovements = [];
  18823. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  18824. if ( j === il ) j = 0;
  18825. if ( k === il ) k = 0;
  18826. // (j)---(i)---(k)
  18827. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  18828. }
  18829. holesMovements.push( oneHoleMovements );
  18830. verticesMovements = verticesMovements.concat( oneHoleMovements );
  18831. }
  18832. // Loop bevelSegments, 1 for the front, 1 for the back
  18833. for ( b = 0; b < bevelSegments; b ++ ) {
  18834. //for ( b = bevelSegments; b > 0; b -- ) {
  18835. t = b / bevelSegments;
  18836. z = bevelThickness * ( 1 - t );
  18837. //z = bevelThickness * t;
  18838. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  18839. //bs = bevelSize * t ; // linear
  18840. // contract shape
  18841. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18842. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18843. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  18844. v( vert.x, vert.y, - z );
  18845. }
  18846. // expand holes
  18847. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  18848. ahole = holes[ h ];
  18849. oneHoleMovements = holesMovements[ h ];
  18850. for ( i = 0, il = ahole.length; i < il; i++ ) {
  18851. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18852. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  18853. v( vert.x, vert.y, -z );
  18854. }
  18855. }
  18856. }
  18857. bs = bevelSize;
  18858. // Back facing vertices
  18859. for ( i = 0; i < vlen; i ++ ) {
  18860. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18861. if ( !extrudeByPath ) {
  18862. v( vert.x, vert.y, 0 );
  18863. } else {
  18864. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  18865. normal.copy( splineTube.normals[0] ).multiplyScalar(vert.x);
  18866. binormal.copy( splineTube.binormals[0] ).multiplyScalar(vert.y);
  18867. position2.copy( extrudePts[0] ).addSelf(normal).addSelf(binormal);
  18868. v( position2.x, position2.y, position2.z );
  18869. }
  18870. }
  18871. // Add stepped vertices...
  18872. // Including front facing vertices
  18873. var s;
  18874. for ( s = 1; s <= steps; s ++ ) {
  18875. for ( i = 0; i < vlen; i ++ ) {
  18876. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  18877. if ( !extrudeByPath ) {
  18878. v( vert.x, vert.y, amount / steps * s );
  18879. } else {
  18880. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  18881. normal.copy( splineTube.normals[s] ).multiplyScalar( vert.x );
  18882. binormal.copy( splineTube.binormals[s] ).multiplyScalar( vert.y );
  18883. position2.copy( extrudePts[s] ).addSelf( normal ).addSelf( binormal );
  18884. v( position2.x, position2.y, position2.z );
  18885. }
  18886. }
  18887. }
  18888. // Add bevel segments planes
  18889. //for ( b = 1; b <= bevelSegments; b ++ ) {
  18890. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  18891. t = b / bevelSegments;
  18892. z = bevelThickness * ( 1 - t );
  18893. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  18894. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  18895. // contract shape
  18896. for ( i = 0, il = contour.length; i < il; i ++ ) {
  18897. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  18898. v( vert.x, vert.y, amount + z );
  18899. }
  18900. // expand holes
  18901. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18902. ahole = holes[ h ];
  18903. oneHoleMovements = holesMovements[ h ];
  18904. for ( i = 0, il = ahole.length; i < il; i ++ ) {
  18905. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  18906. if ( !extrudeByPath ) {
  18907. v( vert.x, vert.y, amount + z );
  18908. } else {
  18909. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  18910. }
  18911. }
  18912. }
  18913. }
  18914. /* Faces */
  18915. // Top and bottom faces
  18916. buildLidFaces();
  18917. // Sides faces
  18918. buildSideFaces();
  18919. ///// Internal functions
  18920. function buildLidFaces() {
  18921. if ( bevelEnabled ) {
  18922. var layer = 0 ; // steps + 1
  18923. var offset = vlen * layer;
  18924. // Bottom faces
  18925. for ( i = 0; i < flen; i ++ ) {
  18926. face = faces[ i ];
  18927. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  18928. }
  18929. layer = steps + bevelSegments * 2;
  18930. offset = vlen * layer;
  18931. // Top faces
  18932. for ( i = 0; i < flen; i ++ ) {
  18933. face = faces[ i ];
  18934. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  18935. }
  18936. } else {
  18937. // Bottom faces
  18938. for ( i = 0; i < flen; i++ ) {
  18939. face = faces[ i ];
  18940. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  18941. }
  18942. // Top faces
  18943. for ( i = 0; i < flen; i ++ ) {
  18944. face = faces[ i ];
  18945. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  18946. }
  18947. }
  18948. }
  18949. // Create faces for the z-sides of the shape
  18950. function buildSideFaces() {
  18951. var layeroffset = 0;
  18952. sidewalls( contour, layeroffset );
  18953. layeroffset += contour.length;
  18954. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  18955. ahole = holes[ h ];
  18956. sidewalls( ahole, layeroffset );
  18957. //, true
  18958. layeroffset += ahole.length;
  18959. }
  18960. }
  18961. function sidewalls( contour, layeroffset ) {
  18962. var j, k;
  18963. i = contour.length;
  18964. while ( --i >= 0 ) {
  18965. j = i;
  18966. k = i - 1;
  18967. if ( k < 0 ) k = contour.length - 1;
  18968. //console.log('b', i,j, i-1, k,vertices.length);
  18969. var s = 0, sl = steps + bevelSegments * 2;
  18970. for ( s = 0; s < sl; s ++ ) {
  18971. var slen1 = vlen * s;
  18972. var slen2 = vlen * ( s + 1 );
  18973. var a = layeroffset + j + slen1,
  18974. b = layeroffset + k + slen1,
  18975. c = layeroffset + k + slen2,
  18976. d = layeroffset + j + slen2;
  18977. f4( a, b, c, d, contour, s, sl, j, k );
  18978. }
  18979. }
  18980. }
  18981. function v( x, y, z ) {
  18982. scope.vertices.push( new THREE.Vector3( x, y, z ) );
  18983. }
  18984. function f3( a, b, c, isBottom ) {
  18985. a += shapesOffset;
  18986. b += shapesOffset;
  18987. c += shapesOffset;
  18988. // normal, color, material
  18989. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  18990. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c ) : uvgen.generateTopUV( scope, shape, options, a, b, c );
  18991. scope.faceVertexUvs[ 0 ].push( uvs );
  18992. }
  18993. function f4( a, b, c, d, wallContour, stepIndex, stepsLength, contourIndex1, contourIndex2 ) {
  18994. a += shapesOffset;
  18995. b += shapesOffset;
  18996. c += shapesOffset;
  18997. d += shapesOffset;
  18998. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  18999. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d,
  19000. stepIndex, stepsLength, contourIndex1, contourIndex2 );
  19001. scope.faceVertexUvs[ 0 ].push( uvs );
  19002. }
  19003. };
  19004. THREE.ExtrudeGeometry.WorldUVGenerator = {
  19005. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19006. var ax = geometry.vertices[ indexA ].x,
  19007. ay = geometry.vertices[ indexA ].y,
  19008. bx = geometry.vertices[ indexB ].x,
  19009. by = geometry.vertices[ indexB ].y,
  19010. cx = geometry.vertices[ indexC ].x,
  19011. cy = geometry.vertices[ indexC ].y;
  19012. return [
  19013. new THREE.UV( ax, ay ),
  19014. new THREE.UV( bx, by ),
  19015. new THREE.UV( cx, cy )
  19016. ];
  19017. },
  19018. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC ) {
  19019. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  19020. },
  19021. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  19022. indexA, indexB, indexC, indexD, stepIndex, stepsLength,
  19023. contourIndex1, contourIndex2 ) {
  19024. var ax = geometry.vertices[ indexA ].x,
  19025. ay = geometry.vertices[ indexA ].y,
  19026. az = geometry.vertices[ indexA ].z,
  19027. bx = geometry.vertices[ indexB ].x,
  19028. by = geometry.vertices[ indexB ].y,
  19029. bz = geometry.vertices[ indexB ].z,
  19030. cx = geometry.vertices[ indexC ].x,
  19031. cy = geometry.vertices[ indexC ].y,
  19032. cz = geometry.vertices[ indexC ].z,
  19033. dx = geometry.vertices[ indexD ].x,
  19034. dy = geometry.vertices[ indexD ].y,
  19035. dz = geometry.vertices[ indexD ].z;
  19036. if ( Math.abs( ay - by ) < 0.01 ) {
  19037. return [
  19038. new THREE.UV( ax, 1 - az ),
  19039. new THREE.UV( bx, 1 - bz ),
  19040. new THREE.UV( cx, 1 - cz ),
  19041. new THREE.UV( dx, 1 - dz )
  19042. ];
  19043. } else {
  19044. return [
  19045. new THREE.UV( ay, 1 - az ),
  19046. new THREE.UV( by, 1 - bz ),
  19047. new THREE.UV( cy, 1 - cz ),
  19048. new THREE.UV( dy, 1 - dz )
  19049. ];
  19050. }
  19051. }
  19052. };
  19053. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  19054. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  19055. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  19056. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  19057. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  19058. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  19059. /**
  19060. * @author jonobr1 / http://jonobr1.com
  19061. *
  19062. * Creates a one-sided polygonal geometry from a path shape. Similar to
  19063. * ExtrudeGeometry.
  19064. *
  19065. * parameters = {
  19066. *
  19067. * curveSegments: <int>, // number of points on the curves. NOT USED AT THE MOMENT.
  19068. *
  19069. * material: <int> // material index for front and back faces
  19070. * uvGenerator: <Object> // object that provides UV generator functions
  19071. *
  19072. * }
  19073. **/
  19074. THREE.ShapeGeometry = function ( shapes, options ) {
  19075. THREE.Geometry.call( this );
  19076. if ( shapes instanceof Array === false ) shapes = [ shapes ];
  19077. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  19078. this.addShapeList( shapes, options );
  19079. this.computeCentroids();
  19080. this.computeFaceNormals();
  19081. };
  19082. THREE.ShapeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19083. /**
  19084. * Add an array of shapes to THREE.ShapeGeometry.
  19085. */
  19086. THREE.ShapeGeometry.prototype.addShapeList = function ( shapes, options ) {
  19087. for ( var i = 0, l = shapes.length; i < l; i++ ) {
  19088. this.addShape( shapes[ i ], options );
  19089. }
  19090. return this;
  19091. };
  19092. /**
  19093. * Adds a shape to THREE.ShapeGeometry, based on THREE.ExtrudeGeometry.
  19094. */
  19095. THREE.ShapeGeometry.prototype.addShape = function ( shape, options ) {
  19096. if ( options === undefined ) options = {};
  19097. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  19098. var material = options.material;
  19099. var uvgen = options.UVGenerator === undefined ? THREE.ExtrudeGeometry.WorldUVGenerator : options.UVGenerator;
  19100. var shapebb = this.shapebb;
  19101. //
  19102. var i, l, hole, s;
  19103. var shapesOffset = this.vertices.length;
  19104. var shapePoints = shape.extractPoints( curveSegments );
  19105. var vertices = shapePoints.shape;
  19106. var holes = shapePoints.holes;
  19107. var reverse = !THREE.Shape.Utils.isClockWise( vertices );
  19108. if ( reverse ) {
  19109. vertices = vertices.reverse();
  19110. // Maybe we should also check if holes are in the opposite direction, just to be safe...
  19111. for ( i = 0, l = holes.length; i < l; i++ ) {
  19112. hole = holes[ i ];
  19113. if ( THREE.Shape.Utils.isClockWise( hole ) ) {
  19114. holes[ i ] = hole.reverse();
  19115. }
  19116. }
  19117. reverse = false;
  19118. }
  19119. var faces = THREE.Shape.Utils.triangulateShape( vertices, holes );
  19120. // Vertices
  19121. var contour = vertices;
  19122. for ( i = 0, l = holes.length; i < l; i++ ) {
  19123. hole = holes[ i ];
  19124. vertices = vertices.concat( hole );
  19125. }
  19126. //
  19127. var vert, vlen = vertices.length;
  19128. var face, flen = faces.length;
  19129. var cont, clen = contour.length;
  19130. for ( i = 0; i < vlen; i++ ) {
  19131. vert = vertices[ i ];
  19132. this.vertices.push( new THREE.Vector3( vert.x, vert.y, 0 ) );
  19133. }
  19134. for ( i = 0; i < flen; i++ ) {
  19135. face = faces[ i ];
  19136. var a = face[ 0 ] + shapesOffset;
  19137. var b = face[ 1 ] + shapesOffset;
  19138. var c = face[ 2 ] + shapesOffset;
  19139. this.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  19140. this.faceVertexUvs[ 0 ].push( uvgen.generateBottomUV( this, shape, options, a, b, c ) );
  19141. }
  19142. };
  19143. /**
  19144. * @author astrodud / http://astrodud.isgreat.org/
  19145. * @author zz85 / https://github.com/zz85
  19146. */
  19147. THREE.LatheGeometry = function ( points, steps, angle ) {
  19148. THREE.Geometry.call( this );
  19149. var _steps = steps || 12;
  19150. var _angle = angle || 2 * Math.PI;
  19151. var _newV = [];
  19152. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  19153. for ( var j = 0; j < points.length; j ++ ) {
  19154. _newV[ j ] = points[ j ].clone();
  19155. this.vertices.push( _newV[ j ] );
  19156. }
  19157. var i, il = _steps + 1;
  19158. for ( i = 0; i < il; i ++ ) {
  19159. for ( var j = 0; j < _newV.length; j ++ ) {
  19160. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  19161. this.vertices.push( _newV[ j ] );
  19162. }
  19163. }
  19164. for ( i = 0; i < _steps; i ++ ) {
  19165. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  19166. var a = i * kl + k;
  19167. var b = ( ( i + 1 ) % il ) * kl + k;
  19168. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  19169. var d = i * kl + ( k + 1 ) % kl;
  19170. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19171. this.faceVertexUvs[ 0 ].push( [
  19172. new THREE.UV( 1 - i / _steps, k / kl ),
  19173. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  19174. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  19175. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  19176. ] );
  19177. }
  19178. }
  19179. this.computeCentroids();
  19180. this.computeFaceNormals();
  19181. this.computeVertexNormals();
  19182. };
  19183. THREE.LatheGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19184. /**
  19185. * @author mrdoob / http://mrdoob.com/
  19186. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  19187. */
  19188. THREE.PlaneGeometry = function ( width, height, widthSegments, heightSegments ) {
  19189. THREE.Geometry.call( this );
  19190. this.width = width;
  19191. this.height = height;
  19192. this.widthSegments = widthSegments || 1;
  19193. this.heightSegments = heightSegments || 1;
  19194. var ix, iz;
  19195. var width_half = width / 2;
  19196. var height_half = height / 2;
  19197. var gridX = this.widthSegments;
  19198. var gridZ = this.heightSegments;
  19199. var gridX1 = gridX + 1;
  19200. var gridZ1 = gridZ + 1;
  19201. var segment_width = this.width / gridX;
  19202. var segment_height = this.height / gridZ;
  19203. var normal = new THREE.Vector3( 0, 0, 1 );
  19204. for ( iz = 0; iz < gridZ1; iz ++ ) {
  19205. for ( ix = 0; ix < gridX1; ix ++ ) {
  19206. var x = ix * segment_width - width_half;
  19207. var y = iz * segment_height - height_half;
  19208. this.vertices.push( new THREE.Vector3( x, - y, 0 ) );
  19209. }
  19210. }
  19211. for ( iz = 0; iz < gridZ; iz ++ ) {
  19212. for ( ix = 0; ix < gridX; ix ++ ) {
  19213. var a = ix + gridX1 * iz;
  19214. var b = ix + gridX1 * ( iz + 1 );
  19215. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  19216. var d = ( ix + 1 ) + gridX1 * iz;
  19217. var face = new THREE.Face4( a, b, c, d );
  19218. face.normal.copy( normal );
  19219. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  19220. this.faces.push( face );
  19221. this.faceVertexUvs[ 0 ].push( [
  19222. new THREE.UV( ix / gridX, 1 - iz / gridZ ),
  19223. new THREE.UV( ix / gridX, 1 - ( iz + 1 ) / gridZ ),
  19224. new THREE.UV( ( ix + 1 ) / gridX, 1 - ( iz + 1 ) / gridZ ),
  19225. new THREE.UV( ( ix + 1 ) / gridX, 1 - iz / gridZ )
  19226. ] );
  19227. }
  19228. }
  19229. this.computeCentroids();
  19230. };
  19231. THREE.PlaneGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19232. /**
  19233. * @author mrdoob / http://mrdoob.com/
  19234. */
  19235. THREE.SphereGeometry = function ( radius, widthSegments, heightSegments, phiStart, phiLength, thetaStart, thetaLength ) {
  19236. THREE.Geometry.call( this );
  19237. this.radius = radius || 50;
  19238. this.widthSegments = Math.max( 3, Math.floor( widthSegments ) || 8 );
  19239. this.heightSegments = Math.max( 2, Math.floor( heightSegments ) || 6 );
  19240. phiStart = phiStart !== undefined ? phiStart : 0;
  19241. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  19242. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  19243. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  19244. var x, y, vertices = [], uvs = [];
  19245. for ( y = 0; y <= this.heightSegments; y ++ ) {
  19246. var verticesRow = [];
  19247. var uvsRow = [];
  19248. for ( x = 0; x <= this.widthSegments; x ++ ) {
  19249. var u = x / this.widthSegments;
  19250. var v = y / this.heightSegments;
  19251. var vertex = new THREE.Vector3();
  19252. vertex.x = - this.radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19253. vertex.y = this.radius * Math.cos( thetaStart + v * thetaLength );
  19254. vertex.z = this.radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  19255. this.vertices.push( vertex );
  19256. verticesRow.push( this.vertices.length - 1 );
  19257. uvsRow.push( new THREE.UV( u, 1 - v ) );
  19258. }
  19259. vertices.push( verticesRow );
  19260. uvs.push( uvsRow );
  19261. }
  19262. for ( y = 0; y < this.heightSegments; y ++ ) {
  19263. for ( x = 0; x < this.widthSegments; x ++ ) {
  19264. var v1 = vertices[ y ][ x + 1 ];
  19265. var v2 = vertices[ y ][ x ];
  19266. var v3 = vertices[ y + 1 ][ x ];
  19267. var v4 = vertices[ y + 1 ][ x + 1 ];
  19268. var n1 = this.vertices[ v1 ].clone().normalize();
  19269. var n2 = this.vertices[ v2 ].clone().normalize();
  19270. var n3 = this.vertices[ v3 ].clone().normalize();
  19271. var n4 = this.vertices[ v4 ].clone().normalize();
  19272. var uv1 = uvs[ y ][ x + 1 ].clone();
  19273. var uv2 = uvs[ y ][ x ].clone();
  19274. var uv3 = uvs[ y + 1 ][ x ].clone();
  19275. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  19276. if ( Math.abs( this.vertices[ v1 ].y ) === this.radius ) {
  19277. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  19278. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  19279. } else if ( Math.abs( this.vertices[ v3 ].y ) === this.radius ) {
  19280. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  19281. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  19282. } else {
  19283. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  19284. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  19285. }
  19286. }
  19287. }
  19288. this.computeCentroids();
  19289. this.computeFaceNormals();
  19290. this.boundingSphere = { radius: this.radius };
  19291. };
  19292. THREE.SphereGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19293. /**
  19294. * @author zz85 / http://www.lab4games.net/zz85/blog
  19295. * @author alteredq / http://alteredqualia.com/
  19296. *
  19297. * For creating 3D text geometry in three.js
  19298. *
  19299. * Text = 3D Text
  19300. *
  19301. * parameters = {
  19302. * size: <float>, // size of the text
  19303. * height: <float>, // thickness to extrude text
  19304. * curveSegments: <int>, // number of points on the curves
  19305. *
  19306. * font: <string>, // font name
  19307. * weight: <string>, // font weight (normal, bold)
  19308. * style: <string>, // font style (normal, italics)
  19309. *
  19310. * bevelEnabled: <bool>, // turn on bevel
  19311. * bevelThickness: <float>, // how deep into text bevel goes
  19312. * bevelSize: <float>, // how far from text outline is bevel
  19313. * }
  19314. *
  19315. */
  19316. /* Usage Examples
  19317. // TextGeometry wrapper
  19318. var text3d = new TextGeometry( text, options );
  19319. // Complete manner
  19320. var textShapes = THREE.FontUtils.generateShapes( text, options );
  19321. var text3d = new ExtrudeGeometry( textShapes, options );
  19322. */
  19323. THREE.TextGeometry = function ( text, parameters ) {
  19324. var textShapes = THREE.FontUtils.generateShapes( text, parameters );
  19325. // translate parameters to ExtrudeGeometry API
  19326. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  19327. // defaults
  19328. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  19329. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  19330. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  19331. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  19332. };
  19333. THREE.TextGeometry.prototype = Object.create( THREE.ExtrudeGeometry.prototype );
  19334. /**
  19335. * @author oosmoxiecode
  19336. * @author mrdoob / http://mrdoob.com/
  19337. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  19338. */
  19339. THREE.TorusGeometry = function ( radius, tube, radialSegments, tubularSegments, arc ) {
  19340. THREE.Geometry.call( this );
  19341. var scope = this;
  19342. this.radius = radius || 100;
  19343. this.tube = tube || 40;
  19344. this.radialSegments = radialSegments || 8;
  19345. this.tubularSegments = tubularSegments || 6;
  19346. this.arc = arc || Math.PI * 2;
  19347. var center = new THREE.Vector3(), uvs = [], normals = [];
  19348. for ( var j = 0; j <= this.radialSegments; j ++ ) {
  19349. for ( var i = 0; i <= this.tubularSegments; i ++ ) {
  19350. var u = i / this.tubularSegments * this.arc;
  19351. var v = j / this.radialSegments * Math.PI * 2;
  19352. center.x = this.radius * Math.cos( u );
  19353. center.y = this.radius * Math.sin( u );
  19354. var vertex = new THREE.Vector3();
  19355. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  19356. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  19357. vertex.z = this.tube * Math.sin( v );
  19358. this.vertices.push( vertex );
  19359. uvs.push( new THREE.UV( i / this.tubularSegments, j / this.radialSegments ) );
  19360. normals.push( vertex.clone().subSelf( center ).normalize() );
  19361. }
  19362. }
  19363. for ( var j = 1; j <= this.radialSegments; j ++ ) {
  19364. for ( var i = 1; i <= this.tubularSegments; i ++ ) {
  19365. var a = ( this.tubularSegments + 1 ) * j + i - 1;
  19366. var b = ( this.tubularSegments + 1 ) * ( j - 1 ) + i - 1;
  19367. var c = ( this.tubularSegments + 1 ) * ( j - 1 ) + i;
  19368. var d = ( this.tubularSegments + 1 ) * j + i;
  19369. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  19370. face.normal.addSelf( normals[ a ] );
  19371. face.normal.addSelf( normals[ b ] );
  19372. face.normal.addSelf( normals[ c ] );
  19373. face.normal.addSelf( normals[ d ] );
  19374. face.normal.normalize();
  19375. this.faces.push( face );
  19376. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  19377. }
  19378. }
  19379. this.computeCentroids();
  19380. };
  19381. THREE.TorusGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19382. /**
  19383. * @author oosmoxiecode
  19384. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  19385. */
  19386. THREE.TorusKnotGeometry = function ( radius, tube, radialSegments, tubularSegments, p, q, heightScale ) {
  19387. THREE.Geometry.call( this );
  19388. var scope = this;
  19389. this.radius = radius || 200;
  19390. this.tube = tube || 40;
  19391. this.radialSegments = radialSegments || 64;
  19392. this.tubularSegments = tubularSegments || 8;
  19393. this.p = p || 2;
  19394. this.q = q || 3;
  19395. this.heightScale = heightScale || 1;
  19396. this.grid = new Array(this.radialSegments);
  19397. var tang = new THREE.Vector3();
  19398. var n = new THREE.Vector3();
  19399. var bitan = new THREE.Vector3();
  19400. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19401. this.grid[ i ] = new Array( this.tubularSegments );
  19402. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19403. var u = i / this.radialSegments * 2 * this.p * Math.PI;
  19404. var v = j / this.tubularSegments * 2 * Math.PI;
  19405. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  19406. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  19407. var cx, cy;
  19408. tang.sub( p2, p1 );
  19409. n.add( p2, p1 );
  19410. bitan.cross( tang, n );
  19411. n.cross( bitan, tang );
  19412. bitan.normalize();
  19413. n.normalize();
  19414. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19415. cy = this.tube * Math.sin( v );
  19416. p1.x += cx * n.x + cy * bitan.x;
  19417. p1.y += cx * n.y + cy * bitan.y;
  19418. p1.z += cx * n.z + cy * bitan.z;
  19419. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  19420. }
  19421. }
  19422. for ( var i = 0; i < this.radialSegments; ++ i ) {
  19423. for ( var j = 0; j < this.tubularSegments; ++ j ) {
  19424. var ip = ( i + 1 ) % this.radialSegments;
  19425. var jp = ( j + 1 ) % this.tubularSegments;
  19426. var a = this.grid[ i ][ j ];
  19427. var b = this.grid[ ip ][ j ];
  19428. var c = this.grid[ ip ][ jp ];
  19429. var d = this.grid[ i ][ jp ];
  19430. var uva = new THREE.UV( i / this.radialSegments, j / this.tubularSegments );
  19431. var uvb = new THREE.UV( ( i + 1 ) / this.radialSegments, j / this.tubularSegments );
  19432. var uvc = new THREE.UV( ( i + 1 ) / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19433. var uvd = new THREE.UV( i / this.radialSegments, ( j + 1 ) / this.tubularSegments );
  19434. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19435. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  19436. }
  19437. }
  19438. this.computeCentroids();
  19439. this.computeFaceNormals();
  19440. this.computeVertexNormals();
  19441. function vert( x, y, z ) {
  19442. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19443. }
  19444. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  19445. var cu = Math.cos( u );
  19446. var cv = Math.cos( v );
  19447. var su = Math.sin( u );
  19448. var quOverP = in_q / in_p * u;
  19449. var cs = Math.cos( quOverP );
  19450. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  19451. var ty = radius * ( 2 + cs ) * su * 0.5;
  19452. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  19453. return new THREE.Vector3( tx, ty, tz );
  19454. }
  19455. };
  19456. THREE.TorusKnotGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19457. /**
  19458. * @author WestLangley / https://github.com/WestLangley
  19459. * @author zz85 / https://github.com/zz85
  19460. * @author miningold / https://github.com/miningold
  19461. *
  19462. * Modified from the TorusKnotGeometry by @oosmoxiecode
  19463. *
  19464. * Creates a tube which extrudes along a 3d spline
  19465. *
  19466. * Uses parallel transport frames as described in
  19467. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  19468. */
  19469. THREE.TubeGeometry = function( path, segments, radius, radiusSegments, closed, debug ) {
  19470. THREE.Geometry.call( this );
  19471. this.path = path;
  19472. this.segments = segments || 64;
  19473. this.radius = radius || 1;
  19474. this.radiusSegments = radiusSegments || 8;
  19475. this.closed = closed || false;
  19476. if ( debug ) this.debug = new THREE.Object3D();
  19477. this.grid = [];
  19478. var scope = this,
  19479. tangent,
  19480. normal,
  19481. binormal,
  19482. numpoints = this.segments + 1,
  19483. x, y, z,
  19484. tx, ty, tz,
  19485. u, v,
  19486. cx, cy,
  19487. pos, pos2 = new THREE.Vector3(),
  19488. i, j,
  19489. ip, jp,
  19490. a, b, c, d,
  19491. uva, uvb, uvc, uvd;
  19492. var frames = new THREE.TubeGeometry.FrenetFrames( this.path, this.segments, this.closed ),
  19493. tangents = frames.tangents,
  19494. normals = frames.normals,
  19495. binormals = frames.binormals;
  19496. // proxy internals
  19497. this.tangents = tangents;
  19498. this.normals = normals;
  19499. this.binormals = binormals;
  19500. function vert( x, y, z ) {
  19501. return scope.vertices.push( new THREE.Vector3( x, y, z ) ) - 1;
  19502. }
  19503. // consruct the grid
  19504. for ( i = 0; i < numpoints; i++ ) {
  19505. this.grid[ i ] = [];
  19506. u = i / ( numpoints - 1 );
  19507. pos = path.getPointAt( u );
  19508. tangent = tangents[ i ];
  19509. normal = normals[ i ];
  19510. binormal = binormals[ i ];
  19511. if ( this.debug ) {
  19512. this.debug.add( new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff ) );
  19513. this.debug.add( new THREE.ArrowHelper(normal, pos, radius, 0xff0000 ) );
  19514. this.debug.add( new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00 ) );
  19515. }
  19516. for ( j = 0; j < this.radiusSegments; j++ ) {
  19517. v = j / this.radiusSegments * 2 * Math.PI;
  19518. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  19519. cy = this.radius * Math.sin( v );
  19520. pos2.copy( pos );
  19521. pos2.x += cx * normal.x + cy * binormal.x;
  19522. pos2.y += cx * normal.y + cy * binormal.y;
  19523. pos2.z += cx * normal.z + cy * binormal.z;
  19524. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  19525. }
  19526. }
  19527. // construct the mesh
  19528. for ( i = 0; i < this.segments; i++ ) {
  19529. for ( j = 0; j < this.radiusSegments; j++ ) {
  19530. ip = ( this.closed ) ? (i + 1) % this.segments : i + 1;
  19531. jp = (j + 1) % this.radiusSegments;
  19532. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  19533. b = this.grid[ ip ][ j ];
  19534. c = this.grid[ ip ][ jp ];
  19535. d = this.grid[ i ][ jp ];
  19536. uva = new THREE.UV( i / this.segments, j / this.radiusSegments );
  19537. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.radiusSegments );
  19538. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.radiusSegments );
  19539. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.radiusSegments );
  19540. this.faces.push( new THREE.Face4( a, b, c, d ) );
  19541. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  19542. }
  19543. }
  19544. this.computeCentroids();
  19545. this.computeFaceNormals();
  19546. this.computeVertexNormals();
  19547. };
  19548. THREE.TubeGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19549. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  19550. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  19551. var tangent = new THREE.Vector3(),
  19552. normal = new THREE.Vector3(),
  19553. binormal = new THREE.Vector3(),
  19554. tangents = [],
  19555. normals = [],
  19556. binormals = [],
  19557. vec = new THREE.Vector3(),
  19558. mat = new THREE.Matrix4(),
  19559. numpoints = segments + 1,
  19560. theta,
  19561. epsilon = 0.0001,
  19562. smallest,
  19563. tx, ty, tz,
  19564. i, u, v;
  19565. // expose internals
  19566. this.tangents = tangents;
  19567. this.normals = normals;
  19568. this.binormals = binormals;
  19569. // compute the tangent vectors for each segment on the path
  19570. for ( i = 0; i < numpoints; i++ ) {
  19571. u = i / ( numpoints - 1 );
  19572. tangents[ i ] = path.getTangentAt( u );
  19573. tangents[ i ].normalize();
  19574. }
  19575. initialNormal3();
  19576. function initialNormal1(lastBinormal) {
  19577. // fixed start binormal. Has dangers of 0 vectors
  19578. normals[ 0 ] = new THREE.Vector3();
  19579. binormals[ 0 ] = new THREE.Vector3();
  19580. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  19581. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  19582. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19583. }
  19584. function initialNormal2() {
  19585. // This uses the Frenet-Serret formula for deriving binormal
  19586. var t2 = path.getTangentAt( epsilon );
  19587. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  19588. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  19589. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  19590. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  19591. }
  19592. function initialNormal3() {
  19593. // select an initial normal vector perpenicular to the first tangent vector,
  19594. // and in the direction of the smallest tangent xyz component
  19595. normals[ 0 ] = new THREE.Vector3();
  19596. binormals[ 0 ] = new THREE.Vector3();
  19597. smallest = Number.MAX_VALUE;
  19598. tx = Math.abs( tangents[ 0 ].x );
  19599. ty = Math.abs( tangents[ 0 ].y );
  19600. tz = Math.abs( tangents[ 0 ].z );
  19601. if ( tx <= smallest ) {
  19602. smallest = tx;
  19603. normal.set( 1, 0, 0 );
  19604. }
  19605. if ( ty <= smallest ) {
  19606. smallest = ty;
  19607. normal.set( 0, 1, 0 );
  19608. }
  19609. if ( tz <= smallest ) {
  19610. normal.set( 0, 0, 1 );
  19611. }
  19612. vec.cross( tangents[ 0 ], normal ).normalize();
  19613. normals[ 0 ].cross( tangents[ 0 ], vec );
  19614. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  19615. }
  19616. // compute the slowly-varying normal and binormal vectors for each segment on the path
  19617. for ( i = 1; i < numpoints; i++ ) {
  19618. normals[ i ] = normals[ i-1 ].clone();
  19619. binormals[ i ] = binormals[ i-1 ].clone();
  19620. vec.cross( tangents[ i-1 ], tangents[ i ] );
  19621. if ( vec.length() > epsilon ) {
  19622. vec.normalize();
  19623. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  19624. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  19625. }
  19626. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19627. }
  19628. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  19629. if ( closed ) {
  19630. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  19631. theta /= ( numpoints - 1 );
  19632. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  19633. theta = -theta;
  19634. }
  19635. for ( i = 1; i < numpoints; i++ ) {
  19636. // twist a little...
  19637. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  19638. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  19639. }
  19640. }
  19641. };
  19642. /**
  19643. * @author clockworkgeek / https://github.com/clockworkgeek
  19644. * @author timothypratley / https://github.com/timothypratley
  19645. */
  19646. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  19647. THREE.Geometry.call( this );
  19648. radius = radius || 1;
  19649. detail = detail || 0;
  19650. var that = this;
  19651. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  19652. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  19653. }
  19654. var midpoints = [], p = this.vertices;
  19655. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  19656. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  19657. }
  19658. this.mergeVertices();
  19659. // Apply radius
  19660. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  19661. this.vertices[ i ].multiplyScalar( radius );
  19662. }
  19663. // Project vector onto sphere's surface
  19664. function prepare( vector ) {
  19665. var vertex = vector.normalize().clone();
  19666. vertex.index = that.vertices.push( vertex ) - 1;
  19667. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  19668. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  19669. var v = inclination( vector ) / Math.PI + 0.5;
  19670. vertex.uv = new THREE.UV( u, 1 - v );
  19671. return vertex;
  19672. }
  19673. // Approximate a curved face with recursively sub-divided triangles.
  19674. function make( v1, v2, v3, detail ) {
  19675. if ( detail < 1 ) {
  19676. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  19677. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  19678. face.normal = face.centroid.clone().normalize();
  19679. that.faces.push( face );
  19680. var azi = azimuth( face.centroid );
  19681. that.faceVertexUvs[ 0 ].push( [
  19682. correctUV( v1.uv, v1, azi ),
  19683. correctUV( v2.uv, v2, azi ),
  19684. correctUV( v3.uv, v3, azi )
  19685. ] );
  19686. } else {
  19687. detail -= 1;
  19688. // split triangle into 4 smaller triangles
  19689. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  19690. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  19691. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  19692. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  19693. }
  19694. }
  19695. function midpoint( v1, v2 ) {
  19696. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  19697. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  19698. var mid = midpoints[ v1.index ][ v2.index ];
  19699. if ( mid === undefined ) {
  19700. // generate mean point and project to surface with prepare()
  19701. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  19702. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  19703. );
  19704. }
  19705. return mid;
  19706. }
  19707. // Angle around the Y axis, counter-clockwise when looking from above.
  19708. function azimuth( vector ) {
  19709. return Math.atan2( vector.z, -vector.x );
  19710. }
  19711. // Angle above the XZ plane.
  19712. function inclination( vector ) {
  19713. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  19714. }
  19715. // Texture fixing helper. Spheres have some odd behaviours.
  19716. function correctUV( uv, vector, azimuth ) {
  19717. if ( ( azimuth < 0 ) && ( uv.u === 1 ) ) uv = new THREE.UV( uv.u - 1, uv.v );
  19718. if ( ( vector.x === 0 ) && ( vector.z === 0 ) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  19719. return uv;
  19720. }
  19721. this.computeCentroids();
  19722. this.boundingSphere = { radius: radius };
  19723. };
  19724. THREE.PolyhedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19725. /**
  19726. * @author timothypratley / https://github.com/timothypratley
  19727. */
  19728. THREE.IcosahedronGeometry = function ( radius, detail ) {
  19729. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  19730. var vertices = [
  19731. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  19732. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  19733. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  19734. ];
  19735. var faces = [
  19736. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  19737. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  19738. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  19739. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  19740. ];
  19741. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19742. };
  19743. THREE.IcosahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19744. /**
  19745. * @author timothypratley / https://github.com/timothypratley
  19746. */
  19747. THREE.OctahedronGeometry = function ( radius, detail ) {
  19748. var vertices = [
  19749. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  19750. ];
  19751. var faces = [
  19752. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  19753. ];
  19754. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19755. };
  19756. THREE.OctahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19757. /**
  19758. * @author timothypratley / https://github.com/timothypratley
  19759. */
  19760. THREE.TetrahedronGeometry = function ( radius, detail ) {
  19761. var vertices = [
  19762. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  19763. ];
  19764. var faces = [
  19765. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  19766. ];
  19767. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  19768. };
  19769. THREE.TetrahedronGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19770. /**
  19771. * @author zz85 / https://github.com/zz85
  19772. * Parametric Surfaces Geometry
  19773. * based on the brilliant article by @prideout http://prideout.net/blog/?p=44
  19774. *
  19775. * new THREE.ParametricGeometry( parametricFunction, uSegments, ySegements, useTris );
  19776. *
  19777. */
  19778. THREE.ParametricGeometry = function ( func, slices, stacks, useTris ) {
  19779. THREE.Geometry.call( this );
  19780. var verts = this.vertices;
  19781. var faces = this.faces;
  19782. var uvs = this.faceVertexUvs[ 0 ];
  19783. useTris = (useTris === undefined) ? false : useTris;
  19784. var i, il, j, p;
  19785. var u, v;
  19786. var stackCount = stacks + 1;
  19787. var sliceCount = slices + 1;
  19788. for ( i = 0; i <= stacks; i ++ ) {
  19789. v = i / stacks;
  19790. for ( j = 0; j <= slices; j ++ ) {
  19791. u = j / slices;
  19792. p = func( u, v );
  19793. verts.push( p );
  19794. }
  19795. }
  19796. var a, b, c, d;
  19797. var uva, uvb, uvc, uvd;
  19798. for ( i = 0; i < stacks; i ++ ) {
  19799. for ( j = 0; j < slices; j ++ ) {
  19800. a = i * sliceCount + j;
  19801. b = i * sliceCount + j + 1;
  19802. c = (i + 1) * sliceCount + j;
  19803. d = (i + 1) * sliceCount + j + 1;
  19804. uva = new THREE.UV( j / slices, i / stacks );
  19805. uvb = new THREE.UV( ( j + 1 ) / slices, i / stacks );
  19806. uvc = new THREE.UV( j / slices, ( i + 1 ) / stacks );
  19807. uvd = new THREE.UV( ( j + 1 ) / slices, ( i + 1 ) / stacks );
  19808. if ( useTris ) {
  19809. faces.push( new THREE.Face3( a, b, c ) );
  19810. faces.push( new THREE.Face3( b, d, c ) );
  19811. uvs.push( [ uva, uvb, uvc ] );
  19812. uvs.push( [ uvb, uvd, uvc ] );
  19813. } else {
  19814. faces.push( new THREE.Face4( a, b, d, c ) );
  19815. uvs.push( [ uva, uvb, uvd, uvc ] );
  19816. }
  19817. }
  19818. }
  19819. // console.log(this);
  19820. // magic bullet
  19821. // var diff = this.mergeVertices();
  19822. // console.log('removed ', diff, ' vertices by merging');
  19823. this.computeCentroids();
  19824. this.computeFaceNormals();
  19825. this.computeVertexNormals();
  19826. };
  19827. THREE.ParametricGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19828. /**
  19829. * @author qiao / https://github.com/qiao
  19830. * @fileoverview This is a convex hull generator using the incremental method.
  19831. * The complexity is O(n^2) where n is the number of vertices.
  19832. * O(nlogn) algorithms do exist, but they are much more complicated.
  19833. *
  19834. * Benchmark:
  19835. *
  19836. * Platform: CPU: P7350 @2.00GHz Engine: V8
  19837. *
  19838. * Num Vertices Time(ms)
  19839. *
  19840. * 10 1
  19841. * 20 3
  19842. * 30 19
  19843. * 40 48
  19844. * 50 107
  19845. */
  19846. THREE.ConvexGeometry = function( vertices ) {
  19847. THREE.Geometry.call( this );
  19848. var faces = [ [ 0, 1, 2 ], [ 0, 2, 1 ] ];
  19849. for ( var i = 3; i < vertices.length; i++ ) {
  19850. addPoint( i );
  19851. }
  19852. function addPoint( vertexId ) {
  19853. var vertex = vertices[ vertexId ].clone();
  19854. var mag = vertex.length();
  19855. vertex.x += mag * randomOffset();
  19856. vertex.y += mag * randomOffset();
  19857. vertex.z += mag * randomOffset();
  19858. var hole = [];
  19859. for ( var f = 0; f < faces.length; ) {
  19860. var face = faces[ f ];
  19861. // for each face, if the vertex can see it,
  19862. // then we try to add the face's edges into the hole.
  19863. if ( visible( face, vertex ) ) {
  19864. for ( var e = 0; e < 3; e++ ) {
  19865. var edge = [ face[ e ], face[ ( e + 1 ) % 3 ] ];
  19866. var boundary = true;
  19867. // remove duplicated edges.
  19868. for ( var h = 0; h < hole.length; h++ ) {
  19869. if ( equalEdge( hole[ h ], edge ) ) {
  19870. hole[ h ] = hole[ hole.length - 1 ];
  19871. hole.pop();
  19872. boundary = false;
  19873. break;
  19874. }
  19875. }
  19876. if ( boundary ) {
  19877. hole.push( edge );
  19878. }
  19879. }
  19880. // remove faces[ f ]
  19881. faces[ f ] = faces[ faces.length - 1 ];
  19882. faces.pop();
  19883. } else { // not visible
  19884. f++;
  19885. }
  19886. }
  19887. // construct the new faces formed by the edges of the hole and the vertex
  19888. for ( var h = 0; h < hole.length; h++ ) {
  19889. faces.push( [
  19890. hole[ h ][ 0 ],
  19891. hole[ h ][ 1 ],
  19892. vertexId
  19893. ] );
  19894. }
  19895. }
  19896. /**
  19897. * Whether the face is visible from the vertex
  19898. */
  19899. function visible( face, vertex ) {
  19900. var va = vertices[ face[ 0 ] ];
  19901. var vb = vertices[ face[ 1 ] ];
  19902. var vc = vertices[ face[ 2 ] ];
  19903. var n = normal( va, vb, vc );
  19904. // distance from face to origin
  19905. var dist = n.dot( va );
  19906. return n.dot( vertex ) >= dist;
  19907. }
  19908. /**
  19909. * Face normal
  19910. */
  19911. function normal( va, vb, vc ) {
  19912. var cb = new THREE.Vector3();
  19913. var ab = new THREE.Vector3();
  19914. cb.sub( vc, vb );
  19915. ab.sub( va, vb );
  19916. cb.crossSelf( ab );
  19917. cb.normalize();
  19918. return cb;
  19919. }
  19920. /**
  19921. * Detect whether two edges are equal.
  19922. * Note that when constructing the convex hull, two same edges can only
  19923. * be of the negative direction.
  19924. */
  19925. function equalEdge( ea, eb ) {
  19926. return ea[ 0 ] === eb[ 1 ] && ea[ 1 ] === eb[ 0 ];
  19927. }
  19928. /**
  19929. * Create a random offset between -1e-6 and 1e-6.
  19930. */
  19931. function randomOffset() {
  19932. return ( Math.random() - 0.5 ) * 2 * 1e-6;
  19933. }
  19934. /**
  19935. * XXX: Not sure if this is the correct approach. Need someone to review.
  19936. */
  19937. function vertexUv( vertex ) {
  19938. var mag = vertex.length();
  19939. return new THREE.UV( vertex.x / mag, vertex.y / mag );
  19940. }
  19941. // Push vertices into `this.vertices`, skipping those inside the hull
  19942. var id = 0;
  19943. var newId = new Array( vertices.length ); // map from old vertex id to new id
  19944. for ( var i = 0; i < faces.length; i++ ) {
  19945. var face = faces[ i ];
  19946. for ( var j = 0; j < 3; j++ ) {
  19947. if ( newId[ face[ j ] ] === undefined ) {
  19948. newId[ face[ j ] ] = id++;
  19949. this.vertices.push( vertices[ face[ j ] ] );
  19950. }
  19951. face[ j ] = newId[ face[ j ] ];
  19952. }
  19953. }
  19954. // Convert faces into instances of THREE.Face3
  19955. for ( var i = 0; i < faces.length; i++ ) {
  19956. this.faces.push( new THREE.Face3(
  19957. faces[ i ][ 0 ],
  19958. faces[ i ][ 1 ],
  19959. faces[ i ][ 2 ]
  19960. ) );
  19961. }
  19962. // Compute UVs
  19963. for ( var i = 0; i < this.faces.length; i++ ) {
  19964. var face = this.faces[ i ];
  19965. this.faceVertexUvs[ 0 ].push( [
  19966. vertexUv( this.vertices[ face.a ] ),
  19967. vertexUv( this.vertices[ face.b ] ),
  19968. vertexUv( this.vertices[ face.c ])
  19969. ] );
  19970. }
  19971. this.computeCentroids();
  19972. this.computeFaceNormals();
  19973. this.computeVertexNormals();
  19974. };
  19975. THREE.ConvexGeometry.prototype = Object.create( THREE.Geometry.prototype );
  19976. /**
  19977. * @author sroucheray / http://sroucheray.org/
  19978. * @author mrdoob / http://mrdoob.com/
  19979. */
  19980. THREE.AxisHelper = function ( size ) {
  19981. var geometry = new THREE.Geometry();
  19982. geometry.vertices.push(
  19983. new THREE.Vector3(), new THREE.Vector3( size || 1, 0, 0 ),
  19984. new THREE.Vector3(), new THREE.Vector3( 0, size || 1, 0 ),
  19985. new THREE.Vector3(), new THREE.Vector3( 0, 0, size || 1 )
  19986. );
  19987. geometry.colors.push(
  19988. new THREE.Color( 0xff0000 ), new THREE.Color( 0xffaa00 ),
  19989. new THREE.Color( 0x00ff00 ), new THREE.Color( 0xaaff00 ),
  19990. new THREE.Color( 0x0000ff ), new THREE.Color( 0x00aaff )
  19991. );
  19992. var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );
  19993. THREE.Line.call( this, geometry, material, THREE.LinePieces );
  19994. };
  19995. THREE.AxisHelper.prototype = Object.create( THREE.Line.prototype );
  19996. /**
  19997. * @author WestLangley / http://github.com/WestLangley
  19998. * @author zz85 / https://github.com/zz85
  19999. *
  20000. * Creates an arrow for visualizing directions
  20001. *
  20002. * Parameters:
  20003. * dir - Vector3
  20004. * origin - Vector3
  20005. * length - Number
  20006. * hex - color in hex value
  20007. */
  20008. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  20009. THREE.Object3D.call( this );
  20010. if ( hex === undefined ) hex = 0xffff00;
  20011. if ( length === undefined ) length = 20;
  20012. var lineGeometry = new THREE.Geometry();
  20013. lineGeometry.vertices.push( new THREE.Vector3( 0, 0, 0 ) );
  20014. lineGeometry.vertices.push( new THREE.Vector3( 0, 1, 0 ) );
  20015. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color: hex } ) );
  20016. this.add( this.line );
  20017. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  20018. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color: hex } ) );
  20019. this.cone.position.set( 0, 1, 0 );
  20020. this.add( this.cone );
  20021. if ( origin instanceof THREE.Vector3 ) this.position = origin;
  20022. this.setDirection( dir );
  20023. this.setLength( length );
  20024. };
  20025. THREE.ArrowHelper.prototype = Object.create( THREE.Object3D.prototype );
  20026. THREE.ArrowHelper.prototype.setDirection = function ( dir ) {
  20027. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  20028. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  20029. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  20030. this.rotation.setEulerFromRotationMatrix( this.matrix, this.eulerOrder );
  20031. };
  20032. THREE.ArrowHelper.prototype.setLength = function ( length ) {
  20033. this.scale.set( length, length, length );
  20034. };
  20035. THREE.ArrowHelper.prototype.setColor = function ( hex ) {
  20036. this.line.material.color.setHex( hex );
  20037. this.cone.material.color.setHex( hex );
  20038. };
  20039. /**
  20040. * @author alteredq / http://alteredqualia.com/
  20041. *
  20042. * - shows frustum, line of sight and up of the camera
  20043. * - suitable for fast updates
  20044. * - based on frustum visualization in lightgl.js shadowmap example
  20045. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  20046. */
  20047. THREE.CameraHelper = function ( camera ) {
  20048. THREE.Line.call( this );
  20049. var scope = this;
  20050. this.geometry = new THREE.Geometry();
  20051. this.material = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  20052. this.type = THREE.LinePieces;
  20053. this.matrixWorld = camera.matrixWorld;
  20054. this.matrixAutoUpdate = false;
  20055. this.pointMap = {};
  20056. // colors
  20057. var hexFrustum = 0xffaa00;
  20058. var hexCone = 0xff0000;
  20059. var hexUp = 0x00aaff;
  20060. var hexTarget = 0xffffff;
  20061. var hexCross = 0x333333;
  20062. // near
  20063. addLine( "n1", "n2", hexFrustum );
  20064. addLine( "n2", "n4", hexFrustum );
  20065. addLine( "n4", "n3", hexFrustum );
  20066. addLine( "n3", "n1", hexFrustum );
  20067. // far
  20068. addLine( "f1", "f2", hexFrustum );
  20069. addLine( "f2", "f4", hexFrustum );
  20070. addLine( "f4", "f3", hexFrustum );
  20071. addLine( "f3", "f1", hexFrustum );
  20072. // sides
  20073. addLine( "n1", "f1", hexFrustum );
  20074. addLine( "n2", "f2", hexFrustum );
  20075. addLine( "n3", "f3", hexFrustum );
  20076. addLine( "n4", "f4", hexFrustum );
  20077. // cone
  20078. addLine( "p", "n1", hexCone );
  20079. addLine( "p", "n2", hexCone );
  20080. addLine( "p", "n3", hexCone );
  20081. addLine( "p", "n4", hexCone );
  20082. // up
  20083. addLine( "u1", "u2", hexUp );
  20084. addLine( "u2", "u3", hexUp );
  20085. addLine( "u3", "u1", hexUp );
  20086. // target
  20087. addLine( "c", "t", hexTarget );
  20088. addLine( "p", "c", hexCross );
  20089. // cross
  20090. addLine( "cn1", "cn2", hexCross );
  20091. addLine( "cn3", "cn4", hexCross );
  20092. addLine( "cf1", "cf2", hexCross );
  20093. addLine( "cf3", "cf4", hexCross );
  20094. this.camera = camera;
  20095. function addLine( a, b, hex ) {
  20096. addPoint( a, hex );
  20097. addPoint( b, hex );
  20098. }
  20099. function addPoint( id, hex ) {
  20100. scope.geometry.vertices.push( new THREE.Vector3() );
  20101. scope.geometry.colors.push( new THREE.Color( hex ) );
  20102. if ( scope.pointMap[ id ] === undefined ) scope.pointMap[ id ] = [];
  20103. scope.pointMap[ id ].push( scope.geometry.vertices.length - 1 );
  20104. }
  20105. this.update( camera );
  20106. };
  20107. THREE.CameraHelper.prototype = Object.create( THREE.Line.prototype );
  20108. THREE.CameraHelper.prototype.update = function () {
  20109. var scope = this;
  20110. var w = 1, h = 1;
  20111. // we need just camera projection matrix
  20112. // world matrix must be identity
  20113. THREE.CameraHelper.__c.projectionMatrix.copy( this.camera.projectionMatrix );
  20114. // center / target
  20115. setPoint( "c", 0, 0, -1 );
  20116. setPoint( "t", 0, 0, 1 );
  20117. // near
  20118. setPoint( "n1", -w, -h, -1 );
  20119. setPoint( "n2", w, -h, -1 );
  20120. setPoint( "n3", -w, h, -1 );
  20121. setPoint( "n4", w, h, -1 );
  20122. // far
  20123. setPoint( "f1", -w, -h, 1 );
  20124. setPoint( "f2", w, -h, 1 );
  20125. setPoint( "f3", -w, h, 1 );
  20126. setPoint( "f4", w, h, 1 );
  20127. // up
  20128. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  20129. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  20130. setPoint( "u3", 0, h * 2, -1 );
  20131. // cross
  20132. setPoint( "cf1", -w, 0, 1 );
  20133. setPoint( "cf2", w, 0, 1 );
  20134. setPoint( "cf3", 0, -h, 1 );
  20135. setPoint( "cf4", 0, h, 1 );
  20136. setPoint( "cn1", -w, 0, -1 );
  20137. setPoint( "cn2", w, 0, -1 );
  20138. setPoint( "cn3", 0, -h, -1 );
  20139. setPoint( "cn4", 0, h, -1 );
  20140. function setPoint( point, x, y, z ) {
  20141. THREE.CameraHelper.__v.set( x, y, z );
  20142. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  20143. var points = scope.pointMap[ point ];
  20144. if ( points !== undefined ) {
  20145. for ( var i = 0, il = points.length; i < il; i ++ ) {
  20146. scope.geometry.vertices[ points[ i ] ].copy( THREE.CameraHelper.__v );
  20147. }
  20148. }
  20149. }
  20150. this.geometry.verticesNeedUpdate = true;
  20151. };
  20152. THREE.CameraHelper.__projector = new THREE.Projector();
  20153. THREE.CameraHelper.__v = new THREE.Vector3();
  20154. THREE.CameraHelper.__c = new THREE.Camera();
  20155. /**
  20156. * @author alteredq / http://alteredqualia.com/
  20157. *
  20158. * - shows directional light color, intensity, position, orientation and target
  20159. */
  20160. THREE.DirectionalLightHelper = function ( light, sphereSize, arrowLength ) {
  20161. THREE.Object3D.call( this );
  20162. this.light = light;
  20163. // position
  20164. this.position = light.position;
  20165. // direction
  20166. this.direction = new THREE.Vector3();
  20167. this.direction.sub( light.target.position, light.position );
  20168. // color
  20169. this.color = light.color.clone();
  20170. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20171. this.color.r *= intensity;
  20172. this.color.g *= intensity;
  20173. this.color.b *= intensity;
  20174. var hexColor = this.color.getHex();
  20175. // light helper
  20176. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20177. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20178. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20179. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20180. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20181. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20182. this.lightArrow.cone.material.fog = false;
  20183. this.lightArrow.line.material.fog = false;
  20184. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20185. this.add( this.lightArrow );
  20186. this.add( this.lightSphere );
  20187. this.add( this.lightRays );
  20188. this.lightSphere.properties.isGizmo = true;
  20189. this.lightSphere.properties.gizmoSubject = light;
  20190. this.lightSphere.properties.gizmoRoot = this;
  20191. // light target helper
  20192. this.targetSphere = null;
  20193. if ( light.target.properties.targetInverse ) {
  20194. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20195. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20196. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20197. this.targetSphere.position = light.target.position;
  20198. this.targetSphere.properties.isGizmo = true;
  20199. this.targetSphere.properties.gizmoSubject = light.target;
  20200. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20201. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20202. var lineGeometry = new THREE.Geometry();
  20203. lineGeometry.vertices.push( this.position.clone() );
  20204. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20205. lineGeometry.computeLineDistances();
  20206. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20207. this.targetLine.properties.isGizmo = true;
  20208. }
  20209. //
  20210. this.properties.isGizmo = true;
  20211. }
  20212. THREE.DirectionalLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20213. THREE.DirectionalLightHelper.prototype.update = function () {
  20214. // update arrow orientation
  20215. // pointing from light to target
  20216. this.direction.sub( this.light.target.position, this.light.position );
  20217. this.lightArrow.setDirection( this.direction );
  20218. // update arrow, spheres, rays and line colors to light color * light intensity
  20219. this.color.copy( this.light.color );
  20220. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20221. this.color.r *= intensity;
  20222. this.color.g *= intensity;
  20223. this.color.b *= intensity;
  20224. this.lightArrow.setColor( this.color.getHex() );
  20225. this.lightSphere.material.color.copy( this.color );
  20226. this.lightRays.material.color.copy( this.color );
  20227. this.targetSphere.material.color.copy( this.color );
  20228. this.targetLine.material.color.copy( this.color );
  20229. // update target line vertices
  20230. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20231. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20232. this.targetLine.geometry.computeLineDistances();
  20233. this.targetLine.geometry.verticesNeedUpdate = true;
  20234. }
  20235. /**
  20236. * @author alteredq / http://alteredqualia.com/
  20237. *
  20238. * - shows hemisphere light intensity, sky and ground colors and directions
  20239. */
  20240. THREE.HemisphereLightHelper = function ( light, sphereSize, arrowLength, domeSize ) {
  20241. THREE.Object3D.call( this );
  20242. this.light = light;
  20243. // position
  20244. this.position = light.position;
  20245. //
  20246. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20247. // sky color
  20248. this.color = light.color.clone();
  20249. this.color.r *= intensity;
  20250. this.color.g *= intensity;
  20251. this.color.b *= intensity;
  20252. var hexColor = this.color.getHex();
  20253. // ground color
  20254. this.groundColor = light.groundColor.clone();
  20255. this.groundColor.r *= intensity;
  20256. this.groundColor.g *= intensity;
  20257. this.groundColor.b *= intensity;
  20258. var hexColorGround = this.groundColor.getHex();
  20259. // double colored light bulb
  20260. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, 0, Math.PI * 0.5 );
  20261. var bulbGroundGeometry = new THREE.SphereGeometry( sphereSize, 16, 8, 0, Math.PI * 2, Math.PI * 0.5, Math.PI );
  20262. var bulbSkyMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20263. var bulbGroundMaterial = new THREE.MeshBasicMaterial( { color: hexColorGround, fog: false } );
  20264. for ( var i = 0, il = bulbGeometry.faces.length; i < il; i ++ ) {
  20265. bulbGeometry.faces[ i ].materialIndex = 0;
  20266. }
  20267. for ( var i = 0, il = bulbGroundGeometry.faces.length; i < il; i ++ ) {
  20268. bulbGroundGeometry.faces[ i ].materialIndex = 1;
  20269. }
  20270. THREE.GeometryUtils.merge( bulbGeometry, bulbGroundGeometry );
  20271. this.lightSphere = new THREE.Mesh( bulbGeometry, new THREE.MeshFaceMaterial( [ bulbSkyMaterial, bulbGroundMaterial ] ) );
  20272. // arrows for sky and ground light directions
  20273. this.lightArrow = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * 1.1, 0 ), arrowLength, hexColor );
  20274. this.lightArrow.rotation.x = Math.PI;
  20275. this.lightArrowGround = new THREE.ArrowHelper( new THREE.Vector3( 0, 1, 0 ), new THREE.Vector3( 0, ( sphereSize + arrowLength ) * -1.1, 0 ), arrowLength, hexColorGround );
  20276. var joint = new THREE.Object3D();
  20277. joint.rotation.x = -Math.PI * 0.5;
  20278. joint.add( this.lightSphere );
  20279. joint.add( this.lightArrow );
  20280. joint.add( this.lightArrowGround );
  20281. this.add( joint );
  20282. //
  20283. this.lightSphere.properties.isGizmo = true;
  20284. this.lightSphere.properties.gizmoSubject = light;
  20285. this.lightSphere.properties.gizmoRoot = this;
  20286. //
  20287. this.properties.isGizmo = true;
  20288. //
  20289. this.target = new THREE.Vector3();
  20290. this.lookAt( this.target );
  20291. }
  20292. THREE.HemisphereLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20293. THREE.HemisphereLightHelper.prototype.update = function () {
  20294. // update sphere sky and ground colors to light color * light intensity
  20295. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20296. this.color.copy( this.light.color );
  20297. this.groundColor.copy( this.light.groundColor );
  20298. this.color.r *= intensity;
  20299. this.color.g *= intensity;
  20300. this.color.b *= intensity;
  20301. this.groundColor.r *= intensity;
  20302. this.groundColor.g *= intensity;
  20303. this.groundColor.b *= intensity;
  20304. this.lightSphere.material.materials[ 0 ].color.copy( this.color );
  20305. this.lightSphere.material.materials[ 1 ].color.copy( this.groundColor );
  20306. this.lightArrow.setColor( this.color.getHex() );
  20307. this.lightArrowGround.setColor( this.groundColor.getHex() );
  20308. this.lookAt( this.target );
  20309. }
  20310. /**
  20311. * @author alteredq / http://alteredqualia.com/
  20312. *
  20313. * - shows point light color, intensity, position and distance
  20314. */
  20315. THREE.PointLightHelper = function ( light, sphereSize ) {
  20316. THREE.Object3D.call( this );
  20317. this.light = light;
  20318. // position
  20319. this.position = light.position;
  20320. // color
  20321. this.color = light.color.clone();
  20322. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20323. this.color.r *= intensity;
  20324. this.color.g *= intensity;
  20325. this.color.b *= intensity;
  20326. var hexColor = this.color.getHex();
  20327. // light helper
  20328. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20329. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20330. var distanceGeometry = new THREE.IcosahedronGeometry( 1, 2 );
  20331. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20332. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20333. var distanceMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.1, transparent: true } );
  20334. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20335. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20336. this.lightDistance = new THREE.Mesh( distanceGeometry, distanceMaterial );
  20337. var d = light.distance;
  20338. if ( d === 0.0 ) {
  20339. this.lightDistance.visible = false;
  20340. } else {
  20341. this.lightDistance.scale.set( d, d, d );
  20342. }
  20343. this.add( this.lightSphere );
  20344. this.add( this.lightRays );
  20345. this.add( this.lightDistance );
  20346. //
  20347. this.lightSphere.properties.isGizmo = true;
  20348. this.lightSphere.properties.gizmoSubject = light;
  20349. this.lightSphere.properties.gizmoRoot = this;
  20350. //
  20351. this.properties.isGizmo = true;
  20352. }
  20353. THREE.PointLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20354. THREE.PointLightHelper.prototype.update = function () {
  20355. // update sphere and rays colors to light color * light intensity
  20356. this.color.copy( this.light.color );
  20357. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20358. this.color.r *= intensity;
  20359. this.color.g *= intensity;
  20360. this.color.b *= intensity;
  20361. this.lightSphere.material.color.copy( this.color );
  20362. this.lightRays.material.color.copy( this.color );
  20363. this.lightDistance.material.color.copy( this.color );
  20364. //
  20365. var d = this.light.distance;
  20366. if ( d === 0.0 ) {
  20367. this.lightDistance.visible = false;
  20368. } else {
  20369. this.lightDistance.visible = true;
  20370. this.lightDistance.scale.set( d, d, d );
  20371. }
  20372. }
  20373. /**
  20374. * @author alteredq / http://alteredqualia.com/
  20375. *
  20376. * - shows spot light color, intensity, position, orientation, light cone and target
  20377. */
  20378. THREE.SpotLightHelper = function ( light, sphereSize, arrowLength ) {
  20379. THREE.Object3D.call( this );
  20380. this.light = light;
  20381. // position
  20382. this.position = light.position;
  20383. // direction
  20384. this.direction = new THREE.Vector3();
  20385. this.direction.sub( light.target.position, light.position );
  20386. // color
  20387. this.color = light.color.clone();
  20388. var intensity = THREE.Math.clamp( light.intensity, 0, 1 );
  20389. this.color.r *= intensity;
  20390. this.color.g *= intensity;
  20391. this.color.b *= intensity;
  20392. var hexColor = this.color.getHex();
  20393. // light helper
  20394. var bulbGeometry = new THREE.SphereGeometry( sphereSize, 16, 8 );
  20395. var raysGeometry = new THREE.AsteriskGeometry( sphereSize * 1.25, sphereSize * 2.25 );
  20396. var coneGeometry = new THREE.CylinderGeometry( 0.0001, 1, 1, 8, 1, true );
  20397. var coneMatrix = new THREE.Matrix4();
  20398. coneMatrix.rotateX( -Math.PI/2 );
  20399. coneMatrix.translate( new THREE.Vector3( 0, -0.5, 0 ) );
  20400. coneGeometry.applyMatrix( coneMatrix );
  20401. var bulbMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false } );
  20402. var raysMaterial = new THREE.LineBasicMaterial( { color: hexColor, fog: false } );
  20403. var coneMaterial = new THREE.MeshBasicMaterial( { color: hexColor, fog: false, wireframe: true, opacity: 0.3, transparent: true } );
  20404. this.lightArrow = new THREE.ArrowHelper( this.direction, null, arrowLength, hexColor );
  20405. this.lightSphere = new THREE.Mesh( bulbGeometry, bulbMaterial );
  20406. this.lightCone = new THREE.Mesh( coneGeometry, coneMaterial );
  20407. var coneLength = light.distance ? light.distance : 10000;
  20408. var coneWidth = coneLength * Math.tan( light.angle * 0.5 ) * 2;
  20409. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20410. this.lightArrow.cone.material.fog = false;
  20411. this.lightArrow.line.material.fog = false;
  20412. this.lightRays = new THREE.Line( raysGeometry, raysMaterial, THREE.LinePieces );
  20413. this.gyroscope = new THREE.Gyroscope();
  20414. this.gyroscope.add( this.lightArrow );
  20415. this.gyroscope.add( this.lightSphere );
  20416. this.gyroscope.add( this.lightRays );
  20417. this.add( this.gyroscope );
  20418. this.add( this.lightCone );
  20419. this.lookAt( light.target.position );
  20420. this.lightSphere.properties.isGizmo = true;
  20421. this.lightSphere.properties.gizmoSubject = light;
  20422. this.lightSphere.properties.gizmoRoot = this;
  20423. // light target helper
  20424. this.targetSphere = null;
  20425. if ( light.target.properties.targetInverse ) {
  20426. var targetGeo = new THREE.SphereGeometry( sphereSize, 8, 4 );
  20427. var targetMaterial = new THREE.MeshBasicMaterial( { color: hexColor, wireframe: true, fog: false } );
  20428. this.targetSphere = new THREE.Mesh( targetGeo, targetMaterial );
  20429. this.targetSphere.position = light.target.position;
  20430. this.targetSphere.properties.isGizmo = true;
  20431. this.targetSphere.properties.gizmoSubject = light.target;
  20432. this.targetSphere.properties.gizmoRoot = this.targetSphere;
  20433. var lineMaterial = new THREE.LineDashedMaterial( { color: hexColor, dashSize: 4, gapSize: 4, opacity: 0.75, transparent: true, fog: false } );
  20434. var lineGeometry = new THREE.Geometry();
  20435. lineGeometry.vertices.push( this.position.clone() );
  20436. lineGeometry.vertices.push( this.targetSphere.position.clone() );
  20437. lineGeometry.computeLineDistances();
  20438. this.targetLine = new THREE.Line( lineGeometry, lineMaterial );
  20439. this.targetLine.properties.isGizmo = true;
  20440. }
  20441. //
  20442. this.properties.isGizmo = true;
  20443. }
  20444. THREE.SpotLightHelper.prototype = Object.create( THREE.Object3D.prototype );
  20445. THREE.SpotLightHelper.prototype.update = function () {
  20446. // update arrow orientation
  20447. // pointing from light to target
  20448. this.direction.sub( this.light.target.position, this.light.position );
  20449. this.lightArrow.setDirection( this.direction );
  20450. // update light cone orientation and size
  20451. this.lookAt( this.light.target.position );
  20452. var coneLength = this.light.distance ? this.light.distance : 10000;
  20453. var coneWidth = coneLength * Math.tan( this.light.angle * 0.5 ) * 2;
  20454. this.lightCone.scale.set( coneWidth, coneWidth, coneLength );
  20455. // update arrow, spheres, rays and line colors to light color * light intensity
  20456. this.color.copy( this.light.color );
  20457. var intensity = THREE.Math.clamp( this.light.intensity, 0, 1 );
  20458. this.color.r *= intensity;
  20459. this.color.g *= intensity;
  20460. this.color.b *= intensity;
  20461. this.lightArrow.setColor( this.color.getHex() );
  20462. this.lightSphere.material.color.copy( this.color );
  20463. this.lightRays.material.color.copy( this.color );
  20464. this.lightCone.material.color.copy( this.color );
  20465. this.targetSphere.material.color.copy( this.color );
  20466. this.targetLine.material.color.copy( this.color );
  20467. // update target line vertices
  20468. this.targetLine.geometry.vertices[ 0 ].copy( this.light.position );
  20469. this.targetLine.geometry.vertices[ 1 ].copy( this.light.target.position );
  20470. this.targetLine.geometry.computeLineDistances();
  20471. this.targetLine.geometry.verticesNeedUpdate = true;
  20472. }
  20473. /*
  20474. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  20475. *
  20476. * Subdivision Geometry Modifier
  20477. * using Catmull-Clark Subdivision Surfaces
  20478. * for creating smooth geometry meshes
  20479. *
  20480. * Note: a modifier modifies vertices and faces of geometry,
  20481. * so use geometry.clone() if original geometry needs to be retained
  20482. *
  20483. * Readings:
  20484. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  20485. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  20486. * http://xrt.wikidot.com/blog:31
  20487. * "Subdivision Surfaces in Character Animation"
  20488. *
  20489. * (on boundary edges)
  20490. * http://rosettacode.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  20491. * https://graphics.stanford.edu/wikis/cs148-09-summer/Assignment3Description
  20492. *
  20493. * Supports:
  20494. * Closed and Open geometries.
  20495. *
  20496. * TODO:
  20497. * crease vertex and "semi-sharp" features
  20498. * selective subdivision
  20499. */
  20500. THREE.SubdivisionModifier = function( subdivisions ) {
  20501. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  20502. // Settings
  20503. this.useOldVertexColors = false;
  20504. this.supportUVs = true;
  20505. this.debug = false;
  20506. };
  20507. // Applies the "modify" pattern
  20508. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  20509. var repeats = this.subdivisions;
  20510. while ( repeats-- > 0 ) {
  20511. this.smooth( geometry );
  20512. }
  20513. };
  20514. /// REFACTORING THIS OUT
  20515. THREE.GeometryUtils.orderedKey = function ( a, b ) {
  20516. return Math.min( a, b ) + "_" + Math.max( a, b );
  20517. };
  20518. // Returns a hashmap - of { edge_key: face_index }
  20519. THREE.GeometryUtils.computeEdgeFaces = function ( geometry ) {
  20520. var i, il, v1, v2, j, k,
  20521. face, faceIndices, faceIndex,
  20522. edge,
  20523. hash,
  20524. edgeFaceMap = {};
  20525. var orderedKey = THREE.GeometryUtils.orderedKey;
  20526. function mapEdgeHash( hash, i ) {
  20527. if ( edgeFaceMap[ hash ] === undefined ) {
  20528. edgeFaceMap[ hash ] = [];
  20529. }
  20530. edgeFaceMap[ hash ].push( i );
  20531. }
  20532. // construct vertex -> face map
  20533. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  20534. face = geometry.faces[ i ];
  20535. if ( face instanceof THREE.Face3 ) {
  20536. hash = orderedKey( face.a, face.b );
  20537. mapEdgeHash( hash, i );
  20538. hash = orderedKey( face.b, face.c );
  20539. mapEdgeHash( hash, i );
  20540. hash = orderedKey( face.c, face.a );
  20541. mapEdgeHash( hash, i );
  20542. } else if ( face instanceof THREE.Face4 ) {
  20543. hash = orderedKey( face.a, face.b );
  20544. mapEdgeHash( hash, i );
  20545. hash = orderedKey( face.b, face.c );
  20546. mapEdgeHash( hash, i );
  20547. hash = orderedKey( face.c, face.d );
  20548. mapEdgeHash( hash, i );
  20549. hash = orderedKey( face.d, face.a );
  20550. mapEdgeHash( hash, i );
  20551. }
  20552. }
  20553. // extract faces
  20554. // var edges = [];
  20555. //
  20556. // var numOfEdges = 0;
  20557. // for (i in edgeFaceMap) {
  20558. // numOfEdges++;
  20559. //
  20560. // edge = edgeFaceMap[i];
  20561. // edges.push(edge);
  20562. //
  20563. // }
  20564. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  20565. return edgeFaceMap;
  20566. }
  20567. /////////////////////////////
  20568. // Performs an iteration of Catmull-Clark Subdivision
  20569. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  20570. //debug( 'running smooth' );
  20571. // New set of vertices, faces and uvs
  20572. var newVertices = [], newFaces = [], newUVs = [];
  20573. function v( x, y, z ) {
  20574. newVertices.push( new THREE.Vector3( x, y, z ) );
  20575. }
  20576. var scope = this;
  20577. var orderedKey = THREE.GeometryUtils.orderedKey;
  20578. var computeEdgeFaces = THREE.GeometryUtils.computeEdgeFaces;
  20579. function assert() {
  20580. if (scope.debug && console && console.assert) console.assert.apply(console, arguments);
  20581. }
  20582. function debug() {
  20583. if (scope.debug) console.log.apply(console, arguments);
  20584. }
  20585. function warn() {
  20586. if (console)
  20587. console.log.apply(console, arguments);
  20588. }
  20589. function f4( a, b, c, d, oldFace, orders, facei ) {
  20590. // TODO move vertex selection over here!
  20591. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.materialIndex );
  20592. if (scope.useOldVertexColors) {
  20593. newFace.vertexColors = [];
  20594. var color, tmpColor, order;
  20595. for (var i=0;i<4;i++) {
  20596. order = orders[i];
  20597. color = new THREE.Color(),
  20598. color.setRGB(0,0,0);
  20599. for (var j=0, jl=0; j<order.length;j++) {
  20600. tmpColor = oldFace.vertexColors[order[j]-1];
  20601. color.r += tmpColor.r;
  20602. color.g += tmpColor.g;
  20603. color.b += tmpColor.b;
  20604. }
  20605. color.r /= order.length;
  20606. color.g /= order.length;
  20607. color.b /= order.length;
  20608. newFace.vertexColors[i] = color;
  20609. }
  20610. }
  20611. newFaces.push( newFace );
  20612. if (scope.supportUVs) {
  20613. var aUv = [
  20614. getUV(a, ''),
  20615. getUV(b, facei),
  20616. getUV(c, facei),
  20617. getUV(d, facei)
  20618. ];
  20619. if (!aUv[0]) debug('a :( ', a+':'+facei);
  20620. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  20621. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  20622. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  20623. else
  20624. newUVs.push( aUv );
  20625. }
  20626. }
  20627. var originalPoints = oldGeometry.vertices;
  20628. var originalFaces = oldGeometry.faces;
  20629. var originalVerticesLength = originalPoints.length;
  20630. var newPoints = originalPoints.concat(); // New set of vertices to work on
  20631. var facePoints = [], // these are new points on exisiting faces
  20632. edgePoints = {}; // these are new points on exisiting edges
  20633. var sharpEdges = {}, sharpVertices = []; // Mark edges and vertices to prevent smoothening on them
  20634. // TODO: handle this correctly.
  20635. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  20636. function debugCoreStuff() {
  20637. console.log('facePoints', facePoints, 'edgePoints', edgePoints);
  20638. console.log('edgeFaceMap', edgeFaceMap, 'vertexEdgeMap', vertexEdgeMap);
  20639. }
  20640. function getUV(vertexNo, oldFaceNo) {
  20641. var j,jl;
  20642. var key = vertexNo+':'+oldFaceNo;
  20643. var theUV = uvForVertices[key];
  20644. if (!theUV) {
  20645. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  20646. debug('face pt');
  20647. } else {
  20648. debug('edge pt');
  20649. }
  20650. warn('warning, UV not found for', key);
  20651. return null;
  20652. }
  20653. return theUV;
  20654. // Original faces -> Vertex Nos.
  20655. // new Facepoint -> Vertex Nos.
  20656. // edge Points
  20657. }
  20658. function addUV(vertexNo, oldFaceNo, value) {
  20659. var key = vertexNo+':'+oldFaceNo;
  20660. if (!(key in uvForVertices)) {
  20661. uvForVertices[key] = value;
  20662. } else {
  20663. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  20664. }
  20665. }
  20666. // Step 1
  20667. // For each face, add a face point
  20668. // Set each face point to be the centroid of all original points for the respective face.
  20669. // debug(oldGeometry);
  20670. var i, il, j, jl, face;
  20671. // For Uvs
  20672. var uvs = oldGeometry.faceVertexUvs[0];
  20673. var abcd = 'abcd', vertice;
  20674. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  20675. if (scope.supportUVs)
  20676. for (i=0, il = uvs.length; i<il; i++ ) {
  20677. for (j=0,jl=uvs[i].length;j<jl;j++) {
  20678. vertice = originalFaces[i][abcd.charAt(j)];
  20679. addUV(vertice, i, uvs[i][j]);
  20680. }
  20681. }
  20682. if (uvs.length == 0) scope.supportUVs = false;
  20683. // Additional UVs check, if we index original
  20684. var uvCount = 0;
  20685. for (var u in uvForVertices) {
  20686. uvCount++;
  20687. }
  20688. if (!uvCount) {
  20689. scope.supportUVs = false;
  20690. debug('no uvs');
  20691. }
  20692. var avgUv ;
  20693. for (i=0, il = originalFaces.length; i<il ;i++) {
  20694. face = originalFaces[ i ];
  20695. facePoints.push( face.centroid );
  20696. newPoints.push( face.centroid );
  20697. if (!scope.supportUVs) continue;
  20698. // Prepare subdivided uv
  20699. avgUv = new THREE.UV();
  20700. if ( face instanceof THREE.Face3 ) {
  20701. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  20702. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  20703. avgUv.u /= 3;
  20704. avgUv.v /= 3;
  20705. } else if ( face instanceof THREE.Face4 ) {
  20706. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  20707. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  20708. avgUv.u /= 4;
  20709. avgUv.v /= 4;
  20710. }
  20711. addUV(originalVerticesLength + i, '', avgUv);
  20712. }
  20713. // Step 2
  20714. // For each edge, add an edge point.
  20715. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  20716. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index eg { edge_key: [face_index, face_index2 ]}
  20717. var edge, faceIndexA, faceIndexB, avg;
  20718. // debug('edgeFaceMap', edgeFaceMap);
  20719. var edgeCount = 0;
  20720. var edgeVertex, edgeVertexA, edgeVertexB;
  20721. ////
  20722. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  20723. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  20724. function addVertexEdgeMap(vertex, edge) {
  20725. if (vertexEdgeMap[vertex]===undefined) {
  20726. vertexEdgeMap[vertex] = [];
  20727. }
  20728. vertexEdgeMap[vertex].push(edge);
  20729. }
  20730. function addVertexFaceMap(vertex, face, edge) {
  20731. if (vertexFaceMap[vertex]===undefined) {
  20732. vertexFaceMap[vertex] = {};
  20733. }
  20734. vertexFaceMap[vertex][face] = edge;
  20735. // vertexFaceMap[vertex][face] = null;
  20736. }
  20737. // Prepares vertexEdgeMap and vertexFaceMap
  20738. for (i in edgeFaceMap) { // This is for every edge
  20739. edge = edgeFaceMap[i];
  20740. edgeVertex = i.split('_');
  20741. edgeVertexA = edgeVertex[0];
  20742. edgeVertexB = edgeVertex[1];
  20743. // Maps an edgeVertex to connecting edges
  20744. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  20745. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  20746. for (j=0,jl=edge.length;j<jl;j++) {
  20747. face = edge[j];
  20748. addVertexFaceMap(edgeVertexA, face, i);
  20749. addVertexFaceMap(edgeVertexB, face, i);
  20750. }
  20751. // {edge vertex: { face1: edge_key, face2: edge_key.. } }
  20752. // this thing is fishy right now.
  20753. if (edge.length < 2) {
  20754. // edge is "sharp";
  20755. sharpEdges[i] = true;
  20756. sharpVertices[edgeVertexA] = true;
  20757. sharpVertices[edgeVertexB] = true;
  20758. }
  20759. }
  20760. for (i in edgeFaceMap) {
  20761. edge = edgeFaceMap[i];
  20762. faceIndexA = edge[0]; // face index a
  20763. faceIndexB = edge[1]; // face index b
  20764. edgeVertex = i.split('_');
  20765. edgeVertexA = edgeVertex[0];
  20766. edgeVertexB = edgeVertex[1];
  20767. avg = new THREE.Vector3();
  20768. //debug(i, faceIndexB,facePoints[faceIndexB]);
  20769. assert(edge.length > 0, 'an edge without faces?!');
  20770. if (edge.length==1) {
  20771. avg.addSelf(originalPoints[edgeVertexA]);
  20772. avg.addSelf(originalPoints[edgeVertexB]);
  20773. avg.multiplyScalar(0.5);
  20774. sharpVertices[newPoints.length] = true;
  20775. } else {
  20776. avg.addSelf(facePoints[faceIndexA]);
  20777. avg.addSelf(facePoints[faceIndexB]);
  20778. avg.addSelf(originalPoints[edgeVertexA]);
  20779. avg.addSelf(originalPoints[edgeVertexB]);
  20780. avg.multiplyScalar(0.25);
  20781. }
  20782. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  20783. newPoints.push( avg );
  20784. edgeCount ++;
  20785. if (!scope.supportUVs) {
  20786. continue;
  20787. }
  20788. // Prepare subdivided uv
  20789. avgUv = new THREE.UV();
  20790. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  20791. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  20792. avgUv.u /= 2;
  20793. avgUv.v /= 2;
  20794. addUV(edgePoints[i], faceIndexA, avgUv);
  20795. if (edge.length>=2) {
  20796. assert(edge.length == 2, 'did we plan for more than 2 edges?');
  20797. avgUv = new THREE.UV();
  20798. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  20799. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  20800. avgUv.u /= 2;
  20801. avgUv.v /= 2;
  20802. addUV(edgePoints[i], faceIndexB, avgUv);
  20803. }
  20804. }
  20805. debug('-- Step 2 done');
  20806. // Step 3
  20807. // For each face point, add an edge for every edge of the face,
  20808. // connecting the face point to each edge point for the face.
  20809. var facePt, currentVerticeIndex;
  20810. var hashAB, hashBC, hashCD, hashDA, hashCA;
  20811. var abc123 = ['123', '12', '2', '23'];
  20812. var bca123 = ['123', '23', '3', '31'];
  20813. var cab123 = ['123', '31', '1', '12'];
  20814. var abc1234 = ['1234', '12', '2', '23'];
  20815. var bcd1234 = ['1234', '23', '3', '34'];
  20816. var cda1234 = ['1234', '34', '4', '41'];
  20817. var dab1234 = ['1234', '41', '1', '12'];
  20818. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  20819. facePt = facePoints[i];
  20820. face = originalFaces[i];
  20821. currentVerticeIndex = originalVerticesLength+ i;
  20822. if ( face instanceof THREE.Face3 ) {
  20823. // create 3 face4s
  20824. hashAB = orderedKey( face.a, face.b );
  20825. hashBC = orderedKey( face.b, face.c );
  20826. hashCA = orderedKey( face.c, face.a );
  20827. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  20828. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  20829. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  20830. } else if ( face instanceof THREE.Face4 ) {
  20831. // create 4 face4s
  20832. hashAB = orderedKey( face.a, face.b );
  20833. hashBC = orderedKey( face.b, face.c );
  20834. hashCD = orderedKey( face.c, face.d );
  20835. hashDA = orderedKey( face.d, face.a );
  20836. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  20837. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  20838. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  20839. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  20840. } else {
  20841. debug('face should be a face!', face);
  20842. }
  20843. }
  20844. newVertices = newPoints;
  20845. // Step 4
  20846. // For each original point P,
  20847. // take the average F of all n face points for faces touching P,
  20848. // and take the average R of all n edge midpoints for edges touching P,
  20849. // where each edge midpoint is the average of its two endpoint vertices.
  20850. // Move each original point to the point
  20851. var F = new THREE.Vector3();
  20852. var R = new THREE.Vector3();
  20853. var n;
  20854. for (i=0, il = originalPoints.length; i<il; i++) {
  20855. // (F + 2R + (n-3)P) / n
  20856. if (vertexEdgeMap[i]===undefined) continue;
  20857. F.set(0,0,0);
  20858. R.set(0,0,0);
  20859. var newPos = new THREE.Vector3(0,0,0);
  20860. var f = 0; // this counts number of faces, original vertex is connected to (also known as valance?)
  20861. for (j in vertexFaceMap[i]) {
  20862. F.addSelf(facePoints[j]);
  20863. f++;
  20864. }
  20865. var sharpEdgeCount = 0;
  20866. n = vertexEdgeMap[i].length; // given a vertex, return its connecting edges
  20867. // Are we on the border?
  20868. var boundary_case = f != n;
  20869. // if (boundary_case) {
  20870. // console.error('moo', 'o', i, 'faces touched', f, 'edges', n, n == 2);
  20871. // }
  20872. for (j=0;j<n;j++) {
  20873. if (
  20874. sharpEdges[
  20875. orderedKey(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  20876. ]) {
  20877. sharpEdgeCount++;
  20878. }
  20879. }
  20880. // if ( sharpEdgeCount==2 ) {
  20881. // continue;
  20882. // // Do not move vertex if there's 2 connecting sharp edges.
  20883. // }
  20884. /*
  20885. if (sharpEdgeCount>2) {
  20886. // TODO
  20887. }
  20888. */
  20889. F.divideScalar(f);
  20890. var boundary_edges = 0;
  20891. if (boundary_case) {
  20892. var bb_edge;
  20893. for (j=0; j<n;j++) {
  20894. edge = vertexEdgeMap[i][j];
  20895. bb_edge = edgeFaceMap[orderedKey(edge[0], edge[1])].length == 1
  20896. if (bb_edge) {
  20897. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20898. R.addSelf(midPt);
  20899. boundary_edges++;
  20900. }
  20901. }
  20902. R.divideScalar(4);
  20903. // console.log(j + ' --- ' + n + ' --- ' + boundary_edges);
  20904. assert(boundary_edges == 2, 'should have only 2 boundary edges');
  20905. } else {
  20906. for (j=0; j<n;j++) {
  20907. edge = vertexEdgeMap[i][j];
  20908. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  20909. R.addSelf(midPt);
  20910. }
  20911. R.divideScalar(n);
  20912. }
  20913. // Sum the formula
  20914. newPos.addSelf(originalPoints[i]);
  20915. if (boundary_case) {
  20916. newPos.divideScalar(2);
  20917. newPos.addSelf(R);
  20918. } else {
  20919. newPos.multiplyScalar(n - 3);
  20920. newPos.addSelf(F);
  20921. newPos.addSelf(R.multiplyScalar(2));
  20922. newPos.divideScalar(n);
  20923. }
  20924. newVertices[i] = newPos;
  20925. }
  20926. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  20927. newGeometry.vertices = newVertices;
  20928. newGeometry.faces = newFaces;
  20929. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  20930. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  20931. newGeometry.computeCentroids();
  20932. newGeometry.computeFaceNormals();
  20933. newGeometry.computeVertexNormals();
  20934. };
  20935. /**
  20936. * @author alteredq / http://alteredqualia.com/
  20937. */
  20938. THREE.ImmediateRenderObject = function ( ) {
  20939. THREE.Object3D.call( this );
  20940. this.render = function ( renderCallback ) { };
  20941. };
  20942. THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype );
  20943. /**
  20944. * @author mikael emtinger / http://gomo.se/
  20945. * @author alteredq / http://alteredqualia.com/
  20946. */
  20947. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20948. THREE.Object3D.call( this );
  20949. this.lensFlares = [];
  20950. this.positionScreen = new THREE.Vector3();
  20951. this.customUpdateCallback = undefined;
  20952. if( texture !== undefined ) {
  20953. this.add( texture, size, distance, blending, color );
  20954. }
  20955. };
  20956. THREE.LensFlare.prototype = Object.create( THREE.Object3D.prototype );
  20957. /*
  20958. * Add: adds another flare
  20959. */
  20960. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20961. if( size === undefined ) size = -1;
  20962. if( distance === undefined ) distance = 0;
  20963. if( opacity === undefined ) opacity = 1;
  20964. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20965. if( blending === undefined ) blending = THREE.NormalBlending;
  20966. distance = Math.min( distance, Math.max( 0, distance ) );
  20967. this.lensFlares.push( { texture: texture, // THREE.Texture
  20968. size: size, // size in pixels (-1 = use texture.width)
  20969. distance: distance, // distance (0-1) from light source (0=at light source)
  20970. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20971. scale: 1, // scale
  20972. rotation: 1, // rotation
  20973. opacity: opacity, // opacity
  20974. color: color, // color
  20975. blending: blending } ); // blending
  20976. };
  20977. /*
  20978. * Update lens flares update positions on all flares based on the screen position
  20979. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20980. */
  20981. THREE.LensFlare.prototype.updateLensFlares = function () {
  20982. var f, fl = this.lensFlares.length;
  20983. var flare;
  20984. var vecX = -this.positionScreen.x * 2;
  20985. var vecY = -this.positionScreen.y * 2;
  20986. for( f = 0; f < fl; f ++ ) {
  20987. flare = this.lensFlares[ f ];
  20988. flare.x = this.positionScreen.x + vecX * flare.distance;
  20989. flare.y = this.positionScreen.y + vecY * flare.distance;
  20990. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20991. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20992. }
  20993. };
  20994. /**
  20995. * @author alteredq / http://alteredqualia.com/
  20996. */
  20997. THREE.MorphBlendMesh = function( geometry, material ) {
  20998. THREE.Mesh.call( this, geometry, material );
  20999. this.animationsMap = {};
  21000. this.animationsList = [];
  21001. // prepare default animation
  21002. // (all frames played together in 1 second)
  21003. var numFrames = this.geometry.morphTargets.length;
  21004. var name = "__default";
  21005. var startFrame = 0;
  21006. var endFrame = numFrames - 1;
  21007. var fps = numFrames / 1;
  21008. this.createAnimation( name, startFrame, endFrame, fps );
  21009. this.setAnimationWeight( name, 1 );
  21010. };
  21011. THREE.MorphBlendMesh.prototype = Object.create( THREE.Mesh.prototype );
  21012. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  21013. var animation = {
  21014. startFrame: start,
  21015. endFrame: end,
  21016. length: end - start + 1,
  21017. fps: fps,
  21018. duration: ( end - start ) / fps,
  21019. lastFrame: 0,
  21020. currentFrame: 0,
  21021. active: false,
  21022. time: 0,
  21023. direction: 1,
  21024. weight: 1,
  21025. directionBackwards: false,
  21026. mirroredLoop: false
  21027. };
  21028. this.animationsMap[ name ] = animation;
  21029. this.animationsList.push( animation );
  21030. };
  21031. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  21032. var pattern = /([a-z]+)(\d+)/;
  21033. var firstAnimation, frameRanges = {};
  21034. var geometry = this.geometry;
  21035. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  21036. var morph = geometry.morphTargets[ i ];
  21037. var chunks = morph.name.match( pattern );
  21038. if ( chunks && chunks.length > 1 ) {
  21039. var name = chunks[ 1 ];
  21040. var num = chunks[ 2 ];
  21041. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  21042. var range = frameRanges[ name ];
  21043. if ( i < range.start ) range.start = i;
  21044. if ( i > range.end ) range.end = i;
  21045. if ( ! firstAnimation ) firstAnimation = name;
  21046. }
  21047. }
  21048. for ( var name in frameRanges ) {
  21049. var range = frameRanges[ name ];
  21050. this.createAnimation( name, range.start, range.end, fps );
  21051. }
  21052. this.firstAnimation = firstAnimation;
  21053. };
  21054. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  21055. var animation = this.animationsMap[ name ];
  21056. if ( animation ) {
  21057. animation.direction = 1;
  21058. animation.directionBackwards = false;
  21059. }
  21060. };
  21061. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  21062. var animation = this.animationsMap[ name ];
  21063. if ( animation ) {
  21064. animation.direction = -1;
  21065. animation.directionBackwards = true;
  21066. }
  21067. };
  21068. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  21069. var animation = this.animationsMap[ name ];
  21070. if ( animation ) {
  21071. animation.fps = fps;
  21072. animation.duration = ( animation.end - animation.start ) / animation.fps;
  21073. }
  21074. };
  21075. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  21076. var animation = this.animationsMap[ name ];
  21077. if ( animation ) {
  21078. animation.duration = duration;
  21079. animation.fps = ( animation.end - animation.start ) / animation.duration;
  21080. }
  21081. };
  21082. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  21083. var animation = this.animationsMap[ name ];
  21084. if ( animation ) {
  21085. animation.weight = weight;
  21086. }
  21087. };
  21088. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  21089. var animation = this.animationsMap[ name ];
  21090. if ( animation ) {
  21091. animation.time = time;
  21092. }
  21093. };
  21094. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  21095. var time = 0;
  21096. var animation = this.animationsMap[ name ];
  21097. if ( animation ) {
  21098. time = animation.time;
  21099. }
  21100. return time;
  21101. };
  21102. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  21103. var duration = -1;
  21104. var animation = this.animationsMap[ name ];
  21105. if ( animation ) {
  21106. duration = animation.duration;
  21107. }
  21108. return duration;
  21109. };
  21110. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  21111. var animation = this.animationsMap[ name ];
  21112. if ( animation ) {
  21113. animation.time = 0;
  21114. animation.active = true;
  21115. } else {
  21116. console.warn( "animation[" + name + "] undefined" );
  21117. }
  21118. };
  21119. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  21120. var animation = this.animationsMap[ name ];
  21121. if ( animation ) {
  21122. animation.active = false;
  21123. }
  21124. };
  21125. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  21126. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  21127. var animation = this.animationsList[ i ];
  21128. if ( ! animation.active ) continue;
  21129. var frameTime = animation.duration / animation.length;
  21130. animation.time += animation.direction * delta;
  21131. if ( animation.mirroredLoop ) {
  21132. if ( animation.time > animation.duration || animation.time < 0 ) {
  21133. animation.direction *= -1;
  21134. if ( animation.time > animation.duration ) {
  21135. animation.time = animation.duration;
  21136. animation.directionBackwards = true;
  21137. }
  21138. if ( animation.time < 0 ) {
  21139. animation.time = 0;
  21140. animation.directionBackwards = false;
  21141. }
  21142. }
  21143. } else {
  21144. animation.time = animation.time % animation.duration;
  21145. if ( animation.time < 0 ) animation.time += animation.duration;
  21146. }
  21147. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  21148. var weight = animation.weight;
  21149. if ( keyframe !== animation.currentFrame ) {
  21150. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  21151. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  21152. this.morphTargetInfluences[ keyframe ] = 0;
  21153. animation.lastFrame = animation.currentFrame;
  21154. animation.currentFrame = keyframe;
  21155. }
  21156. var mix = ( animation.time % frameTime ) / frameTime;
  21157. if ( animation.directionBackwards ) mix = 1 - mix;
  21158. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  21159. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  21160. }
  21161. };
  21162. /**
  21163. * @author mikael emtinger / http://gomo.se/
  21164. * @author alteredq / http://alteredqualia.com/
  21165. */
  21166. THREE.LensFlarePlugin = function ( ) {
  21167. var _gl, _renderer, _lensFlare = {};
  21168. this.init = function ( renderer ) {
  21169. _gl = renderer.context;
  21170. _renderer = renderer;
  21171. _lensFlare.vertices = new Float32Array( 8 + 8 );
  21172. _lensFlare.faces = new Uint16Array( 6 );
  21173. var i = 0;
  21174. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  21175. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  21176. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  21177. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  21178. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21179. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  21180. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  21181. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  21182. i = 0;
  21183. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  21184. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  21185. // buffers
  21186. _lensFlare.vertexBuffer = _gl.createBuffer();
  21187. _lensFlare.elementBuffer = _gl.createBuffer();
  21188. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21189. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  21190. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21191. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  21192. // textures
  21193. _lensFlare.tempTexture = _gl.createTexture();
  21194. _lensFlare.occlusionTexture = _gl.createTexture();
  21195. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21196. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  21197. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21198. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21199. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21200. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21201. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21202. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  21203. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  21204. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  21205. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  21206. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  21207. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  21208. _lensFlare.hasVertexTexture = false;
  21209. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  21210. } else {
  21211. _lensFlare.hasVertexTexture = true;
  21212. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  21213. }
  21214. _lensFlare.attributes = {};
  21215. _lensFlare.uniforms = {};
  21216. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  21217. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  21218. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  21219. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  21220. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  21221. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  21222. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  21223. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  21224. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  21225. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  21226. };
  21227. /*
  21228. * Render lens flares
  21229. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  21230. * reads these back and calculates occlusion.
  21231. * Then _lensFlare.update_lensFlares() is called to re-position and
  21232. * update transparency of flares. Then they are rendered.
  21233. *
  21234. */
  21235. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21236. var flares = scene.__webglFlares,
  21237. nFlares = flares.length;
  21238. if ( ! nFlares ) return;
  21239. var tempPosition = new THREE.Vector3();
  21240. var invAspect = viewportHeight / viewportWidth,
  21241. halfViewportWidth = viewportWidth * 0.5,
  21242. halfViewportHeight = viewportHeight * 0.5;
  21243. var size = 16 / viewportHeight,
  21244. scale = new THREE.Vector2( size * invAspect, size );
  21245. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  21246. screenPositionPixels = new THREE.Vector2( 1, 1 );
  21247. var uniforms = _lensFlare.uniforms,
  21248. attributes = _lensFlare.attributes;
  21249. // set _lensFlare program and reset blending
  21250. _gl.useProgram( _lensFlare.program );
  21251. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  21252. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  21253. // loop through all lens flares to update their occlusion and positions
  21254. // setup gl and common used attribs/unforms
  21255. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21256. _gl.uniform1i( uniforms.map, 1 );
  21257. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21258. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21259. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21260. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21261. _gl.disable( _gl.CULL_FACE );
  21262. _gl.depthMask( false );
  21263. var i, j, jl, flare, sprite;
  21264. for ( i = 0; i < nFlares; i ++ ) {
  21265. size = 16 / viewportHeight;
  21266. scale.set( size * invAspect, size );
  21267. // calc object screen position
  21268. flare = flares[ i ];
  21269. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21270. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  21271. camera.projectionMatrix.multiplyVector3( tempPosition );
  21272. // setup arrays for gl programs
  21273. screenPosition.copy( tempPosition )
  21274. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21275. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21276. // screen cull
  21277. if ( _lensFlare.hasVertexTexture || (
  21278. screenPositionPixels.x > 0 &&
  21279. screenPositionPixels.x < viewportWidth &&
  21280. screenPositionPixels.y > 0 &&
  21281. screenPositionPixels.y < viewportHeight ) ) {
  21282. // save current RGB to temp texture
  21283. _gl.activeTexture( _gl.TEXTURE1 );
  21284. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21285. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21286. // render pink quad
  21287. _gl.uniform1i( uniforms.renderType, 0 );
  21288. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21289. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21290. _gl.disable( _gl.BLEND );
  21291. _gl.enable( _gl.DEPTH_TEST );
  21292. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21293. // copy result to occlusionMap
  21294. _gl.activeTexture( _gl.TEXTURE0 );
  21295. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21296. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21297. // restore graphics
  21298. _gl.uniform1i( uniforms.renderType, 1 );
  21299. _gl.disable( _gl.DEPTH_TEST );
  21300. _gl.activeTexture( _gl.TEXTURE1 );
  21301. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21302. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21303. // update object positions
  21304. flare.positionScreen.copy( screenPosition )
  21305. if ( flare.customUpdateCallback ) {
  21306. flare.customUpdateCallback( flare );
  21307. } else {
  21308. flare.updateLensFlares();
  21309. }
  21310. // render flares
  21311. _gl.uniform1i( uniforms.renderType, 2 );
  21312. _gl.enable( _gl.BLEND );
  21313. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21314. sprite = flare.lensFlares[ j ];
  21315. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21316. screenPosition.x = sprite.x;
  21317. screenPosition.y = sprite.y;
  21318. screenPosition.z = sprite.z;
  21319. size = sprite.size * sprite.scale / viewportHeight;
  21320. scale.x = size * invAspect;
  21321. scale.y = size;
  21322. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21323. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21324. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21325. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21326. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21327. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21328. _renderer.setTexture( sprite.texture, 1 );
  21329. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21330. }
  21331. }
  21332. }
  21333. }
  21334. // restore gl
  21335. _gl.enable( _gl.CULL_FACE );
  21336. _gl.enable( _gl.DEPTH_TEST );
  21337. _gl.depthMask( true );
  21338. };
  21339. function createProgram ( shader ) {
  21340. var program = _gl.createProgram();
  21341. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21342. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21343. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21344. _gl.shaderSource( vertexShader, shader.vertexShader );
  21345. _gl.compileShader( fragmentShader );
  21346. _gl.compileShader( vertexShader );
  21347. _gl.attachShader( program, fragmentShader );
  21348. _gl.attachShader( program, vertexShader );
  21349. _gl.linkProgram( program );
  21350. return program;
  21351. };
  21352. };/**
  21353. * @author alteredq / http://alteredqualia.com/
  21354. */
  21355. THREE.ShadowMapPlugin = function ( ) {
  21356. var _gl,
  21357. _renderer,
  21358. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21359. _frustum = new THREE.Frustum(),
  21360. _projScreenMatrix = new THREE.Matrix4(),
  21361. _min = new THREE.Vector3(),
  21362. _max = new THREE.Vector3();
  21363. this.init = function ( renderer ) {
  21364. _gl = renderer.context;
  21365. _renderer = renderer;
  21366. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21367. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21368. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21369. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21370. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21371. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21372. _depthMaterial._shadowPass = true;
  21373. _depthMaterialMorph._shadowPass = true;
  21374. _depthMaterialSkin._shadowPass = true;
  21375. _depthMaterialMorphSkin._shadowPass = true;
  21376. };
  21377. this.render = function ( scene, camera ) {
  21378. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21379. this.update( scene, camera );
  21380. };
  21381. this.update = function ( scene, camera ) {
  21382. var i, il, j, jl, n,
  21383. shadowMap, shadowMatrix, shadowCamera,
  21384. program, buffer, material,
  21385. webglObject, object, light,
  21386. renderList,
  21387. lights = [],
  21388. k = 0,
  21389. fog = null;
  21390. // set GL state for depth map
  21391. _gl.clearColor( 1, 1, 1, 1 );
  21392. _gl.disable( _gl.BLEND );
  21393. _gl.enable( _gl.CULL_FACE );
  21394. _gl.frontFace( _gl.CCW );
  21395. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21396. _gl.cullFace( _gl.FRONT );
  21397. } else {
  21398. _gl.cullFace( _gl.BACK );
  21399. }
  21400. _renderer.setDepthTest( true );
  21401. // preprocess lights
  21402. // - skip lights that are not casting shadows
  21403. // - create virtual lights for cascaded shadow maps
  21404. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21405. light = scene.__lights[ i ];
  21406. if ( ! light.castShadow ) continue;
  21407. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21408. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21409. var virtualLight;
  21410. if ( ! light.shadowCascadeArray[ n ] ) {
  21411. virtualLight = createVirtualLight( light, n );
  21412. virtualLight.originalCamera = camera;
  21413. var gyro = new THREE.Gyroscope();
  21414. gyro.position = light.shadowCascadeOffset;
  21415. gyro.add( virtualLight );
  21416. gyro.add( virtualLight.target );
  21417. camera.add( gyro );
  21418. light.shadowCascadeArray[ n ] = virtualLight;
  21419. console.log( "Created virtualLight", virtualLight );
  21420. } else {
  21421. virtualLight = light.shadowCascadeArray[ n ];
  21422. }
  21423. updateVirtualLight( light, n );
  21424. lights[ k ] = virtualLight;
  21425. k ++;
  21426. }
  21427. } else {
  21428. lights[ k ] = light;
  21429. k ++;
  21430. }
  21431. }
  21432. // render depth map
  21433. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21434. light = lights[ i ];
  21435. if ( ! light.shadowMap ) {
  21436. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  21437. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21438. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21439. light.shadowMatrix = new THREE.Matrix4();
  21440. }
  21441. if ( ! light.shadowCamera ) {
  21442. if ( light instanceof THREE.SpotLight ) {
  21443. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21444. } else if ( light instanceof THREE.DirectionalLight ) {
  21445. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21446. } else {
  21447. console.error( "Unsupported light type for shadow" );
  21448. continue;
  21449. }
  21450. scene.add( light.shadowCamera );
  21451. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21452. }
  21453. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21454. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21455. light.shadowCamera.add( light.cameraHelper );
  21456. }
  21457. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21458. updateShadowCamera( camera, light );
  21459. }
  21460. shadowMap = light.shadowMap;
  21461. shadowMatrix = light.shadowMatrix;
  21462. shadowCamera = light.shadowCamera;
  21463. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21464. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21465. shadowCamera.updateMatrixWorld();
  21466. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21467. if ( light.cameraHelper ) light.cameraHelper.visible = light.shadowCameraVisible;
  21468. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21469. // compute shadow matrix
  21470. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21471. 0.0, 0.5, 0.0, 0.5,
  21472. 0.0, 0.0, 0.5, 0.5,
  21473. 0.0, 0.0, 0.0, 1.0 );
  21474. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21475. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21476. // update camera matrices and frustum
  21477. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21478. _frustum.setFromMatrix( _projScreenMatrix );
  21479. // render shadow map
  21480. _renderer.setRenderTarget( shadowMap );
  21481. _renderer.clear();
  21482. // set object matrices & frustum culling
  21483. renderList = scene.__webglObjects;
  21484. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21485. webglObject = renderList[ j ];
  21486. object = webglObject.object;
  21487. webglObject.render = false;
  21488. if ( object.visible && object.castShadow ) {
  21489. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21490. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21491. webglObject.render = true;
  21492. }
  21493. }
  21494. }
  21495. // render regular objects
  21496. var objectMaterial, useMorphing, useSkinning;
  21497. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21498. webglObject = renderList[ j ];
  21499. if ( webglObject.render ) {
  21500. object = webglObject.object;
  21501. buffer = webglObject.buffer;
  21502. // culling is overriden globally for all objects
  21503. // while rendering depth map
  21504. // need to deal with MeshFaceMaterial somehow
  21505. // in that case just use the first of material.materials for now
  21506. // (proper solution would require to break objects by materials
  21507. // similarly to regular rendering and then set corresponding
  21508. // depth materials per each chunk instead of just once per object)
  21509. objectMaterial = getObjectMaterial( object );
  21510. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21511. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21512. if ( object.customDepthMaterial ) {
  21513. material = object.customDepthMaterial;
  21514. } else if ( useSkinning ) {
  21515. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21516. } else if ( useMorphing ) {
  21517. material = _depthMaterialMorph;
  21518. } else {
  21519. material = _depthMaterial;
  21520. }
  21521. if ( buffer instanceof THREE.BufferGeometry ) {
  21522. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21523. } else {
  21524. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21525. }
  21526. }
  21527. }
  21528. // set matrices and render immediate objects
  21529. renderList = scene.__webglObjectsImmediate;
  21530. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21531. webglObject = renderList[ j ];
  21532. object = webglObject.object;
  21533. if ( object.visible && object.castShadow ) {
  21534. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld );
  21535. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21536. }
  21537. }
  21538. }
  21539. // restore GL state
  21540. var clearColor = _renderer.getClearColor(),
  21541. clearAlpha = _renderer.getClearAlpha();
  21542. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21543. _gl.enable( _gl.BLEND );
  21544. if ( _renderer.shadowMapCullFace === THREE.CullFaceFront ) {
  21545. _gl.cullFace( _gl.BACK );
  21546. }
  21547. };
  21548. function createVirtualLight( light, cascade ) {
  21549. var virtualLight = new THREE.DirectionalLight();
  21550. virtualLight.isVirtual = true;
  21551. virtualLight.onlyShadow = true;
  21552. virtualLight.castShadow = true;
  21553. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21554. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21555. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21556. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21557. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21558. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21559. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21560. virtualLight.shadowDarkness = light.shadowDarkness;
  21561. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21562. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21563. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21564. virtualLight.pointsWorld = [];
  21565. virtualLight.pointsFrustum = [];
  21566. var pointsWorld = virtualLight.pointsWorld,
  21567. pointsFrustum = virtualLight.pointsFrustum;
  21568. for ( var i = 0; i < 8; i ++ ) {
  21569. pointsWorld[ i ] = new THREE.Vector3();
  21570. pointsFrustum[ i ] = new THREE.Vector3();
  21571. }
  21572. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21573. var farZ = light.shadowCascadeFarZ[ cascade ];
  21574. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21575. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21576. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21577. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21578. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21579. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21580. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21581. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21582. return virtualLight;
  21583. }
  21584. // Synchronize virtual light with the original light
  21585. function updateVirtualLight( light, cascade ) {
  21586. var virtualLight = light.shadowCascadeArray[ cascade ];
  21587. virtualLight.position.copy( light.position );
  21588. virtualLight.target.position.copy( light.target.position );
  21589. virtualLight.lookAt( virtualLight.target );
  21590. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21591. virtualLight.shadowDarkness = light.shadowDarkness;
  21592. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21593. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21594. var farZ = light.shadowCascadeFarZ[ cascade ];
  21595. var pointsFrustum = virtualLight.pointsFrustum;
  21596. pointsFrustum[ 0 ].z = nearZ;
  21597. pointsFrustum[ 1 ].z = nearZ;
  21598. pointsFrustum[ 2 ].z = nearZ;
  21599. pointsFrustum[ 3 ].z = nearZ;
  21600. pointsFrustum[ 4 ].z = farZ;
  21601. pointsFrustum[ 5 ].z = farZ;
  21602. pointsFrustum[ 6 ].z = farZ;
  21603. pointsFrustum[ 7 ].z = farZ;
  21604. }
  21605. // Fit shadow camera's ortho frustum to camera frustum
  21606. function updateShadowCamera( camera, light ) {
  21607. var shadowCamera = light.shadowCamera,
  21608. pointsFrustum = light.pointsFrustum,
  21609. pointsWorld = light.pointsWorld;
  21610. _min.set( Infinity, Infinity, Infinity );
  21611. _max.set( -Infinity, -Infinity, -Infinity );
  21612. for ( var i = 0; i < 8; i ++ ) {
  21613. var p = pointsWorld[ i ];
  21614. p.copy( pointsFrustum[ i ] );
  21615. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21616. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21617. if ( p.x < _min.x ) _min.x = p.x;
  21618. if ( p.x > _max.x ) _max.x = p.x;
  21619. if ( p.y < _min.y ) _min.y = p.y;
  21620. if ( p.y > _max.y ) _max.y = p.y;
  21621. if ( p.z < _min.z ) _min.z = p.z;
  21622. if ( p.z > _max.z ) _max.z = p.z;
  21623. }
  21624. shadowCamera.left = _min.x;
  21625. shadowCamera.right = _max.x;
  21626. shadowCamera.top = _max.y;
  21627. shadowCamera.bottom = _min.y;
  21628. // can't really fit near/far
  21629. //shadowCamera.near = _min.z;
  21630. //shadowCamera.far = _max.z;
  21631. shadowCamera.updateProjectionMatrix();
  21632. }
  21633. // For the moment just ignore objects that have multiple materials with different animation methods
  21634. // Only the first material will be taken into account for deciding which depth material to use for shadow maps
  21635. function getObjectMaterial( object ) {
  21636. return object.material instanceof THREE.MeshFaceMaterial
  21637. ? object.material.materials[ 0 ]
  21638. : object.material;
  21639. };
  21640. };
  21641. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21642. /**
  21643. * @author mikael emtinger / http://gomo.se/
  21644. * @author alteredq / http://alteredqualia.com/
  21645. */
  21646. THREE.SpritePlugin = function ( ) {
  21647. var _gl, _renderer, _sprite = {};
  21648. this.init = function ( renderer ) {
  21649. _gl = renderer.context;
  21650. _renderer = renderer;
  21651. _sprite.vertices = new Float32Array( 8 + 8 );
  21652. _sprite.faces = new Uint16Array( 6 );
  21653. var i = 0;
  21654. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21655. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 0
  21656. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21657. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 1
  21658. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21659. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 2
  21660. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21661. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 3
  21662. i = 0;
  21663. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21664. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21665. _sprite.vertexBuffer = _gl.createBuffer();
  21666. _sprite.elementBuffer = _gl.createBuffer();
  21667. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21668. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21669. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21670. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21671. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21672. _sprite.attributes = {};
  21673. _sprite.uniforms = {};
  21674. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21675. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21676. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21677. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21678. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21679. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21680. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21681. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21682. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21683. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21684. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21685. _sprite.uniforms.sizeAttenuation = _gl.getUniformLocation( _sprite.program, "sizeAttenuation" );
  21686. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21687. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21688. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21689. _sprite.uniforms.fogType = _gl.getUniformLocation( _sprite.program, "fogType" );
  21690. _sprite.uniforms.fogDensity = _gl.getUniformLocation( _sprite.program, "fogDensity" );
  21691. _sprite.uniforms.fogNear = _gl.getUniformLocation( _sprite.program, "fogNear" );
  21692. _sprite.uniforms.fogFar = _gl.getUniformLocation( _sprite.program, "fogFar" );
  21693. _sprite.uniforms.fogColor = _gl.getUniformLocation( _sprite.program, "fogColor" );
  21694. _sprite.uniforms.alphaTest = _gl.getUniformLocation( _sprite.program, "alphaTest" );
  21695. };
  21696. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21697. var sprites = scene.__webglSprites,
  21698. nSprites = sprites.length;
  21699. if ( ! nSprites ) return;
  21700. var attributes = _sprite.attributes,
  21701. uniforms = _sprite.uniforms;
  21702. var invAspect = viewportHeight / viewportWidth;
  21703. var halfViewportWidth = viewportWidth * 0.5,
  21704. halfViewportHeight = viewportHeight * 0.5;
  21705. // setup gl
  21706. _gl.useProgram( _sprite.program );
  21707. _gl.enableVertexAttribArray( attributes.position );
  21708. _gl.enableVertexAttribArray( attributes.uv );
  21709. _gl.disable( _gl.CULL_FACE );
  21710. _gl.enable( _gl.BLEND );
  21711. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21712. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21713. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21714. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21715. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera.projectionMatrix.elements );
  21716. _gl.activeTexture( _gl.TEXTURE0 );
  21717. _gl.uniform1i( uniforms.map, 0 );
  21718. var oldFogType = 0;
  21719. var sceneFogType = 0;
  21720. var fog = scene.fog;
  21721. if ( fog ) {
  21722. _gl.uniform3f( uniforms.fogColor, fog.color.r, fog.color.g, fog.color.b );
  21723. if ( fog instanceof THREE.Fog ) {
  21724. _gl.uniform1f( uniforms.fogNear, fog.near );
  21725. _gl.uniform1f( uniforms.fogFar, fog.far );
  21726. _gl.uniform1i( uniforms.fogType, 1 );
  21727. oldFogType = 1;
  21728. sceneFogType = 1;
  21729. } else if ( fog instanceof THREE.FogExp2 ) {
  21730. _gl.uniform1f( uniforms.fogDensity, fog.density );
  21731. _gl.uniform1i( uniforms.fogType, 2 );
  21732. oldFogType = 2;
  21733. sceneFogType = 2;
  21734. }
  21735. } else {
  21736. _gl.uniform1i( uniforms.fogType, 0 );
  21737. oldFogType = 0;
  21738. sceneFogType = 0;
  21739. }
  21740. // update positions and sort
  21741. var i, sprite, material, screenPosition, size, fogType, scale = [];
  21742. for( i = 0; i < nSprites; i ++ ) {
  21743. sprite = sprites[ i ];
  21744. material = sprite.material;
  21745. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21746. if ( ! material.useScreenCoordinates ) {
  21747. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld );
  21748. sprite.z = - sprite._modelViewMatrix.elements[ 14 ];
  21749. } else {
  21750. sprite.z = - sprite.position.z;
  21751. }
  21752. }
  21753. sprites.sort( painterSortStable );
  21754. // render all sprites
  21755. for( i = 0; i < nSprites; i ++ ) {
  21756. sprite = sprites[ i ];
  21757. material = sprite.material;
  21758. if ( ! sprite.visible || material.opacity === 0 ) continue;
  21759. if ( material.map && material.map.image && material.map.image.width ) {
  21760. _gl.uniform1f( uniforms.alphaTest, material.alphaTest );
  21761. if ( material.useScreenCoordinates ) {
  21762. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21763. _gl.uniform3f(
  21764. uniforms.screenPosition,
  21765. ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21766. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21767. Math.max( 0, Math.min( 1, sprite.position.z ) )
  21768. );
  21769. } else {
  21770. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21771. _gl.uniform1i( uniforms.sizeAttenuation, material.sizeAttenuation ? 1 : 0 );
  21772. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements );
  21773. }
  21774. if ( scene.fog && material.fog ) {
  21775. fogType = sceneFogType;
  21776. } else {
  21777. fogType = 0;
  21778. }
  21779. if ( oldFogType !== fogType ) {
  21780. _gl.uniform1i( uniforms.fogType, fogType );
  21781. oldFogType = fogType;
  21782. }
  21783. size = 1 / ( material.scaleByViewport ? viewportHeight : 1 );
  21784. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21785. scale[ 1 ] = size * sprite.scale.y;
  21786. _gl.uniform2f( uniforms.uvScale, material.uvScale.x, material.uvScale.y );
  21787. _gl.uniform2f( uniforms.uvOffset, material.uvOffset.x, material.uvOffset.y );
  21788. _gl.uniform2f( uniforms.alignment, material.alignment.x, material.alignment.y );
  21789. _gl.uniform1f( uniforms.opacity, material.opacity );
  21790. _gl.uniform3f( uniforms.color, material.color.r, material.color.g, material.color.b );
  21791. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21792. _gl.uniform2fv( uniforms.scale, scale );
  21793. _renderer.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  21794. _renderer.setDepthTest( material.depthTest );
  21795. _renderer.setDepthWrite( material.depthWrite );
  21796. _renderer.setTexture( material.map, 0 );
  21797. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21798. }
  21799. }
  21800. // restore gl
  21801. _gl.enable( _gl.CULL_FACE );
  21802. };
  21803. function createProgram ( shader ) {
  21804. var program = _gl.createProgram();
  21805. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21806. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21807. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21808. _gl.shaderSource( vertexShader, shader.vertexShader );
  21809. _gl.compileShader( fragmentShader );
  21810. _gl.compileShader( vertexShader );
  21811. _gl.attachShader( program, fragmentShader );
  21812. _gl.attachShader( program, vertexShader );
  21813. _gl.linkProgram( program );
  21814. return program;
  21815. };
  21816. function painterSortStable ( a, b ) {
  21817. if ( a.z !== b.z ) {
  21818. return b.z - a.z;
  21819. } else {
  21820. return b.id - a.id;
  21821. }
  21822. };
  21823. };/**
  21824. * @author alteredq / http://alteredqualia.com/
  21825. */
  21826. THREE.DepthPassPlugin = function ( ) {
  21827. this.enabled = false;
  21828. this.renderTarget = null;
  21829. var _gl,
  21830. _renderer,
  21831. _depthMaterial, _depthMaterialMorph, _depthMaterialSkin, _depthMaterialMorphSkin,
  21832. _frustum = new THREE.Frustum(),
  21833. _projScreenMatrix = new THREE.Matrix4();
  21834. this.init = function ( renderer ) {
  21835. _gl = renderer.context;
  21836. _renderer = renderer;
  21837. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21838. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21839. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21840. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21841. _depthMaterialSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, skinning: true } );
  21842. _depthMaterialMorphSkin = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true, skinning: true } );
  21843. _depthMaterial._shadowPass = true;
  21844. _depthMaterialMorph._shadowPass = true;
  21845. _depthMaterialSkin._shadowPass = true;
  21846. _depthMaterialMorphSkin._shadowPass = true;
  21847. };
  21848. this.render = function ( scene, camera ) {
  21849. if ( ! this.enabled ) return;
  21850. this.update( scene, camera );
  21851. };
  21852. this.update = function ( scene, camera ) {
  21853. var i, il, j, jl, n,
  21854. program, buffer, material,
  21855. webglObject, object, light,
  21856. renderList,
  21857. fog = null;
  21858. // set GL state for depth map
  21859. _gl.clearColor( 1, 1, 1, 1 );
  21860. _gl.disable( _gl.BLEND );
  21861. _renderer.setDepthTest( true );
  21862. // update scene
  21863. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21864. // update camera matrices and frustum
  21865. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21866. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21867. _frustum.setFromMatrix( _projScreenMatrix );
  21868. // render depth map
  21869. _renderer.setRenderTarget( this.renderTarget );
  21870. _renderer.clear();
  21871. // set object matrices & frustum culling
  21872. renderList = scene.__webglObjects;
  21873. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21874. webglObject = renderList[ j ];
  21875. object = webglObject.object;
  21876. webglObject.render = false;
  21877. if ( object.visible ) {
  21878. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21879. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21880. webglObject.render = true;
  21881. }
  21882. }
  21883. }
  21884. // render regular objects
  21885. var objectMaterial, useMorphing, useSkinning;
  21886. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21887. webglObject = renderList[ j ];
  21888. if ( webglObject.render ) {
  21889. object = webglObject.object;
  21890. buffer = webglObject.buffer;
  21891. // todo: create proper depth material for particles
  21892. if ( object instanceof THREE.ParticleSystem && !object.customDepthMaterial ) continue;
  21893. objectMaterial = getObjectMaterial( object );
  21894. if ( objectMaterial ) _renderer.setMaterialFaces( object.material );
  21895. useMorphing = object.geometry.morphTargets.length > 0 && objectMaterial.morphTargets;
  21896. useSkinning = object instanceof THREE.SkinnedMesh && objectMaterial.skinning;
  21897. if ( object.customDepthMaterial ) {
  21898. material = object.customDepthMaterial;
  21899. } else if ( useSkinning ) {
  21900. material = useMorphing ? _depthMaterialMorphSkin : _depthMaterialSkin;
  21901. } else if ( useMorphing ) {
  21902. material = _depthMaterialMorph;
  21903. } else {
  21904. material = _depthMaterial;
  21905. }
  21906. if ( buffer instanceof THREE.BufferGeometry ) {
  21907. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21908. } else {
  21909. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21910. }
  21911. }
  21912. }
  21913. // set matrices and render immediate objects
  21914. renderList = scene.__webglObjectsImmediate;
  21915. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21916. webglObject = renderList[ j ];
  21917. object = webglObject.object;
  21918. if ( object.visible ) {
  21919. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld );
  21920. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21921. }
  21922. }
  21923. // restore GL state
  21924. var clearColor = _renderer.getClearColor(),
  21925. clearAlpha = _renderer.getClearAlpha();
  21926. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21927. _gl.enable( _gl.BLEND );
  21928. };
  21929. // For the moment just ignore objects that have multiple materials with different animation methods
  21930. // Only the first material will be taken into account for deciding which depth material to use
  21931. function getObjectMaterial( object ) {
  21932. return object.material instanceof THREE.MeshFaceMaterial
  21933. ? object.material.materials[ 0 ]
  21934. : object.material;
  21935. };
  21936. };
  21937. /**
  21938. * @author mikael emtinger / http://gomo.se/
  21939. *
  21940. */
  21941. THREE.ShaderFlares = {
  21942. 'lensFlareVertexTexture': {
  21943. vertexShader: [
  21944. "uniform vec3 screenPosition;",
  21945. "uniform vec2 scale;",
  21946. "uniform float rotation;",
  21947. "uniform int renderType;",
  21948. "uniform sampler2D occlusionMap;",
  21949. "attribute vec2 position;",
  21950. "attribute vec2 uv;",
  21951. "varying vec2 vUV;",
  21952. "varying float vVisibility;",
  21953. "void main() {",
  21954. "vUV = uv;",
  21955. "vec2 pos = position;",
  21956. "if( renderType == 2 ) {",
  21957. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21958. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21959. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21960. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21961. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21962. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21963. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21964. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21965. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21966. "vVisibility = ( visibility.r / 9.0 ) *",
  21967. "( 1.0 - visibility.g / 9.0 ) *",
  21968. "( visibility.b / 9.0 ) *",
  21969. "( 1.0 - visibility.a / 9.0 );",
  21970. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21971. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21972. "}",
  21973. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21974. "}"
  21975. ].join( "\n" ),
  21976. fragmentShader: [
  21977. "precision mediump float;",
  21978. "uniform sampler2D map;",
  21979. "uniform float opacity;",
  21980. "uniform int renderType;",
  21981. "uniform vec3 color;",
  21982. "varying vec2 vUV;",
  21983. "varying float vVisibility;",
  21984. "void main() {",
  21985. // pink square
  21986. "if( renderType == 0 ) {",
  21987. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21988. // restore
  21989. "} else if( renderType == 1 ) {",
  21990. "gl_FragColor = texture2D( map, vUV );",
  21991. // flare
  21992. "} else {",
  21993. "vec4 texture = texture2D( map, vUV );",
  21994. "texture.a *= opacity * vVisibility;",
  21995. "gl_FragColor = texture;",
  21996. "gl_FragColor.rgb *= color;",
  21997. "}",
  21998. "}"
  21999. ].join( "\n" )
  22000. },
  22001. 'lensFlare': {
  22002. vertexShader: [
  22003. "uniform vec3 screenPosition;",
  22004. "uniform vec2 scale;",
  22005. "uniform float rotation;",
  22006. "uniform int renderType;",
  22007. "attribute vec2 position;",
  22008. "attribute vec2 uv;",
  22009. "varying vec2 vUV;",
  22010. "void main() {",
  22011. "vUV = uv;",
  22012. "vec2 pos = position;",
  22013. "if( renderType == 2 ) {",
  22014. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  22015. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  22016. "}",
  22017. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  22018. "}"
  22019. ].join( "\n" ),
  22020. fragmentShader: [
  22021. "precision mediump float;",
  22022. "uniform sampler2D map;",
  22023. "uniform sampler2D occlusionMap;",
  22024. "uniform float opacity;",
  22025. "uniform int renderType;",
  22026. "uniform vec3 color;",
  22027. "varying vec2 vUV;",
  22028. "void main() {",
  22029. // pink square
  22030. "if( renderType == 0 ) {",
  22031. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  22032. // restore
  22033. "} else if( renderType == 1 ) {",
  22034. "gl_FragColor = texture2D( map, vUV );",
  22035. // flare
  22036. "} else {",
  22037. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  22038. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  22039. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  22040. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  22041. "visibility = ( 1.0 - visibility / 4.0 );",
  22042. "vec4 texture = texture2D( map, vUV );",
  22043. "texture.a *= opacity * visibility;",
  22044. "gl_FragColor = texture;",
  22045. "gl_FragColor.rgb *= color;",
  22046. "}",
  22047. "}"
  22048. ].join( "\n" )
  22049. }
  22050. };
  22051. /**
  22052. * @author mikael emtinger / http://gomo.se/
  22053. * @author alteredq / http://alteredqualia.com/
  22054. *
  22055. */
  22056. THREE.ShaderSprite = {
  22057. 'sprite': {
  22058. vertexShader: [
  22059. "uniform int useScreenCoordinates;",
  22060. "uniform int sizeAttenuation;",
  22061. "uniform vec3 screenPosition;",
  22062. "uniform mat4 modelViewMatrix;",
  22063. "uniform mat4 projectionMatrix;",
  22064. "uniform float rotation;",
  22065. "uniform vec2 scale;",
  22066. "uniform vec2 alignment;",
  22067. "uniform vec2 uvOffset;",
  22068. "uniform vec2 uvScale;",
  22069. "attribute vec2 position;",
  22070. "attribute vec2 uv;",
  22071. "varying vec2 vUV;",
  22072. "void main() {",
  22073. "vUV = uvOffset + uv * uvScale;",
  22074. "vec2 alignedPosition = position + alignment;",
  22075. "vec2 rotatedPosition;",
  22076. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  22077. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  22078. "vec4 finalPosition;",
  22079. "if( useScreenCoordinates != 0 ) {",
  22080. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  22081. "} else {",
  22082. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  22083. "finalPosition.xy += rotatedPosition * ( sizeAttenuation == 1 ? 1.0 : finalPosition.z );",
  22084. "}",
  22085. "gl_Position = finalPosition;",
  22086. "}"
  22087. ].join( "\n" ),
  22088. fragmentShader: [
  22089. "precision mediump float;",
  22090. "uniform vec3 color;",
  22091. "uniform sampler2D map;",
  22092. "uniform float opacity;",
  22093. "uniform int fogType;",
  22094. "uniform vec3 fogColor;",
  22095. "uniform float fogDensity;",
  22096. "uniform float fogNear;",
  22097. "uniform float fogFar;",
  22098. "uniform float alphaTest;",
  22099. "varying vec2 vUV;",
  22100. "void main() {",
  22101. "vec4 texture = texture2D( map, vUV );",
  22102. "if ( texture.a < alphaTest ) discard;",
  22103. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  22104. "if ( fogType > 0 ) {",
  22105. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  22106. "float fogFactor = 0.0;",
  22107. "if ( fogType == 1 ) {",
  22108. "fogFactor = smoothstep( fogNear, fogFar, depth );",
  22109. "} else {",
  22110. "const float LOG2 = 1.442695;",
  22111. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  22112. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  22113. "}",
  22114. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  22115. "}",
  22116. "}"
  22117. ].join( "\n" )
  22118. }
  22119. };