Three.js 797 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223
  1. /**
  2. * @author mr.doob / http://mrdoob.com/
  3. */
  4. var THREE = THREE || { REVISION: '49dev' };
  5. if ( ! self.Int32Array ) {
  6. self.Int32Array = Array;
  7. self.Float32Array = Array;
  8. }
  9. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  10. // http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
  11. // requestAnimationFrame polyfill by Erik Möller
  12. // fixes from Paul Irish and Tino Zijdel
  13. (function() {
  14. var lastTime = 0;
  15. var vendors = ['ms', 'moz', 'webkit', 'o'];
  16. for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
  17. window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
  18. window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
  19. || window[vendors[x]+'CancelRequestAnimationFrame'];
  20. }
  21. if (!window.requestAnimationFrame)
  22. window.requestAnimationFrame = function(callback, element) {
  23. var currTime = new Date().getTime();
  24. var timeToCall = Math.max(0, 16 - (currTime - lastTime));
  25. var id = window.setTimeout(function() { callback(currTime + timeToCall); },
  26. timeToCall);
  27. lastTime = currTime + timeToCall;
  28. return id;
  29. };
  30. if (!window.cancelAnimationFrame)
  31. window.cancelAnimationFrame = function(id) {
  32. clearTimeout(id);
  33. };
  34. }());
  35. /**
  36. * @author alteredq / http://alteredqualia.com/
  37. */
  38. THREE.Clock = function ( autoStart ) {
  39. this.autoStart = ( autoStart !== undefined ) ? autoStart : true;
  40. this.startTime = 0;
  41. this.oldTime = 0;
  42. this.elapsedTime = 0;
  43. this.running = false;
  44. };
  45. THREE.Clock.prototype.start = function () {
  46. this.startTime = Date.now();
  47. this.oldTime = this.startTime;
  48. this.running = true;
  49. };
  50. THREE.Clock.prototype.stop = function () {
  51. this.getElapsedTime();
  52. this.running = false;
  53. };
  54. THREE.Clock.prototype.getElapsedTime = function () {
  55. this.elapsedTime += this.getDelta();
  56. return this.elapsedTime;
  57. };
  58. THREE.Clock.prototype.getDelta = function () {
  59. var diff = 0;
  60. if ( this.autoStart && ! this.running ) {
  61. this.start();
  62. }
  63. if ( this.running ) {
  64. var newTime = Date.now();
  65. diff = 0.001 * ( newTime - this.oldTime );
  66. this.oldTime = newTime;
  67. this.elapsedTime += diff;
  68. }
  69. return diff;
  70. };/**
  71. * @author mr.doob / http://mrdoob.com/
  72. */
  73. THREE.Color = function ( hex ) {
  74. if ( hex !== undefined ) this.setHex( hex );
  75. return this;
  76. };
  77. THREE.Color.prototype = {
  78. constructor: THREE.Color,
  79. r: 1, g: 1, b: 1,
  80. copy: function ( color ) {
  81. this.r = color.r;
  82. this.g = color.g;
  83. this.b = color.b;
  84. return this;
  85. },
  86. copyGammaToLinear: function ( color ) {
  87. this.r = color.r * color.r;
  88. this.g = color.g * color.g;
  89. this.b = color.b * color.b;
  90. return this;
  91. },
  92. copyLinearToGamma: function ( color ) {
  93. this.r = Math.sqrt( color.r );
  94. this.g = Math.sqrt( color.g );
  95. this.b = Math.sqrt( color.b );
  96. return this;
  97. },
  98. convertGammaToLinear: function () {
  99. var r = this.r, g = this.g, b = this.b;
  100. this.r = r * r;
  101. this.g = g * g;
  102. this.b = b * b;
  103. return this;
  104. },
  105. convertLinearToGamma: function () {
  106. this.r = Math.sqrt( this.r );
  107. this.g = Math.sqrt( this.g );
  108. this.b = Math.sqrt( this.b );
  109. return this;
  110. },
  111. setRGB: function ( r, g, b ) {
  112. this.r = r;
  113. this.g = g;
  114. this.b = b;
  115. return this;
  116. },
  117. setHSV: function ( h, s, v ) {
  118. // based on MochiKit implementation by Bob Ippolito
  119. // h,s,v ranges are < 0.0 - 1.0 >
  120. var i, f, p, q, t;
  121. if ( v === 0 ) {
  122. this.r = this.g = this.b = 0;
  123. } else {
  124. i = Math.floor( h * 6 );
  125. f = ( h * 6 ) - i;
  126. p = v * ( 1 - s );
  127. q = v * ( 1 - ( s * f ) );
  128. t = v * ( 1 - ( s * ( 1 - f ) ) );
  129. switch ( i ) {
  130. case 1: this.r = q; this.g = v; this.b = p; break;
  131. case 2: this.r = p; this.g = v; this.b = t; break;
  132. case 3: this.r = p; this.g = q; this.b = v; break;
  133. case 4: this.r = t; this.g = p; this.b = v; break;
  134. case 5: this.r = v; this.g = p; this.b = q; break;
  135. case 6: // fall through
  136. case 0: this.r = v; this.g = t; this.b = p; break;
  137. }
  138. }
  139. return this;
  140. },
  141. setHex: function ( hex ) {
  142. hex = Math.floor( hex );
  143. this.r = ( hex >> 16 & 255 ) / 255;
  144. this.g = ( hex >> 8 & 255 ) / 255;
  145. this.b = ( hex & 255 ) / 255;
  146. return this;
  147. },
  148. lerpSelf: function ( color, alpha ) {
  149. this.r += ( color.r - this.r ) * alpha;
  150. this.g += ( color.g - this.g ) * alpha;
  151. this.b += ( color.b - this.b ) * alpha;
  152. return this;
  153. },
  154. getHex: function () {
  155. return Math.floor( this.r * 255 ) << 16 ^ Math.floor( this.g * 255 ) << 8 ^ Math.floor( this.b * 255 );
  156. },
  157. getContextStyle: function () {
  158. return 'rgb(' + Math.floor( this.r * 255 ) + ',' + Math.floor( this.g * 255 ) + ',' + Math.floor( this.b * 255 ) + ')';
  159. },
  160. clone: function () {
  161. return new THREE.Color().setRGB( this.r, this.g, this.b );
  162. }
  163. };
  164. /**
  165. * @author mr.doob / http://mrdoob.com/
  166. * @author philogb / http://blog.thejit.org/
  167. * @author egraether / http://egraether.com/
  168. * @author zz85 / http://www.lab4games.net/zz85/blog
  169. */
  170. THREE.Vector2 = function ( x, y ) {
  171. this.x = x || 0;
  172. this.y = y || 0;
  173. };
  174. THREE.Vector2.prototype = {
  175. constructor: THREE.Vector2,
  176. set: function ( x, y ) {
  177. this.x = x;
  178. this.y = y;
  179. return this;
  180. },
  181. copy: function ( v ) {
  182. this.x = v.x;
  183. this.y = v.y;
  184. return this;
  185. },
  186. add: function ( a, b ) {
  187. this.x = a.x + b.x;
  188. this.y = a.y + b.y;
  189. return this;
  190. },
  191. addSelf: function ( v ) {
  192. this.x += v.x;
  193. this.y += v.y;
  194. return this;
  195. },
  196. sub: function ( a, b ) {
  197. this.x = a.x - b.x;
  198. this.y = a.y - b.y;
  199. return this;
  200. },
  201. subSelf: function ( v ) {
  202. this.x -= v.x;
  203. this.y -= v.y;
  204. return this;
  205. },
  206. multiplyScalar: function ( s ) {
  207. this.x *= s;
  208. this.y *= s;
  209. return this;
  210. },
  211. divideScalar: function ( s ) {
  212. if ( s ) {
  213. this.x /= s;
  214. this.y /= s;
  215. } else {
  216. this.set( 0, 0 );
  217. }
  218. return this;
  219. },
  220. negate: function() {
  221. return this.multiplyScalar( - 1 );
  222. },
  223. dot: function ( v ) {
  224. return this.x * v.x + this.y * v.y;
  225. },
  226. lengthSq: function () {
  227. return this.x * this.x + this.y * this.y;
  228. },
  229. length: function () {
  230. return Math.sqrt( this.lengthSq() );
  231. },
  232. normalize: function () {
  233. return this.divideScalar( this.length() );
  234. },
  235. distanceTo: function ( v ) {
  236. return Math.sqrt( this.distanceToSquared( v ) );
  237. },
  238. distanceToSquared: function ( v ) {
  239. var dx = this.x - v.x, dy = this.y - v.y;
  240. return dx * dx + dy * dy;
  241. },
  242. setLength: function ( l ) {
  243. return this.normalize().multiplyScalar( l );
  244. },
  245. lerpSelf: function ( v, alpha ) {
  246. this.x += ( v.x - this.x ) * alpha;
  247. this.y += ( v.y - this.y ) * alpha;
  248. return this;
  249. },
  250. equals: function( v ) {
  251. return ( ( v.x === this.x ) && ( v.y === this.y ) );
  252. },
  253. isZero: function () {
  254. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  255. },
  256. clone: function () {
  257. return new THREE.Vector2( this.x, this.y );
  258. }
  259. };
  260. /**
  261. * @author mr.doob / http://mrdoob.com/
  262. * @author kile / http://kile.stravaganza.org/
  263. * @author philogb / http://blog.thejit.org/
  264. * @author mikael emtinger / http://gomo.se/
  265. * @author egraether / http://egraether.com/
  266. */
  267. THREE.Vector3 = function ( x, y, z ) {
  268. this.x = x || 0;
  269. this.y = y || 0;
  270. this.z = z || 0;
  271. };
  272. THREE.Vector3.prototype = {
  273. constructor: THREE.Vector3,
  274. set: function ( x, y, z ) {
  275. this.x = x;
  276. this.y = y;
  277. this.z = z;
  278. return this;
  279. },
  280. setX: function ( x ) {
  281. this.x = x;
  282. return this;
  283. },
  284. setY: function ( y ) {
  285. this.y = y;
  286. return this;
  287. },
  288. setZ: function ( z ) {
  289. this.z = z;
  290. return this;
  291. },
  292. copy: function ( v ) {
  293. this.x = v.x;
  294. this.y = v.y;
  295. this.z = v.z;
  296. return this;
  297. },
  298. add: function ( a, b ) {
  299. this.x = a.x + b.x;
  300. this.y = a.y + b.y;
  301. this.z = a.z + b.z;
  302. return this;
  303. },
  304. addSelf: function ( v ) {
  305. this.x += v.x;
  306. this.y += v.y;
  307. this.z += v.z;
  308. return this;
  309. },
  310. addScalar: function ( s ) {
  311. this.x += s;
  312. this.y += s;
  313. this.z += s;
  314. return this;
  315. },
  316. sub: function ( a, b ) {
  317. this.x = a.x - b.x;
  318. this.y = a.y - b.y;
  319. this.z = a.z - b.z;
  320. return this;
  321. },
  322. subSelf: function ( v ) {
  323. this.x -= v.x;
  324. this.y -= v.y;
  325. this.z -= v.z;
  326. return this;
  327. },
  328. multiply: function ( a, b ) {
  329. this.x = a.x * b.x;
  330. this.y = a.y * b.y;
  331. this.z = a.z * b.z;
  332. return this;
  333. },
  334. multiplySelf: function ( v ) {
  335. this.x *= v.x;
  336. this.y *= v.y;
  337. this.z *= v.z;
  338. return this;
  339. },
  340. multiplyScalar: function ( s ) {
  341. this.x *= s;
  342. this.y *= s;
  343. this.z *= s;
  344. return this;
  345. },
  346. divideSelf: function ( v ) {
  347. this.x /= v.x;
  348. this.y /= v.y;
  349. this.z /= v.z;
  350. return this;
  351. },
  352. divideScalar: function ( s ) {
  353. if ( s ) {
  354. this.x /= s;
  355. this.y /= s;
  356. this.z /= s;
  357. } else {
  358. this.x = 0;
  359. this.y = 0;
  360. this.z = 0;
  361. }
  362. return this;
  363. },
  364. negate: function() {
  365. return this.multiplyScalar( - 1 );
  366. },
  367. dot: function ( v ) {
  368. return this.x * v.x + this.y * v.y + this.z * v.z;
  369. },
  370. lengthSq: function () {
  371. return this.x * this.x + this.y * this.y + this.z * this.z;
  372. },
  373. length: function () {
  374. return Math.sqrt( this.lengthSq() );
  375. },
  376. lengthManhattan: function () {
  377. return Math.abs( this.x ) + Math.abs( this.y ) + Math.abs( this.z );
  378. },
  379. normalize: function () {
  380. return this.divideScalar( this.length() );
  381. },
  382. setLength: function ( l ) {
  383. return this.normalize().multiplyScalar( l );
  384. },
  385. lerpSelf: function ( v, alpha ) {
  386. this.x += ( v.x - this.x ) * alpha;
  387. this.y += ( v.y - this.y ) * alpha;
  388. this.z += ( v.z - this.z ) * alpha;
  389. return this;
  390. },
  391. cross: function ( a, b ) {
  392. this.x = a.y * b.z - a.z * b.y;
  393. this.y = a.z * b.x - a.x * b.z;
  394. this.z = a.x * b.y - a.y * b.x;
  395. return this;
  396. },
  397. crossSelf: function ( v ) {
  398. var x = this.x, y = this.y, z = this.z;
  399. this.x = y * v.z - z * v.y;
  400. this.y = z * v.x - x * v.z;
  401. this.z = x * v.y - y * v.x;
  402. return this;
  403. },
  404. distanceTo: function ( v ) {
  405. return Math.sqrt( this.distanceToSquared( v ) );
  406. },
  407. distanceToSquared: function ( v ) {
  408. return new THREE.Vector3().sub( this, v ).lengthSq();
  409. },
  410. getPositionFromMatrix: function ( m ) {
  411. this.x = m.elements[12];
  412. this.y = m.elements[13];
  413. this.z = m.elements[14];
  414. return this;
  415. },
  416. getRotationFromMatrix: function ( m, scale ) {
  417. var sx = scale ? scale.x : 1;
  418. var sy = scale ? scale.y : 1;
  419. var sz = scale ? scale.z : 1;
  420. var m11 = m.elements[0] / sx, m12 = m.elements[4] / sy, m13 = m.elements[8] / sz;
  421. var m21 = m.elements[1] / sx, m22 = m.elements[5] / sy, m23 = m.elements[9] / sz;
  422. var m33 = m.elements[10] / sz;
  423. this.y = Math.asin( m13 );
  424. var cosY = Math.cos( this.y );
  425. if ( Math.abs( cosY ) > 0.00001 ) {
  426. this.x = Math.atan2( - m23 / cosY, m33 / cosY );
  427. this.z = Math.atan2( - m12 / cosY, m11 / cosY );
  428. } else {
  429. this.x = 0;
  430. this.z = Math.atan2( m21, m22 );
  431. }
  432. return this;
  433. },
  434. /*
  435. // from http://www.mathworks.com/matlabcentral/fileexchange/20696-function-to-convert-between-dcm-euler-angles-quaternions-and-euler-vectors/content/SpinCalc.m
  436. // order XYZ
  437. getEulerXYZFromQuaternion: function ( q ) {
  438. this.x = Math.atan2( 2 * ( q.x * q.w - q.y * q.z ), ( q.w * q.w - q.x * q.x - q.y * q.y + q.z * q.z ) );
  439. this.y = Math.asin( 2 * ( q.x * q.z + q.y * q.w ) );
  440. this.z = Math.atan2( 2 * ( q.z * q.w - q.x * q.y ), ( q.w * q.w + q.x * q.x - q.y * q.y - q.z * q.z ) );
  441. },
  442. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/quaternionToEuler/index.htm
  443. // order YZX (assuming heading == y, attitude == z, bank == x)
  444. getEulerYZXFromQuaternion: function ( q ) {
  445. var sqw = q.w * q.w;
  446. var sqx = q.x * q.x;
  447. var sqy = q.y * q.y;
  448. var sqz = q.z * q.z;
  449. var unit = sqx + sqy + sqz + sqw; // if normalised is one, otherwise is correction factor
  450. var test = q.x * q.y + q.z * q.w;
  451. if ( test > 0.499 * unit ) { // singularity at north pole
  452. this.y = 2 * Math.atan2( q.x, q.w );
  453. this.z = Math.PI / 2;
  454. this.x = 0;
  455. return;
  456. }
  457. if ( test < -0.499 * unit ) { // singularity at south pole
  458. this.y = -2 * Math.atan2( q.x, q.w );
  459. this.z = -Math.PI / 2;
  460. this.x = 0;
  461. return;
  462. }
  463. this.y = Math.atan2( 2 * q.y * q.w - 2 * q.x * q.z, sqx - sqy - sqz + sqw );
  464. this.z = Math.asin( 2 * test / unit );
  465. this.x = Math.atan2( 2 * q.x * q.w - 2 * q.y * q.z, -sqx + sqy - sqz + sqw );
  466. },
  467. */
  468. getScaleFromMatrix: function ( m ) {
  469. var sx = this.set( m.elements[0], m.elements[1], m.elements[2] ).length();
  470. var sy = this.set( m.elements[4], m.elements[5], m.elements[6] ).length();
  471. var sz = this.set( m.elements[8], m.elements[9], m.elements[10] ).length();
  472. this.x = sx;
  473. this.y = sy;
  474. this.z = sz;
  475. },
  476. equals: function ( v ) {
  477. return ( ( v.x === this.x ) && ( v.y === this.y ) && ( v.z === this.z ) );
  478. },
  479. isZero: function () {
  480. return ( this.lengthSq() < 0.0001 /* almostZero */ );
  481. },
  482. clone: function () {
  483. return new THREE.Vector3( this.x, this.y, this.z );
  484. }
  485. };
  486. /**
  487. * @author supereggbert / http://www.paulbrunt.co.uk/
  488. * @author philogb / http://blog.thejit.org/
  489. * @author mikael emtinger / http://gomo.se/
  490. * @author egraether / http://egraether.com/
  491. */
  492. THREE.Vector4 = function ( x, y, z, w ) {
  493. this.x = x || 0;
  494. this.y = y || 0;
  495. this.z = z || 0;
  496. this.w = ( w !== undefined ) ? w : 1;
  497. };
  498. THREE.Vector4.prototype = {
  499. constructor: THREE.Vector4,
  500. set: function ( x, y, z, w ) {
  501. this.x = x;
  502. this.y = y;
  503. this.z = z;
  504. this.w = w;
  505. return this;
  506. },
  507. copy: function ( v ) {
  508. this.x = v.x;
  509. this.y = v.y;
  510. this.z = v.z;
  511. this.w = ( v.w !== undefined ) ? v.w : 1;
  512. return this;
  513. },
  514. add: function ( a, b ) {
  515. this.x = a.x + b.x;
  516. this.y = a.y + b.y;
  517. this.z = a.z + b.z;
  518. this.w = a.w + b.w;
  519. return this;
  520. },
  521. addSelf: function ( v ) {
  522. this.x += v.x;
  523. this.y += v.y;
  524. this.z += v.z;
  525. this.w += v.w;
  526. return this;
  527. },
  528. sub: function ( a, b ) {
  529. this.x = a.x - b.x;
  530. this.y = a.y - b.y;
  531. this.z = a.z - b.z;
  532. this.w = a.w - b.w;
  533. return this;
  534. },
  535. subSelf: function ( v ) {
  536. this.x -= v.x;
  537. this.y -= v.y;
  538. this.z -= v.z;
  539. this.w -= v.w;
  540. return this;
  541. },
  542. multiplyScalar: function ( s ) {
  543. this.x *= s;
  544. this.y *= s;
  545. this.z *= s;
  546. this.w *= s;
  547. return this;
  548. },
  549. divideScalar: function ( s ) {
  550. if ( s ) {
  551. this.x /= s;
  552. this.y /= s;
  553. this.z /= s;
  554. this.w /= s;
  555. } else {
  556. this.x = 0;
  557. this.y = 0;
  558. this.z = 0;
  559. this.w = 1;
  560. }
  561. return this;
  562. },
  563. negate: function() {
  564. return this.multiplyScalar( -1 );
  565. },
  566. dot: function ( v ) {
  567. return this.x * v.x + this.y * v.y + this.z * v.z + this.w * v.w;
  568. },
  569. lengthSq: function () {
  570. return this.dot( this );
  571. },
  572. length: function () {
  573. return Math.sqrt( this.lengthSq() );
  574. },
  575. normalize: function () {
  576. return this.divideScalar( this.length() );
  577. },
  578. setLength: function ( l ) {
  579. return this.normalize().multiplyScalar( l );
  580. },
  581. lerpSelf: function ( v, alpha ) {
  582. this.x += ( v.x - this.x ) * alpha;
  583. this.y += ( v.y - this.y ) * alpha;
  584. this.z += ( v.z - this.z ) * alpha;
  585. this.w += ( v.w - this.w ) * alpha;
  586. return this;
  587. },
  588. clone: function () {
  589. return new THREE.Vector4( this.x, this.y, this.z, this.w );
  590. }
  591. };
  592. /**
  593. * @author mrdoob / http://mrdoob.com/
  594. * @author alteredq / http://alteredqualia.com/
  595. */
  596. THREE.Frustum = function ( ) {
  597. this.planes = [
  598. new THREE.Vector4(),
  599. new THREE.Vector4(),
  600. new THREE.Vector4(),
  601. new THREE.Vector4(),
  602. new THREE.Vector4(),
  603. new THREE.Vector4()
  604. ];
  605. };
  606. THREE.Frustum.prototype.setFromMatrix = function ( m ) {
  607. var i, plane,
  608. planes = this.planes;
  609. var me = m.elements;
  610. var me0 = me[0], me1 = me[1], me2 = me[2], me3 = me[3];
  611. var me4 = me[4], me5 = me[5], me6 = me[6], me7 = me[7];
  612. var me8 = me[8], me9 = me[9], me10 = me[10], me11 = me[11];
  613. var me12 = me[12], me13 = me[13], me14 = me[14], me15 = me[15];
  614. planes[ 0 ].set( me3 - me0, me7 - me4, me11 - me8, me15 - me12 );
  615. planes[ 1 ].set( me3 + me0, me7 + me4, me11 + me8, me15 + me12 );
  616. planes[ 2 ].set( me3 + me1, me7 + me5, me11 + me9, me15 + me13 );
  617. planes[ 3 ].set( me3 - me1, me7 - me5, me11 - me9, me15 - me13 );
  618. planes[ 4 ].set( me3 - me2, me7 - me6, me11 - me10, me15 - me14 );
  619. planes[ 5 ].set( me3 + me2, me7 + me6, me11 + me10, me15 + me14 );
  620. for ( i = 0; i < 6; i ++ ) {
  621. plane = planes[ i ];
  622. plane.divideScalar( Math.sqrt( plane.x * plane.x + plane.y * plane.y + plane.z * plane.z ) );
  623. }
  624. };
  625. THREE.Frustum.prototype.contains = function ( object ) {
  626. var distance,
  627. planes = this.planes,
  628. matrix = object.matrixWorld,
  629. me = matrix.elements,
  630. scale = THREE.Frustum.__v1.set( matrix.getColumnX().length(), matrix.getColumnY().length(), matrix.getColumnZ().length() ),
  631. radius = - object.geometry.boundingSphere.radius * Math.max( scale.x, Math.max( scale.y, scale.z ) );
  632. for ( var i = 0; i < 6; i ++ ) {
  633. distance = planes[ i ].x * me[12] + planes[ i ].y * me[13] + planes[ i ].z * me[14] + planes[ i ].w;
  634. if ( distance <= radius ) return false;
  635. }
  636. return true;
  637. };
  638. THREE.Frustum.__v1 = new THREE.Vector3();
  639. /**
  640. * @author mr.doob / http://mrdoob.com/
  641. */
  642. THREE.Ray = function ( origin, direction ) {
  643. this.origin = origin || new THREE.Vector3();
  644. this.direction = direction || new THREE.Vector3();
  645. var precision = 0.0001;
  646. this.setPrecision = function ( value ) {
  647. precision = value;
  648. };
  649. var a = new THREE.Vector3();
  650. var b = new THREE.Vector3();
  651. var c = new THREE.Vector3();
  652. var d = new THREE.Vector3();
  653. var originCopy = new THREE.Vector3();
  654. var directionCopy = new THREE.Vector3();
  655. var vector = new THREE.Vector3();
  656. var normal = new THREE.Vector3();
  657. var intersectPoint = new THREE.Vector3()
  658. this.intersectObject = function ( object ) {
  659. var intersect, intersects = [];
  660. if ( object instanceof THREE.Particle ) {
  661. var distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  662. if ( distance > object.scale.x ) {
  663. return [];
  664. }
  665. intersect = {
  666. distance: distance,
  667. point: object.position,
  668. face: null,
  669. object: object
  670. };
  671. intersects.push( intersect );
  672. } else if ( object instanceof THREE.Mesh ) {
  673. // Checking boundingSphere
  674. var distance = distanceFromIntersection( this.origin, this.direction, object.matrixWorld.getPosition() );
  675. var scale = THREE.Frustum.__v1.set( object.matrixWorld.getColumnX().length(), object.matrixWorld.getColumnY().length(), object.matrixWorld.getColumnZ().length() );
  676. if ( distance > object.geometry.boundingSphere.radius * Math.max( scale.x, Math.max( scale.y, scale.z ) ) ) {
  677. return intersects;
  678. }
  679. // Checking faces
  680. var f, fl, face, dot, scalar,
  681. geometry = object.geometry,
  682. vertices = geometry.vertices,
  683. objMatrix;
  684. object.matrixRotationWorld.extractRotation( object.matrixWorld );
  685. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  686. face = geometry.faces[ f ];
  687. originCopy.copy( this.origin );
  688. directionCopy.copy( this.direction );
  689. objMatrix = object.matrixWorld;
  690. // determine if ray intersects the plane of the face
  691. // note: this works regardless of the direction of the face normal
  692. vector = objMatrix.multiplyVector3( vector.copy( face.centroid ) ).subSelf( originCopy );
  693. normal = object.matrixRotationWorld.multiplyVector3( normal.copy( face.normal ) );
  694. dot = directionCopy.dot( normal );
  695. // bail if ray and plane are parallel
  696. if ( Math.abs( dot ) < precision ) continue;
  697. // calc distance to plane
  698. scalar = normal.dot( vector ) / dot;
  699. // if negative distance, then plane is behind ray
  700. if ( scalar < 0 ) continue;
  701. if ( object.doubleSided || ( object.flipSided ? dot > 0 : dot < 0 ) ) {
  702. intersectPoint.add( originCopy, directionCopy.multiplyScalar( scalar ) );
  703. if ( face instanceof THREE.Face3 ) {
  704. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ].position ) );
  705. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ].position ) );
  706. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ].position ) );
  707. if ( pointInFace3( intersectPoint, a, b, c ) ) {
  708. intersect = {
  709. distance: originCopy.distanceTo( intersectPoint ),
  710. point: intersectPoint.clone(),
  711. face: face,
  712. object: object
  713. };
  714. intersects.push( intersect );
  715. }
  716. } else if ( face instanceof THREE.Face4 ) {
  717. a = objMatrix.multiplyVector3( a.copy( vertices[ face.a ].position ) );
  718. b = objMatrix.multiplyVector3( b.copy( vertices[ face.b ].position ) );
  719. c = objMatrix.multiplyVector3( c.copy( vertices[ face.c ].position ) );
  720. d = objMatrix.multiplyVector3( d.copy( vertices[ face.d ].position ) );
  721. if ( pointInFace3( intersectPoint, a, b, d ) || pointInFace3( intersectPoint, b, c, d ) ) {
  722. intersect = {
  723. distance: originCopy.distanceTo( intersectPoint ),
  724. point: intersectPoint.clone(),
  725. face: face,
  726. object: object
  727. };
  728. intersects.push( intersect );
  729. }
  730. }
  731. }
  732. }
  733. }
  734. return intersects;
  735. }
  736. this.intersectObjects = function ( objects ) {
  737. var intersects = [];
  738. for ( var i = 0, l = objects.length; i < l; i ++ ) {
  739. Array.prototype.push.apply( intersects, this.intersectObject( objects[ i ] ) );
  740. }
  741. intersects.sort( function ( a, b ) { return a.distance - b.distance; } );
  742. return intersects;
  743. };
  744. var v0 = new THREE.Vector3(), v1 = new THREE.Vector3(), v2 = new THREE.Vector3();
  745. var dot, intersect, distance;
  746. function distanceFromIntersection( origin, direction, position ) {
  747. v0.sub( position, origin );
  748. dot = v0.dot( direction );
  749. intersect = v1.add( origin, v2.copy( direction ).multiplyScalar( dot ) );
  750. distance = position.distanceTo( intersect );
  751. return distance;
  752. }
  753. // http://www.blackpawn.com/texts/pointinpoly/default.html
  754. var dot00, dot01, dot02, dot11, dot12, invDenom, u, v;
  755. function pointInFace3( p, a, b, c ) {
  756. v0.sub( c, a );
  757. v1.sub( b, a );
  758. v2.sub( p, a );
  759. dot00 = v0.dot( v0 );
  760. dot01 = v0.dot( v1 );
  761. dot02 = v0.dot( v2 );
  762. dot11 = v1.dot( v1 );
  763. dot12 = v1.dot( v2 );
  764. invDenom = 1 / ( dot00 * dot11 - dot01 * dot01 );
  765. u = ( dot11 * dot02 - dot01 * dot12 ) * invDenom;
  766. v = ( dot00 * dot12 - dot01 * dot02 ) * invDenom;
  767. return ( u >= 0 ) && ( v >= 0 ) && ( u + v < 1 );
  768. }
  769. };/**
  770. * @author mr.doob / http://mrdoob.com/
  771. */
  772. THREE.Rectangle = function () {
  773. var _left, _top, _right, _bottom,
  774. _width, _height, _isEmpty = true;
  775. function resize() {
  776. _width = _right - _left;
  777. _height = _bottom - _top;
  778. }
  779. this.getX = function () {
  780. return _left;
  781. };
  782. this.getY = function () {
  783. return _top;
  784. };
  785. this.getWidth = function () {
  786. return _width;
  787. };
  788. this.getHeight = function () {
  789. return _height;
  790. };
  791. this.getLeft = function() {
  792. return _left;
  793. };
  794. this.getTop = function() {
  795. return _top;
  796. };
  797. this.getRight = function() {
  798. return _right;
  799. };
  800. this.getBottom = function() {
  801. return _bottom;
  802. };
  803. this.set = function ( left, top, right, bottom ) {
  804. _isEmpty = false;
  805. _left = left; _top = top;
  806. _right = right; _bottom = bottom;
  807. resize();
  808. };
  809. this.addPoint = function ( x, y ) {
  810. if ( _isEmpty ) {
  811. _isEmpty = false;
  812. _left = x; _top = y;
  813. _right = x; _bottom = y;
  814. resize();
  815. } else {
  816. _left = _left < x ? _left : x; // Math.min( _left, x );
  817. _top = _top < y ? _top : y; // Math.min( _top, y );
  818. _right = _right > x ? _right : x; // Math.max( _right, x );
  819. _bottom = _bottom > y ? _bottom : y; // Math.max( _bottom, y );
  820. resize();
  821. }
  822. };
  823. this.add3Points = function ( x1, y1, x2, y2, x3, y3 ) {
  824. if (_isEmpty) {
  825. _isEmpty = false;
  826. _left = x1 < x2 ? ( x1 < x3 ? x1 : x3 ) : ( x2 < x3 ? x2 : x3 );
  827. _top = y1 < y2 ? ( y1 < y3 ? y1 : y3 ) : ( y2 < y3 ? y2 : y3 );
  828. _right = x1 > x2 ? ( x1 > x3 ? x1 : x3 ) : ( x2 > x3 ? x2 : x3 );
  829. _bottom = y1 > y2 ? ( y1 > y3 ? y1 : y3 ) : ( y2 > y3 ? y2 : y3 );
  830. resize();
  831. } else {
  832. _left = x1 < x2 ? ( x1 < x3 ? ( x1 < _left ? x1 : _left ) : ( x3 < _left ? x3 : _left ) ) : ( x2 < x3 ? ( x2 < _left ? x2 : _left ) : ( x3 < _left ? x3 : _left ) );
  833. _top = y1 < y2 ? ( y1 < y3 ? ( y1 < _top ? y1 : _top ) : ( y3 < _top ? y3 : _top ) ) : ( y2 < y3 ? ( y2 < _top ? y2 : _top ) : ( y3 < _top ? y3 : _top ) );
  834. _right = x1 > x2 ? ( x1 > x3 ? ( x1 > _right ? x1 : _right ) : ( x3 > _right ? x3 : _right ) ) : ( x2 > x3 ? ( x2 > _right ? x2 : _right ) : ( x3 > _right ? x3 : _right ) );
  835. _bottom = y1 > y2 ? ( y1 > y3 ? ( y1 > _bottom ? y1 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) ) : ( y2 > y3 ? ( y2 > _bottom ? y2 : _bottom ) : ( y3 > _bottom ? y3 : _bottom ) );
  836. resize();
  837. };
  838. };
  839. this.addRectangle = function ( r ) {
  840. if ( _isEmpty ) {
  841. _isEmpty = false;
  842. _left = r.getLeft(); _top = r.getTop();
  843. _right = r.getRight(); _bottom = r.getBottom();
  844. resize();
  845. } else {
  846. _left = _left < r.getLeft() ? _left : r.getLeft(); // Math.min(_left, r.getLeft() );
  847. _top = _top < r.getTop() ? _top : r.getTop(); // Math.min(_top, r.getTop() );
  848. _right = _right > r.getRight() ? _right : r.getRight(); // Math.max(_right, r.getRight() );
  849. _bottom = _bottom > r.getBottom() ? _bottom : r.getBottom(); // Math.max(_bottom, r.getBottom() );
  850. resize();
  851. }
  852. };
  853. this.inflate = function ( v ) {
  854. _left -= v; _top -= v;
  855. _right += v; _bottom += v;
  856. resize();
  857. };
  858. this.minSelf = function ( r ) {
  859. _left = _left > r.getLeft() ? _left : r.getLeft(); // Math.max( _left, r.getLeft() );
  860. _top = _top > r.getTop() ? _top : r.getTop(); // Math.max( _top, r.getTop() );
  861. _right = _right < r.getRight() ? _right : r.getRight(); // Math.min( _right, r.getRight() );
  862. _bottom = _bottom < r.getBottom() ? _bottom : r.getBottom(); // Math.min( _bottom, r.getBottom() );
  863. resize();
  864. };
  865. this.intersects = function ( r ) {
  866. // http://gamemath.com/2011/09/detecting-whether-two-boxes-overlap/
  867. if ( _right < r.getLeft() ) return false;
  868. if ( _left > r.getRight() ) return false;
  869. if ( _bottom < r.getTop() ) return false;
  870. if ( _top > r.getBottom() ) return false;
  871. return true;
  872. };
  873. this.empty = function () {
  874. _isEmpty = true;
  875. _left = 0; _top = 0;
  876. _right = 0; _bottom = 0;
  877. resize();
  878. };
  879. this.isEmpty = function () {
  880. return _isEmpty;
  881. };
  882. };
  883. /**
  884. * @author alteredq / http://alteredqualia.com/
  885. */
  886. THREE.Math = {
  887. // Clamp value to range <a, b>
  888. clamp: function ( x, a, b ) {
  889. return ( x < a ) ? a : ( ( x > b ) ? b : x );
  890. },
  891. // Clamp value to range <a, inf)
  892. clampBottom: function ( x, a ) {
  893. return x < a ? a : x;
  894. },
  895. // Linear mapping from range <a1, a2> to range <b1, b2>
  896. mapLinear: function ( x, a1, a2, b1, b2 ) {
  897. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  898. },
  899. // Random float from <0, 1> with 16 bits of randomness
  900. // (standard Math.random() creates repetitive patterns when applied over larger space)
  901. random16: function () {
  902. return ( 65280 * Math.random() + 255 * Math.random() ) / 65535;
  903. },
  904. // Random integer from <low, high> interval
  905. randInt: function ( low, high ) {
  906. return low + Math.floor( Math.random() * ( high - low + 1 ) );
  907. },
  908. // Random float from <low, high> interval
  909. randFloat: function ( low, high ) {
  910. return low + Math.random() * ( high - low );
  911. },
  912. // Random float from <-range/2, range/2> interval
  913. randFloatSpread: function ( range ) {
  914. return range * ( 0.5 - Math.random() );
  915. },
  916. sign: function ( x ) {
  917. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  918. }
  919. };
  920. /**
  921. * @author alteredq / http://alteredqualia.com/
  922. */
  923. THREE.Matrix3 = function () {
  924. this.m = [];
  925. };
  926. THREE.Matrix3.prototype = {
  927. constructor: THREE.Matrix3,
  928. getInverse: function ( matrix ) {
  929. // input: THREE.Matrix4
  930. // ( based on http://code.google.com/p/webgl-mjs/ )
  931. var a11 = matrix.elements[10] * matrix.elements[5] - matrix.elements[6] * matrix.elements[9];
  932. var a21 = - matrix.elements[10] * matrix.elements[1] + matrix.elements[2] * matrix.elements[9];
  933. var a31 = matrix.elements[6] * matrix.elements[1] - matrix.elements[2] * matrix.elements[5];
  934. var a12 = - matrix.elements[10] * matrix.elements[4] + matrix.elements[6] * matrix.elements[8];
  935. var a22 = matrix.elements[10] * matrix.elements[0] - matrix.elements[2] * matrix.elements[8];
  936. var a32 = - matrix.elements[6] * matrix.elements[0] + matrix.elements[2] * matrix.elements[4];
  937. var a13 = matrix.elements[9] * matrix.elements[4] - matrix.elements[5] * matrix.elements[8];
  938. var a23 = - matrix.elements[9] * matrix.elements[0] + matrix.elements[1] * matrix.elements[8];
  939. var a33 = matrix.elements[5] * matrix.elements[0] - matrix.elements[1] * matrix.elements[4];
  940. var det = matrix.elements[0] * a11 + matrix.elements[1] * a12 + matrix.elements[2] * a13;
  941. // no inverse
  942. if ( det === 0 ) {
  943. console.warn( "Matrix3.getInverse(): determinant == 0" );
  944. }
  945. var idet = 1.0 / det;
  946. var m = this.m;
  947. m[ 0 ] = idet * a11; m[ 1 ] = idet * a21; m[ 2 ] = idet * a31;
  948. m[ 3 ] = idet * a12; m[ 4 ] = idet * a22; m[ 5 ] = idet * a32;
  949. m[ 6 ] = idet * a13; m[ 7 ] = idet * a23; m[ 8 ] = idet * a33;
  950. return this;
  951. },
  952. /*
  953. transpose: function () {
  954. var tmp, m = this.m;
  955. tmp = m[1]; m[1] = m[3]; m[3] = tmp;
  956. tmp = m[2]; m[2] = m[6]; m[6] = tmp;
  957. tmp = m[5]; m[5] = m[7]; m[7] = tmp;
  958. return this;
  959. },
  960. */
  961. transposeIntoArray: function ( r ) {
  962. var m = this.m;
  963. r[ 0 ] = m[ 0 ];
  964. r[ 1 ] = m[ 3 ];
  965. r[ 2 ] = m[ 6 ];
  966. r[ 3 ] = m[ 1 ];
  967. r[ 4 ] = m[ 4 ];
  968. r[ 5 ] = m[ 7 ];
  969. r[ 6 ] = m[ 2 ];
  970. r[ 7 ] = m[ 5 ];
  971. r[ 8 ] = m[ 8 ];
  972. return this;
  973. }
  974. };
  975. /**
  976. * @author mr.doob / http://mrdoob.com/
  977. * @author supereggbert / http://www.paulbrunt.co.uk/
  978. * @author philogb / http://blog.thejit.org/
  979. * @author jordi_ros / http://plattsoft.com
  980. * @author D1plo1d / http://github.com/D1plo1d
  981. * @author alteredq / http://alteredqualia.com/
  982. * @author mikael emtinger / http://gomo.se/
  983. * @author timknip / http://www.floorplanner.com/
  984. */
  985. THREE.Matrix4 = function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  986. this.elements = new Float32Array(16);
  987. this.set(
  988. ( n11 !== undefined ) ? n11 : 1, n12 || 0, n13 || 0, n14 || 0,
  989. n21 || 0, ( n22 !== undefined ) ? n22 : 1, n23 || 0, n24 || 0,
  990. n31 || 0, n32 || 0, ( n33 !== undefined ) ? n33 : 1, n34 || 0,
  991. n41 || 0, n42 || 0, n43 || 0, ( n44 !== undefined ) ? n44 : 1
  992. );
  993. };
  994. THREE.Matrix4.prototype = {
  995. constructor: THREE.Matrix4,
  996. set: function ( n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ) {
  997. var te = this.elements;
  998. te[0] = n11; te[4] = n12; te[8] = n13; te[12] = n14;
  999. te[1] = n21; te[5] = n22; te[9] = n23; te[13] = n24;
  1000. te[2] = n31; te[6] = n32; te[10] = n33; te[14] = n34;
  1001. te[3] = n41; te[7] = n42; te[11] = n43; te[15] = n44;
  1002. return this;
  1003. },
  1004. identity: function () {
  1005. this.set(
  1006. 1, 0, 0, 0,
  1007. 0, 1, 0, 0,
  1008. 0, 0, 1, 0,
  1009. 0, 0, 0, 1
  1010. );
  1011. return this;
  1012. },
  1013. copy: function ( m ) {
  1014. var me = m.elements;
  1015. this.set(
  1016. me[0], me[4], me[8], me[12],
  1017. me[1], me[5], me[9], me[13],
  1018. me[2], me[6], me[10], me[14],
  1019. me[3], me[7], me[11], me[15]
  1020. );
  1021. return this;
  1022. },
  1023. lookAt: function ( eye, target, up ) {
  1024. var te = this.elements;
  1025. var x = THREE.Matrix4.__v1;
  1026. var y = THREE.Matrix4.__v2;
  1027. var z = THREE.Matrix4.__v3;
  1028. z.sub( eye, target ).normalize();
  1029. if ( z.length() === 0 ) {
  1030. z.z = 1;
  1031. }
  1032. x.cross( up, z ).normalize();
  1033. if ( x.length() === 0 ) {
  1034. z.x += 0.0001;
  1035. x.cross( up, z ).normalize();
  1036. }
  1037. y.cross( z, x );
  1038. te[0] = x.x; te[4] = y.x; te[8] = z.x;
  1039. te[1] = x.y; te[5] = y.y; te[9] = z.y;
  1040. te[2] = x.z; te[6] = y.z; te[10] = z.z;
  1041. return this;
  1042. },
  1043. multiply: function ( a, b ) {
  1044. var ae = a.elements,
  1045. be = b.elements,
  1046. te = this.elements;
  1047. var a11 = ae[0], a12 = ae[4], a13 = ae[8], a14 = ae[12];
  1048. var a21 = ae[1], a22 = ae[5], a23 = ae[9], a24 = ae[13];
  1049. var a31 = ae[2], a32 = ae[6], a33 = ae[10], a34 = ae[14];
  1050. var a41 = ae[3], a42 = ae[7], a43 = ae[11], a44 = ae[15];
  1051. var b11 = be[0], b12 = be[4], b13 = be[8], b14 = be[12];
  1052. var b21 = be[1], b22 = be[5], b23 = be[9], b24 = be[13];
  1053. var b31 = be[2], b32 = be[6], b33 = be[10], b34 = be[14];
  1054. var b41 = be[3], b42 = be[7], b43 = be[11], b44 = be[15];
  1055. te[0] = a11 * b11 + a12 * b21 + a13 * b31 + a14 * b41;
  1056. te[4] = a11 * b12 + a12 * b22 + a13 * b32 + a14 * b42;
  1057. te[8] = a11 * b13 + a12 * b23 + a13 * b33 + a14 * b43;
  1058. te[12] = a11 * b14 + a12 * b24 + a13 * b34 + a14 * b44;
  1059. te[1] = a21 * b11 + a22 * b21 + a23 * b31 + a24 * b41;
  1060. te[5] = a21 * b12 + a22 * b22 + a23 * b32 + a24 * b42;
  1061. te[9] = a21 * b13 + a22 * b23 + a23 * b33 + a24 * b43;
  1062. te[13] = a21 * b14 + a22 * b24 + a23 * b34 + a24 * b44;
  1063. te[2] = a31 * b11 + a32 * b21 + a33 * b31 + a34 * b41;
  1064. te[6] = a31 * b12 + a32 * b22 + a33 * b32 + a34 * b42;
  1065. te[10] = a31 * b13 + a32 * b23 + a33 * b33 + a34 * b43;
  1066. te[14] = a31 * b14 + a32 * b24 + a33 * b34 + a34 * b44;
  1067. te[3] = a41 * b11 + a42 * b21 + a43 * b31 + a44 * b41;
  1068. te[7] = a41 * b12 + a42 * b22 + a43 * b32 + a44 * b42;
  1069. te[11] = a41 * b13 + a42 * b23 + a43 * b33 + a44 * b43;
  1070. te[15] = a41 * b14 + a42 * b24 + a43 * b34 + a44 * b44;
  1071. return this;
  1072. },
  1073. multiplySelf: function ( m ) {
  1074. return this.multiply( this, m );
  1075. },
  1076. multiplyToArray: function ( a, b, r ) {
  1077. var te = this.elements;
  1078. this.multiply( a, b );
  1079. r[ 0 ] = te[0]; r[ 1 ] = te[1]; r[ 2 ] = te[2]; r[ 3 ] = te[3];
  1080. r[ 4 ] = te[4]; r[ 5 ] = te[5]; r[ 6 ] = te[6]; r[ 7 ] = te[7];
  1081. r[ 8 ] = te[8]; r[ 9 ] = te[9]; r[ 10 ] = te[10]; r[ 11 ] = te[11];
  1082. r[ 12 ] = te[12]; r[ 13 ] = te[13]; r[ 14 ] = te[14]; r[ 15 ] = te[15];
  1083. return this;
  1084. },
  1085. multiplyScalar: function ( s ) {
  1086. var te = this.elements;
  1087. te[0] *= s; te[4] *= s; te[8] *= s; te[12] *= s;
  1088. te[1] *= s; te[5] *= s; te[9] *= s; te[13] *= s;
  1089. te[2] *= s; te[6] *= s; te[10] *= s; te[14] *= s;
  1090. te[3] *= s; te[7] *= s; te[11] *= s; te[15] *= s;
  1091. return this;
  1092. },
  1093. multiplyVector3: function ( v ) {
  1094. var te = this.elements;
  1095. var vx = v.x, vy = v.y, vz = v.z;
  1096. var d = 1 / ( te[3] * vx + te[7] * vy + te[11] * vz + te[15] );
  1097. v.x = ( te[0] * vx + te[4] * vy + te[8] * vz + te[12] ) * d;
  1098. v.y = ( te[1] * vx + te[5] * vy + te[9] * vz + te[13] ) * d;
  1099. v.z = ( te[2] * vx + te[6] * vy + te[10] * vz + te[14] ) * d;
  1100. return v;
  1101. },
  1102. multiplyVector4: function ( v ) {
  1103. var te = this.elements;
  1104. var vx = v.x, vy = v.y, vz = v.z, vw = v.w;
  1105. v.x = te[0] * vx + te[4] * vy + te[8] * vz + te[12] * vw;
  1106. v.y = te[1] * vx + te[5] * vy + te[9] * vz + te[13] * vw;
  1107. v.z = te[2] * vx + te[6] * vy + te[10] * vz + te[14] * vw;
  1108. v.w = te[3] * vx + te[7] * vy + te[11] * vz + te[15] * vw;
  1109. return v;
  1110. },
  1111. rotateAxis: function ( v ) {
  1112. var te = this.elements;
  1113. var vx = v.x, vy = v.y, vz = v.z;
  1114. v.x = vx * te[0] + vy * te[4] + vz * te[8];
  1115. v.y = vx * te[1] + vy * te[5] + vz * te[9];
  1116. v.z = vx * te[2] + vy * te[6] + vz * te[10];
  1117. v.normalize();
  1118. return v;
  1119. },
  1120. crossVector: function ( a ) {
  1121. var te = this.elements;
  1122. var v = new THREE.Vector4();
  1123. v.x = te[0] * a.x + te[4] * a.y + te[8] * a.z + te[12] * a.w;
  1124. v.y = te[1] * a.x + te[5] * a.y + te[9] * a.z + te[13] * a.w;
  1125. v.z = te[2] * a.x + te[6] * a.y + te[10] * a.z + te[14] * a.w;
  1126. v.w = ( a.w ) ? te[3] * a.x + te[7] * a.y + te[11] * a.z + te[15] * a.w : 1;
  1127. return v;
  1128. },
  1129. determinant: function () {
  1130. var te = this.elements;
  1131. var n11 = te[0], n12 = te[4], n13 = te[8], n14 = te[12];
  1132. var n21 = te[1], n22 = te[5], n23 = te[9], n24 = te[13];
  1133. var n31 = te[2], n32 = te[6], n33 = te[10], n34 = te[14];
  1134. var n41 = te[3], n42 = te[7], n43 = te[11], n44 = te[15];
  1135. //TODO: make this more efficient
  1136. //( based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm )
  1137. return (
  1138. n14 * n23 * n32 * n41-
  1139. n13 * n24 * n32 * n41-
  1140. n14 * n22 * n33 * n41+
  1141. n12 * n24 * n33 * n41+
  1142. n13 * n22 * n34 * n41-
  1143. n12 * n23 * n34 * n41-
  1144. n14 * n23 * n31 * n42+
  1145. n13 * n24 * n31 * n42+
  1146. n14 * n21 * n33 * n42-
  1147. n11 * n24 * n33 * n42-
  1148. n13 * n21 * n34 * n42+
  1149. n11 * n23 * n34 * n42+
  1150. n14 * n22 * n31 * n43-
  1151. n12 * n24 * n31 * n43-
  1152. n14 * n21 * n32 * n43+
  1153. n11 * n24 * n32 * n43+
  1154. n12 * n21 * n34 * n43-
  1155. n11 * n22 * n34 * n43-
  1156. n13 * n22 * n31 * n44+
  1157. n12 * n23 * n31 * n44+
  1158. n13 * n21 * n32 * n44-
  1159. n11 * n23 * n32 * n44-
  1160. n12 * n21 * n33 * n44+
  1161. n11 * n22 * n33 * n44
  1162. );
  1163. },
  1164. transpose: function () {
  1165. var te = this.elements;
  1166. var tmp;
  1167. tmp = te[1]; te[1] = te[4]; te[4] = tmp;
  1168. tmp = te[2]; te[2] = te[8]; te[8] = tmp;
  1169. tmp = te[6]; te[6] = te[9]; te[9] = tmp;
  1170. tmp = te[3]; te[3] = te[12]; te[12] = tmp;
  1171. tmp = te[7]; te[7] = te[13]; te[13] = tmp;
  1172. tmp = te[11]; te[11] = te[14]; te[14] = tmp;
  1173. return this;
  1174. },
  1175. flattenToArray: function ( flat ) {
  1176. var te = this.elements;
  1177. flat[ 0 ] = te[0]; flat[ 1 ] = te[1]; flat[ 2 ] = te[2]; flat[ 3 ] = te[3];
  1178. flat[ 4 ] = te[4]; flat[ 5 ] = te[5]; flat[ 6 ] = te[6]; flat[ 7 ] = te[7];
  1179. flat[ 8 ] = te[8]; flat[ 9 ] = te[9]; flat[ 10 ] = te[10]; flat[ 11 ] = te[11];
  1180. flat[ 12 ] = te[12]; flat[ 13 ] = te[13]; flat[ 14 ] = te[14]; flat[ 15 ] = te[15];
  1181. return flat;
  1182. },
  1183. flattenToArrayOffset: function( flat, offset ) {
  1184. var te = this.elements;
  1185. flat[ offset ] = te[0];
  1186. flat[ offset + 1 ] = te[1];
  1187. flat[ offset + 2 ] = te[2];
  1188. flat[ offset + 3 ] = te[3];
  1189. flat[ offset + 4 ] = te[4];
  1190. flat[ offset + 5 ] = te[5];
  1191. flat[ offset + 6 ] = te[6];
  1192. flat[ offset + 7 ] = te[7];
  1193. flat[ offset + 8 ] = te[8];
  1194. flat[ offset + 9 ] = te[9];
  1195. flat[ offset + 10 ] = te[10];
  1196. flat[ offset + 11 ] = te[11];
  1197. flat[ offset + 12 ] = te[12];
  1198. flat[ offset + 13 ] = te[13];
  1199. flat[ offset + 14 ] = te[14];
  1200. flat[ offset + 15 ] = te[15];
  1201. return flat;
  1202. },
  1203. getPosition: function () {
  1204. var te = this.elements;
  1205. return THREE.Matrix4.__v1.set( te[12], te[13], te[14] );
  1206. },
  1207. setPosition: function ( v ) {
  1208. var te = this.elements;
  1209. te[12] = v.x;
  1210. te[13] = v.y;
  1211. te[14] = v.z;
  1212. return this;
  1213. },
  1214. getColumnX: function () {
  1215. var te = this.elements;
  1216. return THREE.Matrix4.__v1.set( te[0], te[1], te[2] );
  1217. },
  1218. getColumnY: function () {
  1219. var te = this.elements;
  1220. return THREE.Matrix4.__v1.set( te[4], te[5], te[6] );
  1221. },
  1222. getColumnZ: function() {
  1223. var te = this.elements;
  1224. return THREE.Matrix4.__v1.set( te[8], te[9], te[10] );
  1225. },
  1226. getInverse: function ( m ) {
  1227. // based on http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.htm
  1228. var te = this.elements;
  1229. var me = m.elements;
  1230. var n11 = me[0], n12 = me[4], n13 = me[8], n14 = me[12];
  1231. var n21 = me[1], n22 = me[5], n23 = me[9], n24 = me[13];
  1232. var n31 = me[2], n32 = me[6], n33 = me[10], n34 = me[14];
  1233. var n41 = me[3], n42 = me[7], n43 = me[11], n44 = me[15];
  1234. te[0] = n23*n34*n42 - n24*n33*n42 + n24*n32*n43 - n22*n34*n43 - n23*n32*n44 + n22*n33*n44;
  1235. te[4] = n14*n33*n42 - n13*n34*n42 - n14*n32*n43 + n12*n34*n43 + n13*n32*n44 - n12*n33*n44;
  1236. te[8] = n13*n24*n42 - n14*n23*n42 + n14*n22*n43 - n12*n24*n43 - n13*n22*n44 + n12*n23*n44;
  1237. te[12] = n14*n23*n32 - n13*n24*n32 - n14*n22*n33 + n12*n24*n33 + n13*n22*n34 - n12*n23*n34;
  1238. te[1] = n24*n33*n41 - n23*n34*n41 - n24*n31*n43 + n21*n34*n43 + n23*n31*n44 - n21*n33*n44;
  1239. te[5] = n13*n34*n41 - n14*n33*n41 + n14*n31*n43 - n11*n34*n43 - n13*n31*n44 + n11*n33*n44;
  1240. te[9] = n14*n23*n41 - n13*n24*n41 - n14*n21*n43 + n11*n24*n43 + n13*n21*n44 - n11*n23*n44;
  1241. te[13] = n13*n24*n31 - n14*n23*n31 + n14*n21*n33 - n11*n24*n33 - n13*n21*n34 + n11*n23*n34;
  1242. te[2] = n22*n34*n41 - n24*n32*n41 + n24*n31*n42 - n21*n34*n42 - n22*n31*n44 + n21*n32*n44;
  1243. te[6] = n14*n32*n41 - n12*n34*n41 - n14*n31*n42 + n11*n34*n42 + n12*n31*n44 - n11*n32*n44;
  1244. te[10] = n12*n24*n41 - n14*n22*n41 + n14*n21*n42 - n11*n24*n42 - n12*n21*n44 + n11*n22*n44;
  1245. te[14] = n14*n22*n31 - n12*n24*n31 - n14*n21*n32 + n11*n24*n32 + n12*n21*n34 - n11*n22*n34;
  1246. te[3] = n23*n32*n41 - n22*n33*n41 - n23*n31*n42 + n21*n33*n42 + n22*n31*n43 - n21*n32*n43;
  1247. te[7] = n12*n33*n41 - n13*n32*n41 + n13*n31*n42 - n11*n33*n42 - n12*n31*n43 + n11*n32*n43;
  1248. te[11] = n13*n22*n41 - n12*n23*n41 - n13*n21*n42 + n11*n23*n42 + n12*n21*n43 - n11*n22*n43;
  1249. te[15] = n12*n23*n31 - n13*n22*n31 + n13*n21*n32 - n11*n23*n32 - n12*n21*n33 + n11*n22*n33;
  1250. this.multiplyScalar( 1 / m.determinant() );
  1251. return this;
  1252. },
  1253. setRotationFromEuler: function( v, order ) {
  1254. var te = this.elements;
  1255. var x = v.x, y = v.y, z = v.z;
  1256. var a = Math.cos( x ), b = Math.sin( x );
  1257. var c = Math.cos( y ), d = Math.sin( y );
  1258. var e = Math.cos( z ), f = Math.sin( z );
  1259. switch ( order ) {
  1260. case 'YXZ':
  1261. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1262. te[0] = ce + df * b;
  1263. te[4] = de * b - cf;
  1264. te[8] = a * d;
  1265. te[1] = a * f;
  1266. te[5] = a * e;
  1267. te[9] = - b;
  1268. te[2] = cf * b - de;
  1269. te[6] = df + ce * b;
  1270. te[10] = a * c;
  1271. break;
  1272. case 'ZXY':
  1273. var ce = c * e, cf = c * f, de = d * e, df = d * f;
  1274. te[0] = ce - df * b;
  1275. te[4] = - a * f;
  1276. te[8] = de + cf * b;
  1277. te[1] = cf + de * b;
  1278. te[5] = a * e;
  1279. te[9] = df - ce * b;
  1280. te[2] = - a * d;
  1281. te[6] = b;
  1282. te[10] = a * c;
  1283. break;
  1284. case 'ZYX':
  1285. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1286. te[0] = c * e;
  1287. te[4] = be * d - af;
  1288. te[8] = ae * d + bf;
  1289. te[1] = c * f;
  1290. te[5] = bf * d + ae;
  1291. te[9] = af * d - be;
  1292. te[2] = - d;
  1293. te[6] = b * c;
  1294. te[10] = a * c;
  1295. break;
  1296. case 'YZX':
  1297. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1298. te[0] = c * e;
  1299. te[4] = bd - ac * f;
  1300. te[8] = bc * f + ad;
  1301. te[1] = f;
  1302. te[5] = a * e;
  1303. te[9] = - b * e;
  1304. te[2] = - d * e;
  1305. te[6] = ad * f + bc;
  1306. te[10] = ac - bd * f;
  1307. break;
  1308. case 'XZY':
  1309. var ac = a * c, ad = a * d, bc = b * c, bd = b * d;
  1310. te[0] = c * e;
  1311. te[4] = - f;
  1312. te[8] = d * e;
  1313. te[1] = ac * f + bd;
  1314. te[5] = a * e;
  1315. te[9] = ad * f - bc;
  1316. te[2] = bc * f - ad;
  1317. te[6] = b * e;
  1318. te[10] = bd * f + ac;
  1319. break;
  1320. default: // 'XYZ'
  1321. var ae = a * e, af = a * f, be = b * e, bf = b * f;
  1322. te[0] = c * e;
  1323. te[4] = - c * f;
  1324. te[8] = d;
  1325. te[1] = af + be * d;
  1326. te[5] = ae - bf * d;
  1327. te[9] = - b * c;
  1328. te[2] = bf - ae * d;
  1329. te[6] = be + af * d;
  1330. te[10] = a * c;
  1331. break;
  1332. }
  1333. return this;
  1334. },
  1335. setRotationFromQuaternion: function( q ) {
  1336. var te = this.elements;
  1337. var x = q.x, y = q.y, z = q.z, w = q.w;
  1338. var x2 = x + x, y2 = y + y, z2 = z + z;
  1339. var xx = x * x2, xy = x * y2, xz = x * z2;
  1340. var yy = y * y2, yz = y * z2, zz = z * z2;
  1341. var wx = w * x2, wy = w * y2, wz = w * z2;
  1342. te[0] = 1 - ( yy + zz );
  1343. te[4] = xy - wz;
  1344. te[8] = xz + wy;
  1345. te[1] = xy + wz;
  1346. te[5] = 1 - ( xx + zz );
  1347. te[9] = yz - wx;
  1348. te[2] = xz - wy;
  1349. te[6] = yz + wx;
  1350. te[10] = 1 - ( xx + yy );
  1351. return this;
  1352. },
  1353. compose: function ( translation, rotation, scale ) {
  1354. var te = this.elements;
  1355. var mRotation = THREE.Matrix4.__m1;
  1356. var mScale = THREE.Matrix4.__m2;
  1357. mRotation.identity();
  1358. mRotation.setRotationFromQuaternion( rotation );
  1359. mScale.makeScale( scale.x, scale.y, scale.z );
  1360. this.multiply( mRotation, mScale );
  1361. te[12] = translation.x;
  1362. te[13] = translation.y;
  1363. te[14] = translation.z;
  1364. return this;
  1365. },
  1366. decompose: function ( translation, rotation, scale ) {
  1367. // grab the axis vectors
  1368. var te = this.elements;
  1369. var x = THREE.Matrix4.__v1;
  1370. var y = THREE.Matrix4.__v2;
  1371. var z = THREE.Matrix4.__v3;
  1372. x.set( te[0], te[1], te[2] );
  1373. y.set( te[4], te[5], te[6] );
  1374. z.set( te[8], te[9], te[10] );
  1375. translation = ( translation instanceof THREE.Vector3 ) ? translation : new THREE.Vector3();
  1376. rotation = ( rotation instanceof THREE.Quaternion ) ? rotation : new THREE.Quaternion();
  1377. scale = ( scale instanceof THREE.Vector3 ) ? scale : new THREE.Vector3();
  1378. scale.x = x.length();
  1379. scale.y = y.length();
  1380. scale.z = z.length();
  1381. translation.x = te[12];
  1382. translation.y = te[13];
  1383. translation.z = te[14];
  1384. // scale the rotation part
  1385. var matrix = THREE.Matrix4.__m1;
  1386. matrix.copy( this );
  1387. matrix.elements[0] /= scale.x;
  1388. matrix.elements[1] /= scale.x;
  1389. matrix.elements[2] /= scale.x;
  1390. matrix.elements[4] /= scale.y;
  1391. matrix.elements[5] /= scale.y;
  1392. matrix.elements[6] /= scale.y;
  1393. matrix.elements[8] /= scale.z;
  1394. matrix.elements[9] /= scale.z;
  1395. matrix.elements[10] /= scale.z;
  1396. rotation.setFromRotationMatrix( matrix );
  1397. return [ translation, rotation, scale ];
  1398. },
  1399. extractPosition: function ( m ) {
  1400. var te = this.elements;
  1401. var me = m.elements;
  1402. te[12] = me[12];
  1403. te[13] = me[13];
  1404. te[14] = me[14];
  1405. return this;
  1406. },
  1407. extractRotation: function ( m ) {
  1408. var te = this.elements;
  1409. var me = m.elements;
  1410. var vector = THREE.Matrix4.__v1;
  1411. var scaleX = 1 / vector.set( me[0], me[1], me[2] ).length();
  1412. var scaleY = 1 / vector.set( me[4], me[5], me[6] ).length();
  1413. var scaleZ = 1 / vector.set( me[8], me[9], me[10] ).length();
  1414. te[0] = me[0] * scaleX;
  1415. te[1] = me[1] * scaleX;
  1416. te[2] = me[2] * scaleX;
  1417. te[4] = me[4] * scaleY;
  1418. te[5] = me[5] * scaleY;
  1419. te[6] = me[6] * scaleY;
  1420. te[8] = me[8] * scaleZ;
  1421. te[9] = me[9] * scaleZ;
  1422. te[10] = me[10] * scaleZ;
  1423. return this;
  1424. },
  1425. //
  1426. translate: function ( v ) {
  1427. var te = this.elements;
  1428. var x = v.x, y = v.y, z = v.z;
  1429. te[12] = te[0] * x + te[4] * y + te[8] * z + te[12];
  1430. te[13] = te[1] * x + te[5] * y + te[9] * z + te[13];
  1431. te[14] = te[2] * x + te[6] * y + te[10] * z + te[14];
  1432. te[15] = te[3] * x + te[7] * y + te[11] * z + te[15];
  1433. return this;
  1434. },
  1435. rotateX: function ( angle ) {
  1436. var te = this.elements;
  1437. var m12 = te[4];
  1438. var m22 = te[5];
  1439. var m32 = te[6];
  1440. var m42 = te[7];
  1441. var m13 = te[8];
  1442. var m23 = te[9];
  1443. var m33 = te[10];
  1444. var m43 = te[11];
  1445. var c = Math.cos( angle );
  1446. var s = Math.sin( angle );
  1447. te[4] = c * m12 + s * m13;
  1448. te[5] = c * m22 + s * m23;
  1449. te[6] = c * m32 + s * m33;
  1450. te[7] = c * m42 + s * m43;
  1451. te[8] = c * m13 - s * m12;
  1452. te[9] = c * m23 - s * m22;
  1453. te[10] = c * m33 - s * m32;
  1454. te[11] = c * m43 - s * m42;
  1455. return this;
  1456. },
  1457. rotateY: function ( angle ) {
  1458. var te = this.elements;
  1459. var m11 = te[0];
  1460. var m21 = te[1];
  1461. var m31 = te[2];
  1462. var m41 = te[3];
  1463. var m13 = te[8];
  1464. var m23 = te[9];
  1465. var m33 = te[10];
  1466. var m43 = te[11];
  1467. var c = Math.cos( angle );
  1468. var s = Math.sin( angle );
  1469. te[0] = c * m11 - s * m13;
  1470. te[1] = c * m21 - s * m23;
  1471. te[2] = c * m31 - s * m33;
  1472. te[3] = c * m41 - s * m43;
  1473. te[8] = c * m13 + s * m11;
  1474. te[9] = c * m23 + s * m21;
  1475. te[10] = c * m33 + s * m31;
  1476. te[11] = c * m43 + s * m41;
  1477. return this;
  1478. },
  1479. rotateZ: function ( angle ) {
  1480. var te = this.elements;
  1481. var m11 = te[0];
  1482. var m21 = te[1];
  1483. var m31 = te[2];
  1484. var m41 = te[3];
  1485. var m12 = te[4];
  1486. var m22 = te[5];
  1487. var m32 = te[6];
  1488. var m42 = te[7];
  1489. var c = Math.cos( angle );
  1490. var s = Math.sin( angle );
  1491. te[0] = c * m11 + s * m12;
  1492. te[1] = c * m21 + s * m22;
  1493. te[2] = c * m31 + s * m32;
  1494. te[3] = c * m41 + s * m42;
  1495. te[4] = c * m12 - s * m11;
  1496. te[5] = c * m22 - s * m21;
  1497. te[6] = c * m32 - s * m31;
  1498. te[7] = c * m42 - s * m41;
  1499. return this;
  1500. },
  1501. rotateByAxis: function ( axis, angle ) {
  1502. var te = this.elements;
  1503. // optimize by checking axis
  1504. if ( axis.x === 1 && axis.y === 0 && axis.z === 0 ) {
  1505. return this.rotateX( angle );
  1506. } else if ( axis.x === 0 && axis.y === 1 && axis.z === 0 ) {
  1507. return this.rotateY( angle );
  1508. } else if ( axis.x === 0 && axis.y === 0 && axis.z === 1 ) {
  1509. return this.rotateZ( angle );
  1510. }
  1511. var x = axis.x, y = axis.y, z = axis.z;
  1512. var n = Math.sqrt(x * x + y * y + z * z);
  1513. x /= n;
  1514. y /= n;
  1515. z /= n;
  1516. var xx = x * x, yy = y * y, zz = z * z;
  1517. var c = Math.cos( angle );
  1518. var s = Math.sin( angle );
  1519. var oneMinusCosine = 1 - c;
  1520. var xy = x * y * oneMinusCosine;
  1521. var xz = x * z * oneMinusCosine;
  1522. var yz = y * z * oneMinusCosine;
  1523. var xs = x * s;
  1524. var ys = y * s;
  1525. var zs = z * s;
  1526. var r11 = xx + (1 - xx) * c;
  1527. var r21 = xy + zs;
  1528. var r31 = xz - ys;
  1529. var r12 = xy - zs;
  1530. var r22 = yy + (1 - yy) * c;
  1531. var r32 = yz + xs;
  1532. var r13 = xz + ys;
  1533. var r23 = yz - xs;
  1534. var r33 = zz + (1 - zz) * c;
  1535. var m11 = te[0], m21 = te[1], m31 = te[2], m41 = te[3];
  1536. var m12 = te[4], m22 = te[5], m32 = te[6], m42 = te[7];
  1537. var m13 = te[8], m23 = te[9], m33 = te[10], m43 = te[11];
  1538. var m14 = te[12], m24 = te[13], m34 = te[14], m44 = te[15];
  1539. te[0] = r11 * m11 + r21 * m12 + r31 * m13;
  1540. te[1] = r11 * m21 + r21 * m22 + r31 * m23;
  1541. te[2] = r11 * m31 + r21 * m32 + r31 * m33;
  1542. te[3] = r11 * m41 + r21 * m42 + r31 * m43;
  1543. te[4] = r12 * m11 + r22 * m12 + r32 * m13;
  1544. te[5] = r12 * m21 + r22 * m22 + r32 * m23;
  1545. te[6] = r12 * m31 + r22 * m32 + r32 * m33;
  1546. te[7] = r12 * m41 + r22 * m42 + r32 * m43;
  1547. te[8] = r13 * m11 + r23 * m12 + r33 * m13;
  1548. te[9] = r13 * m21 + r23 * m22 + r33 * m23;
  1549. te[10] = r13 * m31 + r23 * m32 + r33 * m33;
  1550. te[11] = r13 * m41 + r23 * m42 + r33 * m43;
  1551. return this;
  1552. },
  1553. scale: function ( v ) {
  1554. var te = this.elements;
  1555. var x = v.x, y = v.y, z = v.z;
  1556. te[0] *= x; te[4] *= y; te[8] *= z;
  1557. te[1] *= x; te[5] *= y; te[9] *= z;
  1558. te[2] *= x; te[6] *= y; te[10] *= z;
  1559. te[3] *= x; te[7] *= y; te[11] *= z;
  1560. return this;
  1561. },
  1562. //
  1563. makeTranslation: function ( x, y, z ) {
  1564. this.set(
  1565. 1, 0, 0, x,
  1566. 0, 1, 0, y,
  1567. 0, 0, 1, z,
  1568. 0, 0, 0, 1
  1569. );
  1570. return this;
  1571. },
  1572. makeRotationX: function ( theta ) {
  1573. var c = Math.cos( theta ), s = Math.sin( theta );
  1574. this.set(
  1575. 1, 0, 0, 0,
  1576. 0, c, -s, 0,
  1577. 0, s, c, 0,
  1578. 0, 0, 0, 1
  1579. );
  1580. return this;
  1581. },
  1582. makeRotationY: function ( theta ) {
  1583. var c = Math.cos( theta ), s = Math.sin( theta );
  1584. this.set(
  1585. c, 0, s, 0,
  1586. 0, 1, 0, 0,
  1587. -s, 0, c, 0,
  1588. 0, 0, 0, 1
  1589. );
  1590. return this;
  1591. },
  1592. makeRotationZ: function ( theta ) {
  1593. var c = Math.cos( theta ), s = Math.sin( theta );
  1594. this.set(
  1595. c, -s, 0, 0,
  1596. s, c, 0, 0,
  1597. 0, 0, 1, 0,
  1598. 0, 0, 0, 1
  1599. );
  1600. return this;
  1601. },
  1602. makeRotationAxis: function ( axis, angle ) {
  1603. // Based on http://www.gamedev.net/reference/articles/article1199.asp
  1604. var c = Math.cos( angle );
  1605. var s = Math.sin( angle );
  1606. var t = 1 - c;
  1607. var x = axis.x, y = axis.y, z = axis.z;
  1608. var tx = t * x, ty = t * y;
  1609. this.set(
  1610. tx * x + c, tx * y - s * z, tx * z + s * y, 0,
  1611. tx * y + s * z, ty * y + c, ty * z - s * x, 0,
  1612. tx * z - s * y, ty * z + s * x, t * z * z + c, 0,
  1613. 0, 0, 0, 1
  1614. );
  1615. return this;
  1616. },
  1617. makeScale: function ( x, y, z ) {
  1618. this.set(
  1619. x, 0, 0, 0,
  1620. 0, y, 0, 0,
  1621. 0, 0, z, 0,
  1622. 0, 0, 0, 1
  1623. );
  1624. return this;
  1625. },
  1626. makeFrustum: function ( left, right, bottom, top, near, far ) {
  1627. var te = this.elements;
  1628. var x = 2 * near / ( right - left );
  1629. var y = 2 * near / ( top - bottom );
  1630. var a = ( right + left ) / ( right - left );
  1631. var b = ( top + bottom ) / ( top - bottom );
  1632. var c = - ( far + near ) / ( far - near );
  1633. var d = - 2 * far * near / ( far - near );
  1634. te[0] = x; te[4] = 0; te[8] = a; te[12] = 0;
  1635. te[1] = 0; te[5] = y; te[9] = b; te[13] = 0;
  1636. te[2] = 0; te[6] = 0; te[10] = c; te[14] = d;
  1637. te[3] = 0; te[7] = 0; te[11] = - 1; te[15] = 0;
  1638. return this;
  1639. },
  1640. makePerspective: function ( fov, aspect, near, far ) {
  1641. var ymax = near * Math.tan( fov * Math.PI / 360 );
  1642. var ymin = - ymax;
  1643. var xmin = ymin * aspect;
  1644. var xmax = ymax * aspect;
  1645. return this.makeFrustum( xmin, xmax, ymin, ymax, near, far );
  1646. },
  1647. makeOrthographic: function ( left, right, top, bottom, near, far ) {
  1648. var te = this.elements;
  1649. var w = right - left;
  1650. var h = top - bottom;
  1651. var p = far - near;
  1652. var x = ( right + left ) / w;
  1653. var y = ( top + bottom ) / h;
  1654. var z = ( far + near ) / p;
  1655. te[0] = 2 / w; te[4] = 0; te[8] = 0; te[12] = -x;
  1656. te[1] = 0; te[5] = 2 / h; te[9] = 0; te[13] = -y;
  1657. te[2] = 0; te[6] = 0; te[10] = -2 / p; te[14] = -z;
  1658. te[3] = 0; te[7] = 0; te[11] = 0; te[15] = 1;
  1659. return this;
  1660. },
  1661. clone: function () {
  1662. var te = this.elements;
  1663. return new THREE.Matrix4(
  1664. te[0], te[4], te[8], te[12],
  1665. te[1], te[5], te[9], te[13],
  1666. te[2], te[6], te[10], te[14],
  1667. te[3], te[7], te[11], te[15]
  1668. );
  1669. }
  1670. };
  1671. THREE.Matrix4.__v1 = new THREE.Vector3();
  1672. THREE.Matrix4.__v2 = new THREE.Vector3();
  1673. THREE.Matrix4.__v3 = new THREE.Vector3();
  1674. THREE.Matrix4.__m1 = new THREE.Matrix4();
  1675. THREE.Matrix4.__m2 = new THREE.Matrix4();
  1676. /**
  1677. * @author mr.doob / http://mrdoob.com/
  1678. * @author mikael emtinger / http://gomo.se/
  1679. * @author alteredq / http://alteredqualia.com/
  1680. */
  1681. THREE.Object3D = function () {
  1682. this.id = THREE.Object3DCount ++;
  1683. this.name = '';
  1684. this.parent = undefined;
  1685. this.children = [];
  1686. this.up = new THREE.Vector3( 0, 1, 0 );
  1687. this.position = new THREE.Vector3();
  1688. this.rotation = new THREE.Vector3();
  1689. this.eulerOrder = 'XYZ';
  1690. this.scale = new THREE.Vector3( 1, 1, 1 );
  1691. this.doubleSided = false;
  1692. this.flipSided = false;
  1693. this.renderDepth = null;
  1694. this.rotationAutoUpdate = true;
  1695. this.matrix = new THREE.Matrix4();
  1696. this.matrixWorld = new THREE.Matrix4();
  1697. this.matrixRotationWorld = new THREE.Matrix4();
  1698. this.matrixAutoUpdate = true;
  1699. this.matrixWorldNeedsUpdate = true;
  1700. this.quaternion = new THREE.Quaternion();
  1701. this.useQuaternion = false;
  1702. this.boundRadius = 0.0;
  1703. this.boundRadiusScale = 1.0;
  1704. this.visible = true;
  1705. this.castShadow = false;
  1706. this.receiveShadow = false;
  1707. this.frustumCulled = true;
  1708. this._vector = new THREE.Vector3();
  1709. };
  1710. THREE.Object3D.prototype = {
  1711. constructor: THREE.Object3D,
  1712. applyMatrix: function ( matrix ) {
  1713. this.matrix.multiply( matrix, this.matrix );
  1714. this.scale.getScaleFromMatrix( this.matrix );
  1715. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  1716. this.position.getPositionFromMatrix( this.matrix );
  1717. },
  1718. translate: function ( distance, axis ) {
  1719. this.matrix.rotateAxis( axis );
  1720. this.position.addSelf( axis.multiplyScalar( distance ) );
  1721. },
  1722. translateX: function ( distance ) {
  1723. this.translate( distance, this._vector.set( 1, 0, 0 ) );
  1724. },
  1725. translateY: function ( distance ) {
  1726. this.translate( distance, this._vector.set( 0, 1, 0 ) );
  1727. },
  1728. translateZ: function ( distance ) {
  1729. this.translate( distance, this._vector.set( 0, 0, 1 ) );
  1730. },
  1731. lookAt: function ( vector ) {
  1732. // TODO: Add hierarchy support.
  1733. this.matrix.lookAt( vector, this.position, this.up );
  1734. if ( this.rotationAutoUpdate ) {
  1735. this.rotation.getRotationFromMatrix( this.matrix );
  1736. }
  1737. },
  1738. add: function ( object ) {
  1739. if ( object === this ) {
  1740. console.warn( 'THREE.Object3D.add: An object can\'t be added as a child of itself.' );
  1741. return;
  1742. }
  1743. if ( this.children.indexOf( object ) === - 1 ) {
  1744. if ( object.parent !== undefined ) {
  1745. object.parent.remove( object );
  1746. }
  1747. object.parent = this;
  1748. this.children.push( object );
  1749. // add to scene
  1750. var scene = this;
  1751. while ( scene.parent !== undefined ) {
  1752. scene = scene.parent;
  1753. }
  1754. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  1755. scene.__addObject( object );
  1756. }
  1757. }
  1758. },
  1759. remove: function ( object ) {
  1760. var index = this.children.indexOf( object );
  1761. if ( index !== - 1 ) {
  1762. object.parent = undefined;
  1763. this.children.splice( index, 1 );
  1764. // remove from scene
  1765. var scene = this;
  1766. while ( scene.parent !== undefined ) {
  1767. scene = scene.parent;
  1768. }
  1769. if ( scene !== undefined && scene instanceof THREE.Scene ) {
  1770. scene.__removeObject( object );
  1771. }
  1772. }
  1773. },
  1774. getChildByName: function ( name, recursive ) {
  1775. var c, cl, child;
  1776. for ( c = 0, cl = this.children.length; c < cl; c ++ ) {
  1777. child = this.children[ c ];
  1778. if ( child.name === name ) {
  1779. return child;
  1780. }
  1781. if ( recursive ) {
  1782. child = child.getChildByName( name, recursive );
  1783. if ( child !== undefined ) {
  1784. return child;
  1785. }
  1786. }
  1787. }
  1788. return undefined;
  1789. },
  1790. updateMatrix: function () {
  1791. this.matrix.setPosition( this.position );
  1792. if ( this.useQuaternion ) {
  1793. this.matrix.setRotationFromQuaternion( this.quaternion );
  1794. } else {
  1795. this.matrix.setRotationFromEuler( this.rotation, this.eulerOrder );
  1796. }
  1797. if ( this.scale.x !== 1 || this.scale.y !== 1 || this.scale.z !== 1 ) {
  1798. this.matrix.scale( this.scale );
  1799. this.boundRadiusScale = Math.max( this.scale.x, Math.max( this.scale.y, this.scale.z ) );
  1800. }
  1801. this.matrixWorldNeedsUpdate = true;
  1802. },
  1803. updateMatrixWorld: function ( force ) {
  1804. this.matrixAutoUpdate && this.updateMatrix();
  1805. // update matrixWorld
  1806. if ( this.matrixWorldNeedsUpdate || force ) {
  1807. if ( this.parent ) {
  1808. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  1809. } else {
  1810. this.matrixWorld.copy( this.matrix );
  1811. }
  1812. this.matrixWorldNeedsUpdate = false;
  1813. force = true;
  1814. }
  1815. // update children
  1816. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  1817. this.children[ i ].updateMatrixWorld( force );
  1818. }
  1819. }
  1820. };
  1821. THREE.Object3DCount = 0;
  1822. /**
  1823. * @author mr.doob / http://mrdoob.com/
  1824. * @author supereggbert / http://www.paulbrunt.co.uk/
  1825. * @author julianwa / https://github.com/julianwa
  1826. */
  1827. THREE.Projector = function() {
  1828. var _object, _objectCount, _objectPool = [],
  1829. _vertex, _vertexCount, _vertexPool = [],
  1830. _face, _face3Count, _face3Pool = [], _face4Count, _face4Pool = [],
  1831. _line, _lineCount, _linePool = [],
  1832. _particle, _particleCount, _particlePool = [],
  1833. _renderData = { objects: [], sprites: [], lights: [], elements: [] },
  1834. _vector3 = new THREE.Vector3(),
  1835. _vector4 = new THREE.Vector4(),
  1836. _projScreenMatrix = new THREE.Matrix4(),
  1837. _projScreenobjectMatrixWorld = new THREE.Matrix4(),
  1838. _frustum = new THREE.Frustum(),
  1839. _clippedVertex1PositionScreen = new THREE.Vector4(),
  1840. _clippedVertex2PositionScreen = new THREE.Vector4(),
  1841. _face3VertexNormals;
  1842. this.projectVector = function ( vector, camera ) {
  1843. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1844. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  1845. _projScreenMatrix.multiplyVector3( vector );
  1846. return vector;
  1847. };
  1848. this.unprojectVector = function ( vector, camera ) {
  1849. camera.projectionMatrixInverse.getInverse( camera.projectionMatrix );
  1850. _projScreenMatrix.multiply( camera.matrixWorld, camera.projectionMatrixInverse );
  1851. _projScreenMatrix.multiplyVector3( vector );
  1852. return vector;
  1853. };
  1854. this.pickingRay = function ( vector, camera ) {
  1855. var end, ray, t;
  1856. // set two vectors with opposing z values
  1857. vector.z = -1.0;
  1858. end = new THREE.Vector3( vector.x, vector.y, 1.0 );
  1859. this.unprojectVector( vector, camera );
  1860. this.unprojectVector( end, camera );
  1861. // find direction from vector to end
  1862. end.subSelf( vector ).normalize();
  1863. return new THREE.Ray( vector, end );
  1864. };
  1865. this.projectGraph = function ( root, sort ) {
  1866. _objectCount = 0;
  1867. _renderData.objects.length = 0;
  1868. _renderData.sprites.length = 0;
  1869. _renderData.lights.length = 0;
  1870. var projectObject = function ( object ) {
  1871. if ( object.visible === false ) return;
  1872. if ( ( object instanceof THREE.Mesh || object instanceof THREE.Line ) &&
  1873. ( object.frustumCulled === false || _frustum.contains( object ) ) ) {
  1874. _vector3.copy( object.matrixWorld.getPosition() );
  1875. _projScreenMatrix.multiplyVector3( _vector3 );
  1876. _object = getNextObjectInPool();
  1877. _object.object = object;
  1878. _object.z = _vector3.z;
  1879. _renderData.objects.push( _object );
  1880. } else if ( object instanceof THREE.Sprite || object instanceof THREE.Particle ) {
  1881. _vector3.copy( object.matrixWorld.getPosition() );
  1882. _projScreenMatrix.multiplyVector3( _vector3 );
  1883. _object = getNextObjectInPool();
  1884. _object.object = object;
  1885. _object.z = _vector3.z;
  1886. _renderData.sprites.push( _object );
  1887. } else if ( object instanceof THREE.Light ) {
  1888. _renderData.lights.push( object );
  1889. }
  1890. for ( var c = 0, cl = object.children.length; c < cl; c ++ ) {
  1891. projectObject( object.children[ c ] );
  1892. }
  1893. };
  1894. projectObject( root );
  1895. sort && _renderData.objects.sort( painterSort );
  1896. return _renderData;
  1897. };
  1898. this.projectScene = function ( scene, camera, sort ) {
  1899. var near = camera.near, far = camera.far, visible = false,
  1900. o, ol, v, vl, f, fl, n, nl, c, cl, u, ul, object,
  1901. objectMatrixWorld, objectMatrixWorldRotation,
  1902. geometry, geometryMaterials, vertices, vertex, vertexPositionScreen,
  1903. faces, face, faceVertexNormals, normal, faceVertexUvs, uvs,
  1904. v1, v2, v3, v4;
  1905. _face3Count = 0;
  1906. _face4Count = 0;
  1907. _lineCount = 0;
  1908. _particleCount = 0;
  1909. _renderData.elements.length = 0;
  1910. if ( camera.parent === undefined ) {
  1911. console.warn( 'DEPRECATED: Camera hasn\'t been added to a Scene. Adding it...' );
  1912. scene.add( camera );
  1913. }
  1914. scene.updateMatrixWorld();
  1915. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  1916. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  1917. _frustum.setFromMatrix( _projScreenMatrix );
  1918. _renderData = this.projectGraph( scene, false );
  1919. for ( o = 0, ol = _renderData.objects.length; o < ol; o++ ) {
  1920. object = _renderData.objects[ o ].object;
  1921. objectMatrixWorld = object.matrixWorld;
  1922. _vertexCount = 0;
  1923. if ( object instanceof THREE.Mesh ) {
  1924. geometry = object.geometry;
  1925. geometryMaterials = object.geometry.materials;
  1926. vertices = geometry.vertices;
  1927. faces = geometry.faces;
  1928. faceVertexUvs = geometry.faceVertexUvs;
  1929. objectMatrixWorldRotation = object.matrixRotationWorld.extractRotation( objectMatrixWorld );
  1930. for ( v = 0, vl = vertices.length; v < vl; v ++ ) {
  1931. _vertex = getNextVertexInPool();
  1932. _vertex.positionWorld.copy( vertices[ v ].position );
  1933. objectMatrixWorld.multiplyVector3( _vertex.positionWorld );
  1934. _vertex.positionScreen.copy( _vertex.positionWorld );
  1935. _projScreenMatrix.multiplyVector4( _vertex.positionScreen );
  1936. _vertex.positionScreen.x /= _vertex.positionScreen.w;
  1937. _vertex.positionScreen.y /= _vertex.positionScreen.w;
  1938. _vertex.visible = _vertex.positionScreen.z > near && _vertex.positionScreen.z < far;
  1939. }
  1940. for ( f = 0, fl = faces.length; f < fl; f ++ ) {
  1941. face = faces[ f ];
  1942. if ( face instanceof THREE.Face3 ) {
  1943. v1 = _vertexPool[ face.a ];
  1944. v2 = _vertexPool[ face.b ];
  1945. v3 = _vertexPool[ face.c ];
  1946. if ( v1.visible && v2.visible && v3.visible ) {
  1947. visible = ( ( v3.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  1948. ( v3.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) ) < 0;
  1949. if ( object.doubleSided || visible != object.flipSided ) {
  1950. _face = getNextFace3InPool();
  1951. _face.v1.copy( v1 );
  1952. _face.v2.copy( v2 );
  1953. _face.v3.copy( v3 );
  1954. } else {
  1955. continue;
  1956. }
  1957. } else {
  1958. continue;
  1959. }
  1960. } else if ( face instanceof THREE.Face4 ) {
  1961. v1 = _vertexPool[ face.a ];
  1962. v2 = _vertexPool[ face.b ];
  1963. v3 = _vertexPool[ face.c ];
  1964. v4 = _vertexPool[ face.d ];
  1965. if ( v1.visible && v2.visible && v3.visible && v4.visible ) {
  1966. visible = ( v4.positionScreen.x - v1.positionScreen.x ) * ( v2.positionScreen.y - v1.positionScreen.y ) -
  1967. ( v4.positionScreen.y - v1.positionScreen.y ) * ( v2.positionScreen.x - v1.positionScreen.x ) < 0 ||
  1968. ( v2.positionScreen.x - v3.positionScreen.x ) * ( v4.positionScreen.y - v3.positionScreen.y ) -
  1969. ( v2.positionScreen.y - v3.positionScreen.y ) * ( v4.positionScreen.x - v3.positionScreen.x ) < 0;
  1970. if ( object.doubleSided || visible != object.flipSided ) {
  1971. _face = getNextFace4InPool();
  1972. _face.v1.copy( v1 );
  1973. _face.v2.copy( v2 );
  1974. _face.v3.copy( v3 );
  1975. _face.v4.copy( v4 );
  1976. } else {
  1977. continue;
  1978. }
  1979. } else {
  1980. continue;
  1981. }
  1982. }
  1983. _face.normalWorld.copy( face.normal );
  1984. if ( !visible && ( object.flipSided || object.doubleSided ) ) _face.normalWorld.negate();
  1985. objectMatrixWorldRotation.multiplyVector3( _face.normalWorld );
  1986. _face.centroidWorld.copy( face.centroid );
  1987. objectMatrixWorld.multiplyVector3( _face.centroidWorld );
  1988. _face.centroidScreen.copy( _face.centroidWorld );
  1989. _projScreenMatrix.multiplyVector3( _face.centroidScreen );
  1990. faceVertexNormals = face.vertexNormals;
  1991. for ( n = 0, nl = faceVertexNormals.length; n < nl; n ++ ) {
  1992. normal = _face.vertexNormalsWorld[ n ];
  1993. normal.copy( faceVertexNormals[ n ] );
  1994. if ( !visible && ( object.flipSided || object.doubleSided ) ) normal.negate();
  1995. objectMatrixWorldRotation.multiplyVector3( normal );
  1996. }
  1997. for ( c = 0, cl = faceVertexUvs.length; c < cl; c ++ ) {
  1998. uvs = faceVertexUvs[ c ][ f ];
  1999. if ( !uvs ) continue;
  2000. for ( u = 0, ul = uvs.length; u < ul; u ++ ) {
  2001. _face.uvs[ c ][ u ] = uvs[ u ];
  2002. }
  2003. }
  2004. _face.material = object.material;
  2005. _face.faceMaterial = face.materialIndex !== null ? geometryMaterials[ face.materialIndex ] : null;
  2006. _face.z = _face.centroidScreen.z;
  2007. _renderData.elements.push( _face );
  2008. }
  2009. } else if ( object instanceof THREE.Line ) {
  2010. _projScreenobjectMatrixWorld.multiply( _projScreenMatrix, objectMatrixWorld );
  2011. vertices = object.geometry.vertices;
  2012. v1 = getNextVertexInPool();
  2013. v1.positionScreen.copy( vertices[ 0 ].position );
  2014. _projScreenobjectMatrixWorld.multiplyVector4( v1.positionScreen );
  2015. // Handle LineStrip and LinePieces
  2016. var step = object.type === THREE.LinePieces ? 2 : 1;
  2017. for ( v = 1, vl = vertices.length; v < vl; v ++ ) {
  2018. v1 = getNextVertexInPool();
  2019. v1.positionScreen.copy( vertices[ v ].position );
  2020. _projScreenobjectMatrixWorld.multiplyVector4( v1.positionScreen );
  2021. if ( ( v + 1 ) % step > 0 ) continue;
  2022. v2 = _vertexPool[ _vertexCount - 2 ];
  2023. _clippedVertex1PositionScreen.copy( v1.positionScreen );
  2024. _clippedVertex2PositionScreen.copy( v2.positionScreen );
  2025. if ( clipLine( _clippedVertex1PositionScreen, _clippedVertex2PositionScreen ) ) {
  2026. // Perform the perspective divide
  2027. _clippedVertex1PositionScreen.multiplyScalar( 1 / _clippedVertex1PositionScreen.w );
  2028. _clippedVertex2PositionScreen.multiplyScalar( 1 / _clippedVertex2PositionScreen.w );
  2029. _line = getNextLineInPool();
  2030. _line.v1.positionScreen.copy( _clippedVertex1PositionScreen );
  2031. _line.v2.positionScreen.copy( _clippedVertex2PositionScreen );
  2032. _line.z = Math.max( _clippedVertex1PositionScreen.z, _clippedVertex2PositionScreen.z );
  2033. _line.material = object.material;
  2034. _renderData.elements.push( _line );
  2035. }
  2036. }
  2037. }
  2038. }
  2039. for ( o = 0, ol = _renderData.sprites.length; o < ol; o++ ) {
  2040. object = _renderData.sprites[ o ].object;
  2041. objectMatrixWorld = object.matrixWorld;
  2042. if ( object instanceof THREE.Particle ) {
  2043. _vector4.set( objectMatrixWorld.elements[12], objectMatrixWorld.elements[13], objectMatrixWorld.elements[14], 1 );
  2044. _projScreenMatrix.multiplyVector4( _vector4 );
  2045. _vector4.z /= _vector4.w;
  2046. if ( _vector4.z > 0 && _vector4.z < 1 ) {
  2047. _particle = getNextParticleInPool();
  2048. _particle.x = _vector4.x / _vector4.w;
  2049. _particle.y = _vector4.y / _vector4.w;
  2050. _particle.z = _vector4.z;
  2051. _particle.rotation = object.rotation.z;
  2052. _particle.scale.x = object.scale.x * Math.abs( _particle.x - ( _vector4.x + camera.projectionMatrix.elements[0] ) / ( _vector4.w + camera.projectionMatrix.elements[12] ) );
  2053. _particle.scale.y = object.scale.y * Math.abs( _particle.y - ( _vector4.y + camera.projectionMatrix.elements[5] ) / ( _vector4.w + camera.projectionMatrix.elements[13] ) );
  2054. _particle.material = object.material;
  2055. _renderData.elements.push( _particle );
  2056. }
  2057. }
  2058. }
  2059. sort && _renderData.elements.sort( painterSort );
  2060. return _renderData;
  2061. };
  2062. // Pools
  2063. function getNextObjectInPool() {
  2064. var object = _objectPool[ _objectCount ] = _objectPool[ _objectCount ] || new THREE.RenderableObject();
  2065. _objectCount ++;
  2066. return object;
  2067. }
  2068. function getNextVertexInPool() {
  2069. var vertex = _vertexPool[ _vertexCount ] = _vertexPool[ _vertexCount ] || new THREE.RenderableVertex();
  2070. _vertexCount ++;
  2071. return vertex;
  2072. }
  2073. function getNextFace3InPool() {
  2074. var face = _face3Pool[ _face3Count ] = _face3Pool[ _face3Count ] || new THREE.RenderableFace3();
  2075. _face3Count ++;
  2076. return face;
  2077. }
  2078. function getNextFace4InPool() {
  2079. var face = _face4Pool[ _face4Count ] = _face4Pool[ _face4Count ] || new THREE.RenderableFace4();
  2080. _face4Count ++;
  2081. return face;
  2082. }
  2083. function getNextLineInPool() {
  2084. var line = _linePool[ _lineCount ] = _linePool[ _lineCount ] || new THREE.RenderableLine();
  2085. _lineCount ++;
  2086. return line;
  2087. }
  2088. function getNextParticleInPool() {
  2089. var particle = _particlePool[ _particleCount ] = _particlePool[ _particleCount ] || new THREE.RenderableParticle();
  2090. _particleCount ++;
  2091. return particle;
  2092. }
  2093. //
  2094. function painterSort( a, b ) {
  2095. return b.z - a.z;
  2096. }
  2097. function clipLine( s1, s2 ) {
  2098. var alpha1 = 0, alpha2 = 1,
  2099. // Calculate the boundary coordinate of each vertex for the near and far clip planes,
  2100. // Z = -1 and Z = +1, respectively.
  2101. bc1near = s1.z + s1.w,
  2102. bc2near = s2.z + s2.w,
  2103. bc1far = - s1.z + s1.w,
  2104. bc2far = - s2.z + s2.w;
  2105. if ( bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0 ) {
  2106. // Both vertices lie entirely within all clip planes.
  2107. return true;
  2108. } else if ( ( bc1near < 0 && bc2near < 0) || (bc1far < 0 && bc2far < 0 ) ) {
  2109. // Both vertices lie entirely outside one of the clip planes.
  2110. return false;
  2111. } else {
  2112. // The line segment spans at least one clip plane.
  2113. if ( bc1near < 0 ) {
  2114. // v1 lies outside the near plane, v2 inside
  2115. alpha1 = Math.max( alpha1, bc1near / ( bc1near - bc2near ) );
  2116. } else if ( bc2near < 0 ) {
  2117. // v2 lies outside the near plane, v1 inside
  2118. alpha2 = Math.min( alpha2, bc1near / ( bc1near - bc2near ) );
  2119. }
  2120. if ( bc1far < 0 ) {
  2121. // v1 lies outside the far plane, v2 inside
  2122. alpha1 = Math.max( alpha1, bc1far / ( bc1far - bc2far ) );
  2123. } else if ( bc2far < 0 ) {
  2124. // v2 lies outside the far plane, v2 inside
  2125. alpha2 = Math.min( alpha2, bc1far / ( bc1far - bc2far ) );
  2126. }
  2127. if ( alpha2 < alpha1 ) {
  2128. // The line segment spans two boundaries, but is outside both of them.
  2129. // (This can't happen when we're only clipping against just near/far but good
  2130. // to leave the check here for future usage if other clip planes are added.)
  2131. return false;
  2132. } else {
  2133. // Update the s1 and s2 vertices to match the clipped line segment.
  2134. s1.lerpSelf( s2, alpha1 );
  2135. s2.lerpSelf( s1, 1 - alpha2 );
  2136. return true;
  2137. }
  2138. }
  2139. }
  2140. };
  2141. /**
  2142. * @author mikael emtinger / http://gomo.se/
  2143. * @author alteredq / http://alteredqualia.com/
  2144. */
  2145. THREE.Quaternion = function( x, y, z, w ) {
  2146. this.x = x || 0;
  2147. this.y = y || 0;
  2148. this.z = z || 0;
  2149. this.w = ( w !== undefined ) ? w : 1;
  2150. };
  2151. THREE.Quaternion.prototype = {
  2152. constructor: THREE.Quaternion,
  2153. set: function ( x, y, z, w ) {
  2154. this.x = x;
  2155. this.y = y;
  2156. this.z = z;
  2157. this.w = w;
  2158. return this;
  2159. },
  2160. copy: function ( q ) {
  2161. this.x = q.x;
  2162. this.y = q.y;
  2163. this.z = q.z;
  2164. this.w = q.w;
  2165. return this;
  2166. },
  2167. setFromEuler: function ( vector ) {
  2168. var c = Math.PI / 360, // 0.5 * Math.PI / 360, // 0.5 is an optimization
  2169. x = vector.x * c,
  2170. y = vector.y * c,
  2171. z = vector.z * c,
  2172. c1 = Math.cos( y ),
  2173. s1 = Math.sin( y ),
  2174. c2 = Math.cos( -z ),
  2175. s2 = Math.sin( -z ),
  2176. c3 = Math.cos( x ),
  2177. s3 = Math.sin( x ),
  2178. c1c2 = c1 * c2,
  2179. s1s2 = s1 * s2;
  2180. this.w = c1c2 * c3 - s1s2 * s3;
  2181. this.x = c1c2 * s3 + s1s2 * c3;
  2182. this.y = s1 * c2 * c3 + c1 * s2 * s3;
  2183. this.z = c1 * s2 * c3 - s1 * c2 * s3;
  2184. return this;
  2185. },
  2186. setFromAxisAngle: function ( axis, angle ) {
  2187. // from http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm
  2188. // axis have to be normalized
  2189. var halfAngle = angle / 2,
  2190. s = Math.sin( halfAngle );
  2191. this.x = axis.x * s;
  2192. this.y = axis.y * s;
  2193. this.z = axis.z * s;
  2194. this.w = Math.cos( halfAngle );
  2195. return this;
  2196. },
  2197. setFromRotationMatrix: function ( m ) {
  2198. // Adapted from: http://www.euclideanspace.com/maths/geometry/rotations/conversions/matrixToQuaternion/index.htm
  2199. function copySign( a, b ) {
  2200. return b < 0 ? -Math.abs( a ) : Math.abs( a );
  2201. }
  2202. var absQ = Math.pow( m.determinant(), 1.0 / 3.0 );
  2203. this.w = Math.sqrt( Math.max( 0, absQ + m.elements[0] + m.elements[5] + m.elements[10] ) ) / 2;
  2204. this.x = Math.sqrt( Math.max( 0, absQ + m.elements[0] - m.elements[5] - m.elements[10] ) ) / 2;
  2205. this.y = Math.sqrt( Math.max( 0, absQ - m.elements[0] + m.elements[5] - m.elements[10] ) ) / 2;
  2206. this.z = Math.sqrt( Math.max( 0, absQ - m.elements[0] - m.elements[5] + m.elements[10] ) ) / 2;
  2207. this.x = copySign( this.x, ( m.elements[6] - m.elements[9] ) );
  2208. this.y = copySign( this.y, ( m.elements[8] - m.elements[2] ) );
  2209. this.z = copySign( this.z, ( m.elements[1] - m.elements[4] ) );
  2210. this.normalize();
  2211. return this;
  2212. },
  2213. calculateW : function () {
  2214. this.w = - Math.sqrt( Math.abs( 1.0 - this.x * this.x - this.y * this.y - this.z * this.z ) );
  2215. return this;
  2216. },
  2217. inverse: function () {
  2218. this.x *= -1;
  2219. this.y *= -1;
  2220. this.z *= -1;
  2221. return this;
  2222. },
  2223. length: function () {
  2224. return Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2225. },
  2226. normalize: function () {
  2227. var l = Math.sqrt( this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w );
  2228. if ( l === 0 ) {
  2229. this.x = 0;
  2230. this.y = 0;
  2231. this.z = 0;
  2232. this.w = 0;
  2233. } else {
  2234. l = 1 / l;
  2235. this.x = this.x * l;
  2236. this.y = this.y * l;
  2237. this.z = this.z * l;
  2238. this.w = this.w * l;
  2239. }
  2240. return this;
  2241. },
  2242. multiply: function ( a, b ) {
  2243. // from http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/code/index.htm
  2244. this.x = a.x * b.w + a.y * b.z - a.z * b.y + a.w * b.x;
  2245. this.y = -a.x * b.z + a.y * b.w + a.z * b.x + a.w * b.y;
  2246. this.z = a.x * b.y - a.y * b.x + a.z * b.w + a.w * b.z;
  2247. this.w = -a.x * b.x - a.y * b.y - a.z * b.z + a.w * b.w;
  2248. return this;
  2249. },
  2250. multiplySelf: function ( b ) {
  2251. var qax = this.x, qay = this.y, qaz = this.z, qaw = this.w,
  2252. qbx = b.x, qby = b.y, qbz = b.z, qbw = b.w;
  2253. this.x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
  2254. this.y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
  2255. this.z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
  2256. this.w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
  2257. return this;
  2258. },
  2259. multiplyVector3: function ( vector, dest ) {
  2260. if ( !dest ) { dest = vector; }
  2261. var x = vector.x, y = vector.y, z = vector.z,
  2262. qx = this.x, qy = this.y, qz = this.z, qw = this.w;
  2263. // calculate quat * vector
  2264. var ix = qw * x + qy * z - qz * y,
  2265. iy = qw * y + qz * x - qx * z,
  2266. iz = qw * z + qx * y - qy * x,
  2267. iw = -qx * x - qy * y - qz * z;
  2268. // calculate result * inverse quat
  2269. dest.x = ix * qw + iw * -qx + iy * -qz - iz * -qy;
  2270. dest.y = iy * qw + iw * -qy + iz * -qx - ix * -qz;
  2271. dest.z = iz * qw + iw * -qz + ix * -qy - iy * -qx;
  2272. return dest;
  2273. },
  2274. clone: function () {
  2275. return new THREE.Quaternion( this.x, this.y, this.z, this.w );
  2276. }
  2277. }
  2278. THREE.Quaternion.slerp = function ( qa, qb, qm, t ) {
  2279. // http://www.euclideanspace.com/maths/algebra/realNormedAlgebra/quaternions/slerp/
  2280. var cosHalfTheta = qa.w * qb.w + qa.x * qb.x + qa.y * qb.y + qa.z * qb.z;
  2281. if (cosHalfTheta < 0) {
  2282. qm.w = -qb.w; qm.x = -qb.x; qm.y = -qb.y; qm.z = -qb.z;
  2283. cosHalfTheta = -cosHalfTheta;
  2284. } else {
  2285. qm.copy(qb);
  2286. }
  2287. if ( Math.abs( cosHalfTheta ) >= 1.0 ) {
  2288. qm.w = qa.w; qm.x = qa.x; qm.y = qa.y; qm.z = qa.z;
  2289. return qm;
  2290. }
  2291. var halfTheta = Math.acos( cosHalfTheta ),
  2292. sinHalfTheta = Math.sqrt( 1.0 - cosHalfTheta * cosHalfTheta );
  2293. if ( Math.abs( sinHalfTheta ) < 0.001 ) {
  2294. qm.w = 0.5 * ( qa.w + qb.w );
  2295. qm.x = 0.5 * ( qa.x + qb.x );
  2296. qm.y = 0.5 * ( qa.y + qb.y );
  2297. qm.z = 0.5 * ( qa.z + qb.z );
  2298. return qm;
  2299. }
  2300. var ratioA = Math.sin( ( 1 - t ) * halfTheta ) / sinHalfTheta,
  2301. ratioB = Math.sin( t * halfTheta ) / sinHalfTheta;
  2302. qm.w = ( qa.w * ratioA + qm.w * ratioB );
  2303. qm.x = ( qa.x * ratioA + qm.x * ratioB );
  2304. qm.y = ( qa.y * ratioA + qm.y * ratioB );
  2305. qm.z = ( qa.z * ratioA + qm.z * ratioB );
  2306. return qm;
  2307. }
  2308. /**
  2309. * @author mr.doob / http://mrdoob.com/
  2310. */
  2311. THREE.Vertex = function ( position ) {
  2312. this.position = position || new THREE.Vector3();
  2313. };
  2314. THREE.Vertex.prototype = {
  2315. constructor: THREE.Vertex,
  2316. clone: function () {
  2317. return new THREE.Vertex( this.position.clone() );
  2318. }
  2319. };
  2320. /**
  2321. * @author mr.doob / http://mrdoob.com/
  2322. * @author alteredq / http://alteredqualia.com/
  2323. */
  2324. THREE.Face3 = function ( a, b, c, normal, color, materialIndex ) {
  2325. this.a = a;
  2326. this.b = b;
  2327. this.c = c;
  2328. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2329. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2330. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2331. this.vertexColors = color instanceof Array ? color : [];
  2332. this.vertexTangents = [];
  2333. this.materialIndex = materialIndex;
  2334. this.centroid = new THREE.Vector3();
  2335. };
  2336. THREE.Face3.prototype = {
  2337. constructor: THREE.Face3,
  2338. clone: function () {
  2339. var face = new THREE.Face3( this.a, this.b, this.c );
  2340. face.normal.copy( this.normal );
  2341. face.color.copy( this.color );
  2342. face.centroid.copy( this.centroid );
  2343. face.materialIndex = this.materialIndex;
  2344. var i, il;
  2345. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2346. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2347. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2348. return face;
  2349. }
  2350. };
  2351. /**
  2352. * @author mr.doob / http://mrdoob.com/
  2353. * @author alteredq / http://alteredqualia.com/
  2354. */
  2355. THREE.Face4 = function ( a, b, c, d, normal, color, materialIndex ) {
  2356. this.a = a;
  2357. this.b = b;
  2358. this.c = c;
  2359. this.d = d;
  2360. this.normal = normal instanceof THREE.Vector3 ? normal : new THREE.Vector3();
  2361. this.vertexNormals = normal instanceof Array ? normal : [ ];
  2362. this.color = color instanceof THREE.Color ? color : new THREE.Color();
  2363. this.vertexColors = color instanceof Array ? color : [];
  2364. this.vertexTangents = [];
  2365. this.materialIndex = materialIndex;
  2366. this.centroid = new THREE.Vector3();
  2367. };
  2368. THREE.Face4.prototype = {
  2369. constructor: THREE.Face4,
  2370. clone: function () {
  2371. var face = new THREE.Face4( this.a, this.b, this.c, this.d );
  2372. face.normal.copy( this.normal );
  2373. face.color.copy( this.color );
  2374. face.centroid.copy( this.centroid );
  2375. face.materialIndex = this.materialIndex;
  2376. var i, il;
  2377. for ( i = 0, il = this.vertexNormals.length; i < il; i ++ ) face.vertexNormals[ i ] = this.vertexNormals[ i ].clone();
  2378. for ( i = 0, il = this.vertexColors.length; i < il; i ++ ) face.vertexColors[ i ] = this.vertexColors[ i ].clone();
  2379. for ( i = 0, il = this.vertexTangents.length; i < il; i ++ ) face.vertexTangents[ i ] = this.vertexTangents[ i ].clone();
  2380. return face;
  2381. }
  2382. };
  2383. /**
  2384. * @author mr.doob / http://mrdoob.com/
  2385. */
  2386. THREE.UV = function ( u, v ) {
  2387. this.u = u || 0;
  2388. this.v = v || 0;
  2389. };
  2390. THREE.UV.prototype = {
  2391. constructor: THREE.UV,
  2392. set: function ( u, v ) {
  2393. this.u = u;
  2394. this.v = v;
  2395. return this;
  2396. },
  2397. copy: function ( uv ) {
  2398. this.u = uv.u;
  2399. this.v = uv.v;
  2400. return this;
  2401. },
  2402. lerpSelf: function ( uv, alpha ) {
  2403. this.u += ( uv.u - this.u ) * alpha;
  2404. this.v += ( uv.v - this.v ) * alpha;
  2405. return this;
  2406. },
  2407. clone: function () {
  2408. return new THREE.UV( this.u, this.v );
  2409. }
  2410. };
  2411. /**
  2412. * @author mr.doob / http://mrdoob.com/
  2413. * @author kile / http://kile.stravaganza.org/
  2414. * @author alteredq / http://alteredqualia.com/
  2415. * @author mikael emtinger / http://gomo.se/
  2416. * @author zz85 / http://www.lab4games.net/zz85/blog
  2417. */
  2418. THREE.Geometry = function () {
  2419. this.id = THREE.GeometryCount ++;
  2420. this.vertices = [];
  2421. this.colors = []; // one-to-one vertex colors, used in ParticleSystem, Line and Ribbon
  2422. this.materials = [];
  2423. this.faces = [];
  2424. this.faceUvs = [[]];
  2425. this.faceVertexUvs = [[]];
  2426. this.morphTargets = [];
  2427. this.morphColors = [];
  2428. this.morphNormals = [];
  2429. this.skinWeights = [];
  2430. this.skinIndices = [];
  2431. this.boundingBox = null;
  2432. this.boundingSphere = null;
  2433. this.hasTangents = false;
  2434. this.dynamic = false; // unless set to true the *Arrays will be deleted once sent to a buffer.
  2435. };
  2436. THREE.Geometry.prototype = {
  2437. constructor : THREE.Geometry,
  2438. applyMatrix: function ( matrix ) {
  2439. var matrixRotation = new THREE.Matrix4();
  2440. matrixRotation.extractRotation( matrix );
  2441. for ( var i = 0, il = this.vertices.length; i < il; i ++ ) {
  2442. var vertex = this.vertices[ i ];
  2443. matrix.multiplyVector3( vertex.position );
  2444. }
  2445. for ( var i = 0, il = this.faces.length; i < il; i ++ ) {
  2446. var face = this.faces[ i ];
  2447. matrixRotation.multiplyVector3( face.normal );
  2448. for ( var j = 0, jl = face.vertexNormals.length; j < jl; j ++ ) {
  2449. matrixRotation.multiplyVector3( face.vertexNormals[ j ] );
  2450. }
  2451. matrix.multiplyVector3( face.centroid );
  2452. }
  2453. },
  2454. computeCentroids: function () {
  2455. var f, fl, face;
  2456. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2457. face = this.faces[ f ];
  2458. face.centroid.set( 0, 0, 0 );
  2459. if ( face instanceof THREE.Face3 ) {
  2460. face.centroid.addSelf( this.vertices[ face.a ].position );
  2461. face.centroid.addSelf( this.vertices[ face.b ].position );
  2462. face.centroid.addSelf( this.vertices[ face.c ].position );
  2463. face.centroid.divideScalar( 3 );
  2464. } else if ( face instanceof THREE.Face4 ) {
  2465. face.centroid.addSelf( this.vertices[ face.a ].position );
  2466. face.centroid.addSelf( this.vertices[ face.b ].position );
  2467. face.centroid.addSelf( this.vertices[ face.c ].position );
  2468. face.centroid.addSelf( this.vertices[ face.d ].position );
  2469. face.centroid.divideScalar( 4 );
  2470. }
  2471. }
  2472. },
  2473. computeFaceNormals: function () {
  2474. var n, nl, v, vl, vertex, f, fl, face, vA, vB, vC,
  2475. cb = new THREE.Vector3(), ab = new THREE.Vector3();
  2476. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2477. face = this.faces[ f ];
  2478. vA = this.vertices[ face.a ];
  2479. vB = this.vertices[ face.b ];
  2480. vC = this.vertices[ face.c ];
  2481. cb.sub( vC.position, vB.position );
  2482. ab.sub( vA.position, vB.position );
  2483. cb.crossSelf( ab );
  2484. if ( !cb.isZero() ) {
  2485. cb.normalize();
  2486. }
  2487. face.normal.copy( cb );
  2488. }
  2489. },
  2490. computeVertexNormals: function () {
  2491. var v, vl, f, fl, face, vertices;
  2492. // create internal buffers for reuse when calling this method repeatedly
  2493. // (otherwise memory allocation / deallocation every frame is big resource hog)
  2494. if ( this.__tmpVertices === undefined ) {
  2495. this.__tmpVertices = new Array( this.vertices.length );
  2496. vertices = this.__tmpVertices;
  2497. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2498. vertices[ v ] = new THREE.Vector3();
  2499. }
  2500. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2501. face = this.faces[ f ];
  2502. if ( face instanceof THREE.Face3 ) {
  2503. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2504. } else if ( face instanceof THREE.Face4 ) {
  2505. face.vertexNormals = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  2506. }
  2507. }
  2508. } else {
  2509. vertices = this.__tmpVertices;
  2510. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2511. vertices[ v ].set( 0, 0, 0 );
  2512. }
  2513. }
  2514. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2515. face = this.faces[ f ];
  2516. if ( face instanceof THREE.Face3 ) {
  2517. vertices[ face.a ].addSelf( face.normal );
  2518. vertices[ face.b ].addSelf( face.normal );
  2519. vertices[ face.c ].addSelf( face.normal );
  2520. } else if ( face instanceof THREE.Face4 ) {
  2521. vertices[ face.a ].addSelf( face.normal );
  2522. vertices[ face.b ].addSelf( face.normal );
  2523. vertices[ face.c ].addSelf( face.normal );
  2524. vertices[ face.d ].addSelf( face.normal );
  2525. }
  2526. }
  2527. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2528. vertices[ v ].normalize();
  2529. }
  2530. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2531. face = this.faces[ f ];
  2532. if ( face instanceof THREE.Face3 ) {
  2533. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2534. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  2535. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  2536. } else if ( face instanceof THREE.Face4 ) {
  2537. face.vertexNormals[ 0 ].copy( vertices[ face.a ] );
  2538. face.vertexNormals[ 1 ].copy( vertices[ face.b ] );
  2539. face.vertexNormals[ 2 ].copy( vertices[ face.c ] );
  2540. face.vertexNormals[ 3 ].copy( vertices[ face.d ] );
  2541. }
  2542. }
  2543. },
  2544. computeMorphNormals: function () {
  2545. var i, il, f, fl, face;
  2546. // save original normals
  2547. // - create temp variables on first access
  2548. // otherwise just copy (for faster repeated calls)
  2549. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2550. face = this.faces[ f ];
  2551. if ( ! face.__originalFaceNormal ) {
  2552. face.__originalFaceNormal = face.normal.clone();
  2553. } else {
  2554. face.__originalFaceNormal.copy( face.normal );
  2555. }
  2556. if ( ! face.__originalVertexNormals ) face.__originalVertexNormals = [];
  2557. for ( i = 0, il = face.vertexNormals.length; i < il; i ++ ) {
  2558. if ( ! face.__originalVertexNormals[ i ] ) {
  2559. face.__originalVertexNormals[ i ] = face.vertexNormals[ i ].clone();
  2560. } else {
  2561. face.__originalVertexNormals[ i ].copy( face.vertexNormals[ i ] );
  2562. }
  2563. }
  2564. }
  2565. // use temp geometry to compute face and vertex normals for each morph
  2566. var tmpGeo = new THREE.Geometry();
  2567. tmpGeo.faces = this.faces;
  2568. for ( i = 0, il = this.morphTargets.length; i < il; i ++ ) {
  2569. // create on first access
  2570. if ( ! this.morphNormals[ i ] ) {
  2571. this.morphNormals[ i ] = {};
  2572. this.morphNormals[ i ].faceNormals = [];
  2573. this.morphNormals[ i ].vertexNormals = [];
  2574. var dstNormalsFace = this.morphNormals[ i ].faceNormals;
  2575. var dstNormalsVertex = this.morphNormals[ i ].vertexNormals;
  2576. var faceNormal, vertexNormals;
  2577. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2578. face = this.faces[ f ];
  2579. faceNormal = new THREE.Vector3();
  2580. if ( face instanceof THREE.Face3 ) {
  2581. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3() };
  2582. } else {
  2583. vertexNormals = { a: new THREE.Vector3(), b: new THREE.Vector3(), c: new THREE.Vector3(), d: new THREE.Vector3() };
  2584. }
  2585. dstNormalsFace.push( faceNormal );
  2586. dstNormalsVertex.push( vertexNormals );
  2587. }
  2588. }
  2589. var morphNormals = this.morphNormals[ i ];
  2590. // set vertices to morph target
  2591. tmpGeo.vertices = this.morphTargets[ i ].vertices;
  2592. // compute morph normals
  2593. tmpGeo.computeFaceNormals();
  2594. tmpGeo.computeVertexNormals();
  2595. // store morph normals
  2596. var faceNormal, vertexNormals;
  2597. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2598. face = this.faces[ f ];
  2599. faceNormal = morphNormals.faceNormals[ f ];
  2600. vertexNormals = morphNormals.vertexNormals[ f ];
  2601. faceNormal.copy( face.normal );
  2602. if ( face instanceof THREE.Face3 ) {
  2603. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  2604. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  2605. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  2606. } else {
  2607. vertexNormals.a.copy( face.vertexNormals[ 0 ] );
  2608. vertexNormals.b.copy( face.vertexNormals[ 1 ] );
  2609. vertexNormals.c.copy( face.vertexNormals[ 2 ] );
  2610. vertexNormals.d.copy( face.vertexNormals[ 3 ] );
  2611. }
  2612. }
  2613. }
  2614. // restore original normals
  2615. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2616. face = this.faces[ f ];
  2617. face.normal = face.__originalFaceNormal;
  2618. face.vertexNormals = face.__originalVertexNormals;
  2619. }
  2620. },
  2621. computeTangents: function () {
  2622. // based on http://www.terathon.com/code/tangent.html
  2623. // tangents go to vertices
  2624. var f, fl, v, vl, i, il, vertexIndex,
  2625. face, uv, vA, vB, vC, uvA, uvB, uvC,
  2626. x1, x2, y1, y2, z1, z2,
  2627. s1, s2, t1, t2, r, t, test,
  2628. tan1 = [], tan2 = [],
  2629. sdir = new THREE.Vector3(), tdir = new THREE.Vector3(),
  2630. tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(),
  2631. n = new THREE.Vector3(), w;
  2632. for ( v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2633. tan1[ v ] = new THREE.Vector3();
  2634. tan2[ v ] = new THREE.Vector3();
  2635. }
  2636. function handleTriangle( context, a, b, c, ua, ub, uc ) {
  2637. vA = context.vertices[ a ].position;
  2638. vB = context.vertices[ b ].position;
  2639. vC = context.vertices[ c ].position;
  2640. uvA = uv[ ua ];
  2641. uvB = uv[ ub ];
  2642. uvC = uv[ uc ];
  2643. x1 = vB.x - vA.x;
  2644. x2 = vC.x - vA.x;
  2645. y1 = vB.y - vA.y;
  2646. y2 = vC.y - vA.y;
  2647. z1 = vB.z - vA.z;
  2648. z2 = vC.z - vA.z;
  2649. s1 = uvB.u - uvA.u;
  2650. s2 = uvC.u - uvA.u;
  2651. t1 = uvB.v - uvA.v;
  2652. t2 = uvC.v - uvA.v;
  2653. r = 1.0 / ( s1 * t2 - s2 * t1 );
  2654. sdir.set( ( t2 * x1 - t1 * x2 ) * r,
  2655. ( t2 * y1 - t1 * y2 ) * r,
  2656. ( t2 * z1 - t1 * z2 ) * r );
  2657. tdir.set( ( s1 * x2 - s2 * x1 ) * r,
  2658. ( s1 * y2 - s2 * y1 ) * r,
  2659. ( s1 * z2 - s2 * z1 ) * r );
  2660. tan1[ a ].addSelf( sdir );
  2661. tan1[ b ].addSelf( sdir );
  2662. tan1[ c ].addSelf( sdir );
  2663. tan2[ a ].addSelf( tdir );
  2664. tan2[ b ].addSelf( tdir );
  2665. tan2[ c ].addSelf( tdir );
  2666. }
  2667. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2668. face = this.faces[ f ];
  2669. uv = this.faceVertexUvs[ 0 ][ f ]; // use UV layer 0 for tangents
  2670. if ( face instanceof THREE.Face3 ) {
  2671. handleTriangle( this, face.a, face.b, face.c, 0, 1, 2 );
  2672. } else if ( face instanceof THREE.Face4 ) {
  2673. handleTriangle( this, face.a, face.b, face.d, 0, 1, 3 );
  2674. handleTriangle( this, face.b, face.c, face.d, 1, 2, 3 );
  2675. }
  2676. }
  2677. var faceIndex = [ 'a', 'b', 'c', 'd' ];
  2678. for ( f = 0, fl = this.faces.length; f < fl; f ++ ) {
  2679. face = this.faces[ f ];
  2680. for ( i = 0; i < face.vertexNormals.length; i++ ) {
  2681. n.copy( face.vertexNormals[ i ] );
  2682. vertexIndex = face[ faceIndex[ i ] ];
  2683. t = tan1[ vertexIndex ];
  2684. // Gram-Schmidt orthogonalize
  2685. tmp.copy( t );
  2686. tmp.subSelf( n.multiplyScalar( n.dot( t ) ) ).normalize();
  2687. // Calculate handedness
  2688. tmp2.cross( face.vertexNormals[ i ], t );
  2689. test = tmp2.dot( tan2[ vertexIndex ] );
  2690. w = (test < 0.0) ? -1.0 : 1.0;
  2691. face.vertexTangents[ i ] = new THREE.Vector4( tmp.x, tmp.y, tmp.z, w );
  2692. }
  2693. }
  2694. this.hasTangents = true;
  2695. },
  2696. computeBoundingBox: function () {
  2697. if ( ! this.boundingBox ) {
  2698. this.boundingBox = { min: new THREE.Vector3(), max: new THREE.Vector3() };
  2699. }
  2700. if ( this.vertices.length > 0 ) {
  2701. var position, firstPosition = this.vertices[ 0 ].position;
  2702. this.boundingBox.min.copy( firstPosition );
  2703. this.boundingBox.max.copy( firstPosition );
  2704. var min = this.boundingBox.min,
  2705. max = this.boundingBox.max;
  2706. for ( var v = 1, vl = this.vertices.length; v < vl; v ++ ) {
  2707. position = this.vertices[ v ].position;
  2708. if ( position.x < min.x ) {
  2709. min.x = position.x;
  2710. } else if ( position.x > max.x ) {
  2711. max.x = position.x;
  2712. }
  2713. if ( position.y < min.y ) {
  2714. min.y = position.y;
  2715. } else if ( position.y > max.y ) {
  2716. max.y = position.y;
  2717. }
  2718. if ( position.z < min.z ) {
  2719. min.z = position.z;
  2720. } else if ( position.z > max.z ) {
  2721. max.z = position.z;
  2722. }
  2723. }
  2724. } else {
  2725. this.boundingBox.min.set( 0, 0, 0 );
  2726. this.boundingBox.max.set( 0, 0, 0 );
  2727. }
  2728. },
  2729. computeBoundingSphere: function () {
  2730. if ( ! this.boundingSphere ) this.boundingSphere = { radius: 0 };
  2731. var radius, maxRadius = 0;
  2732. for ( var v = 0, vl = this.vertices.length; v < vl; v ++ ) {
  2733. radius = this.vertices[ v ].position.length();
  2734. if ( radius > maxRadius ) maxRadius = radius;
  2735. }
  2736. this.boundingSphere.radius = maxRadius;
  2737. },
  2738. /*
  2739. * Checks for duplicate vertices with hashmap.
  2740. * Duplicated vertices are removed
  2741. * and faces' vertices are updated.
  2742. */
  2743. mergeVertices: function() {
  2744. var verticesMap = {}; // Hashmap for looking up vertice by position coordinates (and making sure they are unique)
  2745. var unique = [], changes = [];
  2746. var v, key;
  2747. var precisionPoints = 4; // number of decimal points, eg. 4 for epsilon of 0.0001
  2748. var precision = Math.pow( 10, precisionPoints );
  2749. var i,il, face;
  2750. for ( i = 0, il = this.vertices.length; i < il; i ++ ) {
  2751. v = this.vertices[ i ].position;
  2752. key = [ Math.round( v.x * precision ), Math.round( v.y * precision ), Math.round( v.z * precision ) ].join( '_' );
  2753. if ( verticesMap[ key ] === undefined ) {
  2754. verticesMap[ key ] = i;
  2755. unique.push( this.vertices[ i ] );
  2756. changes[ i ] = unique.length - 1;
  2757. } else {
  2758. //console.log('Duplicate vertex found. ', i, ' could be using ', verticesMap[key]);
  2759. changes[ i ] = changes[ verticesMap[ key ] ];
  2760. }
  2761. };
  2762. // Start to patch face indices
  2763. for( i = 0, il = this.faces.length; i < il; i ++ ) {
  2764. face = this.faces[ i ];
  2765. if ( face instanceof THREE.Face3 ) {
  2766. face.a = changes[ face.a ];
  2767. face.b = changes[ face.b ];
  2768. face.c = changes[ face.c ];
  2769. } else if ( face instanceof THREE.Face4 ) {
  2770. face.a = changes[ face.a ];
  2771. face.b = changes[ face.b ];
  2772. face.c = changes[ face.c ];
  2773. face.d = changes[ face.d ];
  2774. }
  2775. }
  2776. // Use unique set of vertices
  2777. this.vertices = unique;
  2778. }
  2779. };
  2780. THREE.GeometryCount = 0;
  2781. /**
  2782. * Spline from Tween.js, slightly optimized (and trashed)
  2783. * http://sole.github.com/tween.js/examples/05_spline.html
  2784. *
  2785. * @author mrdoob / http://mrdoob.com/
  2786. * @author alteredq / http://alteredqualia.com/
  2787. */
  2788. THREE.Spline = function ( points ) {
  2789. this.points = points;
  2790. var c = [], v3 = { x: 0, y: 0, z: 0 },
  2791. point, intPoint, weight, w2, w3,
  2792. pa, pb, pc, pd;
  2793. this.initFromArray = function( a ) {
  2794. this.points = [];
  2795. for ( var i = 0; i < a.length; i++ ) {
  2796. this.points[ i ] = { x: a[ i ][ 0 ], y: a[ i ][ 1 ], z: a[ i ][ 2 ] };
  2797. }
  2798. };
  2799. this.getPoint = function ( k ) {
  2800. point = ( this.points.length - 1 ) * k;
  2801. intPoint = Math.floor( point );
  2802. weight = point - intPoint;
  2803. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  2804. c[ 1 ] = intPoint;
  2805. c[ 2 ] = intPoint > this.points.length - 2 ? this.points.length - 1 : intPoint + 1;
  2806. c[ 3 ] = intPoint > this.points.length - 3 ? this.points.length - 1 : intPoint + 2;
  2807. pa = this.points[ c[ 0 ] ];
  2808. pb = this.points[ c[ 1 ] ];
  2809. pc = this.points[ c[ 2 ] ];
  2810. pd = this.points[ c[ 3 ] ];
  2811. w2 = weight * weight;
  2812. w3 = weight * w2;
  2813. v3.x = interpolate( pa.x, pb.x, pc.x, pd.x, weight, w2, w3 );
  2814. v3.y = interpolate( pa.y, pb.y, pc.y, pd.y, weight, w2, w3 );
  2815. v3.z = interpolate( pa.z, pb.z, pc.z, pd.z, weight, w2, w3 );
  2816. return v3;
  2817. };
  2818. this.getControlPointsArray = function () {
  2819. var i, p, l = this.points.length,
  2820. coords = [];
  2821. for ( i = 0; i < l; i ++ ) {
  2822. p = this.points[ i ];
  2823. coords[ i ] = [ p.x, p.y, p.z ];
  2824. }
  2825. return coords;
  2826. };
  2827. // approximate length by summing linear segments
  2828. this.getLength = function ( nSubDivisions ) {
  2829. var i, index, nSamples, position,
  2830. point = 0, intPoint = 0, oldIntPoint = 0,
  2831. oldPosition = new THREE.Vector3(),
  2832. tmpVec = new THREE.Vector3(),
  2833. chunkLengths = [],
  2834. totalLength = 0;
  2835. // first point has 0 length
  2836. chunkLengths[ 0 ] = 0;
  2837. if ( !nSubDivisions ) nSubDivisions = 100;
  2838. nSamples = this.points.length * nSubDivisions;
  2839. oldPosition.copy( this.points[ 0 ] );
  2840. for ( i = 1; i < nSamples; i ++ ) {
  2841. index = i / nSamples;
  2842. position = this.getPoint( index );
  2843. tmpVec.copy( position );
  2844. totalLength += tmpVec.distanceTo( oldPosition );
  2845. oldPosition.copy( position );
  2846. point = ( this.points.length - 1 ) * index;
  2847. intPoint = Math.floor( point );
  2848. if ( intPoint != oldIntPoint ) {
  2849. chunkLengths[ intPoint ] = totalLength;
  2850. oldIntPoint = intPoint;
  2851. }
  2852. }
  2853. // last point ends with total length
  2854. chunkLengths[ chunkLengths.length ] = totalLength;
  2855. return { chunks: chunkLengths, total: totalLength };
  2856. };
  2857. this.reparametrizeByArcLength = function ( samplingCoef ) {
  2858. var i, j,
  2859. index, indexCurrent, indexNext,
  2860. linearDistance, realDistance,
  2861. sampling, position,
  2862. newpoints = [],
  2863. tmpVec = new THREE.Vector3(),
  2864. sl = this.getLength();
  2865. newpoints.push( tmpVec.copy( this.points[ 0 ] ).clone() );
  2866. for ( i = 1; i < this.points.length; i++ ) {
  2867. //tmpVec.copy( this.points[ i - 1 ] );
  2868. //linearDistance = tmpVec.distanceTo( this.points[ i ] );
  2869. realDistance = sl.chunks[ i ] - sl.chunks[ i - 1 ];
  2870. sampling = Math.ceil( samplingCoef * realDistance / sl.total );
  2871. indexCurrent = ( i - 1 ) / ( this.points.length - 1 );
  2872. indexNext = i / ( this.points.length - 1 );
  2873. for ( j = 1; j < sampling - 1; j++ ) {
  2874. index = indexCurrent + j * ( 1 / sampling ) * ( indexNext - indexCurrent );
  2875. position = this.getPoint( index );
  2876. newpoints.push( tmpVec.copy( position ).clone() );
  2877. }
  2878. newpoints.push( tmpVec.copy( this.points[ i ] ).clone() );
  2879. }
  2880. this.points = newpoints;
  2881. };
  2882. // Catmull-Rom
  2883. function interpolate( p0, p1, p2, p3, t, t2, t3 ) {
  2884. var v0 = ( p2 - p0 ) * 0.5,
  2885. v1 = ( p3 - p1 ) * 0.5;
  2886. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  2887. };
  2888. };
  2889. /**
  2890. * @author mr.doob / http://mrdoob.com/
  2891. * @author mikael emtinger / http://gomo.se/
  2892. */
  2893. THREE.Camera = function () {
  2894. THREE.Object3D.call( this );
  2895. this.matrixWorldInverse = new THREE.Matrix4();
  2896. this.projectionMatrix = new THREE.Matrix4();
  2897. this.projectionMatrixInverse = new THREE.Matrix4();
  2898. };
  2899. THREE.Camera.prototype = new THREE.Object3D();
  2900. THREE.Camera.prototype.constructor = THREE.Camera;
  2901. THREE.Camera.prototype.lookAt = function ( vector ) {
  2902. // TODO: Add hierarchy support.
  2903. this.matrix.lookAt( this.position, vector, this.up );
  2904. if ( this.rotationAutoUpdate ) {
  2905. this.rotation.getRotationFromMatrix( this.matrix );
  2906. }
  2907. };
  2908. /**
  2909. * @author alteredq / http://alteredqualia.com/
  2910. */
  2911. THREE.OrthographicCamera = function ( left, right, top, bottom, near, far ) {
  2912. THREE.Camera.call( this );
  2913. this.left = left;
  2914. this.right = right;
  2915. this.top = top;
  2916. this.bottom = bottom;
  2917. this.near = ( near !== undefined ) ? near : 0.1;
  2918. this.far = ( far !== undefined ) ? far : 2000;
  2919. this.updateProjectionMatrix();
  2920. };
  2921. THREE.OrthographicCamera.prototype = new THREE.Camera();
  2922. THREE.OrthographicCamera.prototype.constructor = THREE.OrthographicCamera;
  2923. THREE.OrthographicCamera.prototype.updateProjectionMatrix = function () {
  2924. this.projectionMatrix.makeOrthographic( this.left, this.right, this.top, this.bottom, this.near, this.far );
  2925. };
  2926. /**
  2927. * @author mr.doob / http://mrdoob.com/
  2928. * @author greggman / http://games.greggman.com/
  2929. * @author zz85 / http://www.lab4games.net/zz85/blog
  2930. */
  2931. THREE.PerspectiveCamera = function ( fov, aspect, near, far ) {
  2932. THREE.Camera.call( this );
  2933. this.fov = fov !== undefined ? fov : 50;
  2934. this.aspect = aspect !== undefined ? aspect : 1;
  2935. this.near = near !== undefined ? near : 0.1;
  2936. this.far = far !== undefined ? far : 2000;
  2937. this.updateProjectionMatrix();
  2938. };
  2939. THREE.PerspectiveCamera.prototype = new THREE.Camera();
  2940. THREE.PerspectiveCamera.prototype.constructor = THREE.PerspectiveCamera;
  2941. /**
  2942. * Uses Focal Length (in mm) to estimate and set FOV
  2943. * 35mm (fullframe) camera is used if frame size is not specified;
  2944. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  2945. */
  2946. THREE.PerspectiveCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  2947. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  2948. this.fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  2949. this.updateProjectionMatrix();
  2950. }
  2951. /**
  2952. * Sets an offset in a larger frustum. This is useful for multi-window or
  2953. * multi-monitor/multi-machine setups.
  2954. *
  2955. * For example, if you have 3x2 monitors and each monitor is 1920x1080 and
  2956. * the monitors are in grid like this
  2957. *
  2958. * +---+---+---+
  2959. * | A | B | C |
  2960. * +---+---+---+
  2961. * | D | E | F |
  2962. * +---+---+---+
  2963. *
  2964. * then for each monitor you would call it like this
  2965. *
  2966. * var w = 1920;
  2967. * var h = 1080;
  2968. * var fullWidth = w * 3;
  2969. * var fullHeight = h * 2;
  2970. *
  2971. * --A--
  2972. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 0, w, h );
  2973. * --B--
  2974. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 0, w, h );
  2975. * --C--
  2976. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 0, w, h );
  2977. * --D--
  2978. * camera.setOffset( fullWidth, fullHeight, w * 0, h * 1, w, h );
  2979. * --E--
  2980. * camera.setOffset( fullWidth, fullHeight, w * 1, h * 1, w, h );
  2981. * --F--
  2982. * camera.setOffset( fullWidth, fullHeight, w * 2, h * 1, w, h );
  2983. *
  2984. * Note there is no reason monitors have to be the same size or in a grid.
  2985. */
  2986. THREE.PerspectiveCamera.prototype.setViewOffset = function ( fullWidth, fullHeight, x, y, width, height ) {
  2987. this.fullWidth = fullWidth;
  2988. this.fullHeight = fullHeight;
  2989. this.x = x;
  2990. this.y = y;
  2991. this.width = width;
  2992. this.height = height;
  2993. this.updateProjectionMatrix();
  2994. };
  2995. THREE.PerspectiveCamera.prototype.updateProjectionMatrix = function () {
  2996. if ( this.fullWidth ) {
  2997. var aspect = this.fullWidth / this.fullHeight;
  2998. var top = Math.tan( this.fov * Math.PI / 360 ) * this.near;
  2999. var bottom = -top;
  3000. var left = aspect * bottom;
  3001. var right = aspect * top;
  3002. var width = Math.abs( right - left );
  3003. var height = Math.abs( top - bottom );
  3004. this.projectionMatrix.makeFrustum(
  3005. left + this.x * width / this.fullWidth,
  3006. left + ( this.x + this.width ) * width / this.fullWidth,
  3007. top - ( this.y + this.height ) * height / this.fullHeight,
  3008. top - this.y * height / this.fullHeight,
  3009. this.near,
  3010. this.far
  3011. );
  3012. } else {
  3013. this.projectionMatrix.makePerspective( this.fov, this.aspect, this.near, this.far );
  3014. }
  3015. };
  3016. /**
  3017. * @author mr.doob / http://mrdoob.com/
  3018. * @author alteredq / http://alteredqualia.com/
  3019. */
  3020. THREE.Light = function ( hex ) {
  3021. THREE.Object3D.call( this );
  3022. this.color = new THREE.Color( hex );
  3023. };
  3024. THREE.Light.prototype = new THREE.Object3D();
  3025. THREE.Light.prototype.constructor = THREE.Light;
  3026. THREE.Light.prototype.supr = THREE.Object3D.prototype;
  3027. /**
  3028. * @author mr.doob / http://mrdoob.com/
  3029. */
  3030. THREE.AmbientLight = function ( hex ) {
  3031. THREE.Light.call( this, hex );
  3032. };
  3033. THREE.AmbientLight.prototype = new THREE.Light();
  3034. THREE.AmbientLight.prototype.constructor = THREE.AmbientLight;
  3035. /**
  3036. * @author mr.doob / http://mrdoob.com/
  3037. * @author alteredq / http://alteredqualia.com/
  3038. */
  3039. THREE.DirectionalLight = function ( hex, intensity, distance ) {
  3040. THREE.Light.call( this, hex );
  3041. this.position = new THREE.Vector3( 0, 1, 0 );
  3042. this.target = new THREE.Object3D();
  3043. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3044. this.distance = ( distance !== undefined ) ? distance : 0;
  3045. this.castShadow = false;
  3046. this.onlyShadow = false;
  3047. //
  3048. this.shadowCameraNear = 50;
  3049. this.shadowCameraFar = 5000;
  3050. this.shadowCameraLeft = -500;
  3051. this.shadowCameraRight = 500;
  3052. this.shadowCameraTop = 500;
  3053. this.shadowCameraBottom = -500;
  3054. this.shadowCameraVisible = false;
  3055. this.shadowBias = 0;
  3056. this.shadowDarkness = 0.5;
  3057. this.shadowMapWidth = 512;
  3058. this.shadowMapHeight = 512;
  3059. //
  3060. this.shadowCascade = false;
  3061. this.shadowCascadeOffset = new THREE.Vector3( 0, 0, -1000 );
  3062. this.shadowCascadeCount = 2;
  3063. this.shadowCascadeBias = [ 0, 0, 0 ];
  3064. this.shadowCascadeWidth = [ 512, 512, 512 ];
  3065. this.shadowCascadeHeight = [ 512, 512, 512 ];
  3066. this.shadowCascadeNearZ = [ -1.000, 0.990, 0.998 ];
  3067. this.shadowCascadeFarZ = [ 0.990, 0.998, 1.000 ];
  3068. this.shadowCascadeArray = [];
  3069. //
  3070. this.shadowMap = null;
  3071. this.shadowMapSize = null;
  3072. this.shadowCamera = null;
  3073. this.shadowMatrix = null;
  3074. };
  3075. THREE.DirectionalLight.prototype = new THREE.Light();
  3076. THREE.DirectionalLight.prototype.constructor = THREE.DirectionalLight;
  3077. /**
  3078. * @author mr.doob / http://mrdoob.com/
  3079. */
  3080. THREE.PointLight = function ( hex, intensity, distance ) {
  3081. THREE.Light.call( this, hex );
  3082. this.position = new THREE.Vector3( 0, 0, 0 );
  3083. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3084. this.distance = ( distance !== undefined ) ? distance : 0;
  3085. };
  3086. THREE.PointLight.prototype = new THREE.Light();
  3087. THREE.PointLight.prototype.constructor = THREE.PointLight;
  3088. /**
  3089. * @author alteredq / http://alteredqualia.com/
  3090. */
  3091. THREE.SpotLight = function ( hex, intensity, distance ) {
  3092. THREE.Light.call( this, hex );
  3093. this.position = new THREE.Vector3( 0, 1, 0 );
  3094. this.target = new THREE.Object3D();
  3095. this.intensity = ( intensity !== undefined ) ? intensity : 1;
  3096. this.distance = ( distance !== undefined ) ? distance : 0;
  3097. this.castShadow = false;
  3098. this.onlyShadow = false;
  3099. //
  3100. this.shadowCameraNear = 50;
  3101. this.shadowCameraFar = 5000;
  3102. this.shadowCameraFov = 50;
  3103. this.shadowCameraVisible = false;
  3104. this.shadowBias = 0;
  3105. this.shadowDarkness = 0.5;
  3106. this.shadowMapWidth = 512;
  3107. this.shadowMapHeight = 512;
  3108. //
  3109. this.shadowMap = null;
  3110. this.shadowMapSize = null;
  3111. this.shadowCamera = null;
  3112. this.shadowMatrix = null;
  3113. };
  3114. THREE.SpotLight.prototype = new THREE.Light();
  3115. THREE.SpotLight.prototype.constructor = THREE.SpotLight;
  3116. /**
  3117. * @author mr.doob / http://mrdoob.com/
  3118. * @author alteredq / http://alteredqualia.com/
  3119. */
  3120. THREE.Material = function ( parameters ) {
  3121. parameters = parameters || {};
  3122. this.id = THREE.MaterialCount ++;
  3123. this.name = '';
  3124. this.opacity = parameters.opacity !== undefined ? parameters.opacity : 1;
  3125. this.transparent = parameters.transparent !== undefined ? parameters.transparent : false;
  3126. this.blending = parameters.blending !== undefined ? parameters.blending : THREE.NormalBlending;
  3127. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  3128. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  3129. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  3130. this.depthTest = parameters.depthTest !== undefined ? parameters.depthTest : true;
  3131. this.depthWrite = parameters.depthWrite !== undefined ? parameters.depthWrite : true;
  3132. this.polygonOffset = parameters.polygonOffset !== undefined ? parameters.polygonOffset : false;
  3133. this.polygonOffsetFactor = parameters.polygonOffsetFactor !== undefined ? parameters.polygonOffsetFactor : 0;
  3134. this.polygonOffsetUnits = parameters.polygonOffsetUnits !== undefined ? parameters.polygonOffsetUnits : 0;
  3135. this.alphaTest = parameters.alphaTest !== undefined ? parameters.alphaTest : 0;
  3136. this.overdraw = parameters.overdraw !== undefined ? parameters.overdraw : false; // Boolean for fixing antialiasing gaps in CanvasRenderer
  3137. this.needsUpdate = true;
  3138. }
  3139. THREE.MaterialCount = 0;
  3140. // shading
  3141. THREE.NoShading = 0;
  3142. THREE.FlatShading = 1;
  3143. THREE.SmoothShading = 2;
  3144. // colors
  3145. THREE.NoColors = 0;
  3146. THREE.FaceColors = 1;
  3147. THREE.VertexColors = 2;
  3148. // blending modes
  3149. THREE.NoBlending = 0;
  3150. THREE.NormalBlending = 1;
  3151. THREE.AdditiveBlending = 2;
  3152. THREE.SubtractiveBlending = 3;
  3153. THREE.MultiplyBlending = 4;
  3154. THREE.AdditiveAlphaBlending = 5;
  3155. THREE.CustomBlending = 6;
  3156. // custom blending equations
  3157. // (numbers start from 100 not to clash with other
  3158. // mappings to OpenGL constants defined in Texture.js)
  3159. THREE.AddEquation = 100;
  3160. THREE.SubtractEquation = 101;
  3161. THREE.ReverseSubtractEquation = 102;
  3162. // custom blending destination factors
  3163. THREE.ZeroFactor = 200;
  3164. THREE.OneFactor = 201;
  3165. THREE.SrcColorFactor = 202;
  3166. THREE.OneMinusSrcColorFactor = 203;
  3167. THREE.SrcAlphaFactor = 204;
  3168. THREE.OneMinusSrcAlphaFactor = 205;
  3169. THREE.DstAlphaFactor = 206;
  3170. THREE.OneMinusDstAlphaFactor = 207;
  3171. // custom blending source factors
  3172. //THREE.ZeroFactor = 200;
  3173. //THREE.OneFactor = 201;
  3174. //THREE.SrcAlphaFactor = 204;
  3175. //THREE.OneMinusSrcAlphaFactor = 205;
  3176. //THREE.DstAlphaFactor = 206;
  3177. //THREE.OneMinusDstAlphaFactor = 207;
  3178. THREE.DstColorFactor = 208;
  3179. THREE.OneMinusDstColorFactor = 209;
  3180. THREE.SrcAlphaSaturateFactor = 210;
  3181. /**
  3182. * @author mr.doob / http://mrdoob.com/
  3183. * @author alteredq / http://alteredqualia.com/
  3184. *
  3185. * parameters = {
  3186. * color: <hex>,
  3187. * opacity: <float>,
  3188. *
  3189. * blending: THREE.NormalBlending,
  3190. * depthTest: <bool>,
  3191. *
  3192. * linewidth: <float>,
  3193. * linecap: "round",
  3194. * linejoin: "round",
  3195. *
  3196. * vertexColors: <bool>
  3197. *
  3198. * fog: <bool>
  3199. * }
  3200. */
  3201. THREE.LineBasicMaterial = function ( parameters ) {
  3202. THREE.Material.call( this, parameters );
  3203. parameters = parameters || {};
  3204. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3205. this.linewidth = parameters.linewidth !== undefined ? parameters.linewidth : 1;
  3206. this.linecap = parameters.linecap !== undefined ? parameters.linecap : 'round';
  3207. this.linejoin = parameters.linejoin !== undefined ? parameters.linejoin : 'round';
  3208. this.vertexColors = parameters.vertexColors ? parameters.vertexColors : false;
  3209. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3210. };
  3211. THREE.LineBasicMaterial.prototype = new THREE.Material();
  3212. THREE.LineBasicMaterial.prototype.constructor = THREE.LineBasicMaterial;
  3213. /**
  3214. * @author mr.doob / http://mrdoob.com/
  3215. * @author alteredq / http://alteredqualia.com/
  3216. *
  3217. * parameters = {
  3218. * color: <hex>,
  3219. * opacity: <float>,
  3220. * map: new THREE.Texture( <Image> ),
  3221. *
  3222. * lightMap: new THREE.Texture( <Image> ),
  3223. *
  3224. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3225. * combine: THREE.Multiply,
  3226. * reflectivity: <float>,
  3227. * refractionRatio: <float>,
  3228. *
  3229. * shading: THREE.SmoothShading,
  3230. * blending: THREE.NormalBlending,
  3231. * depthTest: <bool>,
  3232. *
  3233. * wireframe: <boolean>,
  3234. * wireframeLinewidth: <float>,
  3235. *
  3236. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3237. *
  3238. * skinning: <bool>,
  3239. * morphTargets: <bool>,
  3240. *
  3241. * fog: <bool>
  3242. * }
  3243. */
  3244. THREE.MeshBasicMaterial = function ( parameters ) {
  3245. THREE.Material.call( this, parameters );
  3246. parameters = parameters || {};
  3247. // color property represents emissive for MeshBasicMaterial
  3248. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3249. this.map = parameters.map !== undefined ? parameters.map : null;
  3250. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3251. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3252. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3253. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3254. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3255. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3256. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3257. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3258. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3259. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3260. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3261. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3262. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3263. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3264. };
  3265. THREE.MeshBasicMaterial.prototype = new THREE.Material();
  3266. THREE.MeshBasicMaterial.prototype.constructor = THREE.MeshBasicMaterial;
  3267. /**
  3268. * @author mr.doob / http://mrdoob.com/
  3269. * @author alteredq / http://alteredqualia.com/
  3270. *
  3271. * parameters = {
  3272. * color: <hex>,
  3273. * ambient: <hex>,
  3274. * emissive: <hex>,
  3275. * opacity: <float>,
  3276. *
  3277. * map: new THREE.Texture( <Image> ),
  3278. *
  3279. * lightMap: new THREE.Texture( <Image> ),
  3280. *
  3281. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3282. * combine: THREE.Multiply,
  3283. * reflectivity: <float>,
  3284. * refractionRatio: <float>,
  3285. *
  3286. * shading: THREE.SmoothShading,
  3287. * blending: THREE.NormalBlending,
  3288. * depthTest: <bool>,
  3289. *
  3290. * wireframe: <boolean>,
  3291. * wireframeLinewidth: <float>,
  3292. *
  3293. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3294. *
  3295. * skinning: <bool>,
  3296. * morphTargets: <bool>,
  3297. * morphNormals: <bool>,
  3298. *
  3299. * fog: <bool>
  3300. * }
  3301. */
  3302. THREE.MeshLambertMaterial = function ( parameters ) {
  3303. THREE.Material.call( this, parameters );
  3304. parameters = parameters || {};
  3305. // color property represents diffuse for MeshLambertMaterial
  3306. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3307. this.ambient = parameters.ambient !== undefined ? new THREE.Color( parameters.ambient ) : new THREE.Color( 0xffffff );
  3308. this.emissive = parameters.emissive !== undefined ? new THREE.Color( parameters.emissive ) : new THREE.Color( 0x000000 );
  3309. this.wrapAround = parameters.wrapAround !== undefined ? parameters.wrapAround: false;
  3310. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  3311. this.map = parameters.map !== undefined ? parameters.map : null;
  3312. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3313. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3314. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3315. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3316. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3317. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3318. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3319. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3320. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3321. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3322. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3323. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3324. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3325. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3326. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false;
  3327. };
  3328. THREE.MeshLambertMaterial.prototype = new THREE.Material();
  3329. THREE.MeshLambertMaterial.prototype.constructor = THREE.MeshLambertMaterial;
  3330. /**
  3331. * @author mr.doob / http://mrdoob.com/
  3332. * @author alteredq / http://alteredqualia.com/
  3333. *
  3334. * parameters = {
  3335. * color: <hex>,
  3336. * ambient: <hex>,
  3337. * emissive: <hex>,
  3338. * specular: <hex>,
  3339. * shininess: <float>,
  3340. * opacity: <float>,
  3341. *
  3342. * map: new THREE.Texture( <Image> ),
  3343. *
  3344. * lightMap: new THREE.Texture( <Image> ),
  3345. *
  3346. * envMap: new THREE.TextureCube( [posx, negx, posy, negy, posz, negz] ),
  3347. * combine: THREE.Multiply,
  3348. * reflectivity: <float>,
  3349. * refractionRatio: <float>,
  3350. *
  3351. * shading: THREE.SmoothShading,
  3352. * blending: THREE.NormalBlending,
  3353. * depthTest: <bool>,
  3354. *
  3355. * wireframe: <boolean>,
  3356. * wireframeLinewidth: <float>,
  3357. *
  3358. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3359. *
  3360. * skinning: <bool>,
  3361. * morphTargets: <bool>,
  3362. * morphNormals: <bool>,
  3363. *
  3364. * fog: <bool>
  3365. * }
  3366. */
  3367. THREE.MeshPhongMaterial = function ( parameters ) {
  3368. THREE.Material.call( this, parameters );
  3369. parameters = parameters || {};
  3370. // color property represents diffuse for MeshPhongMaterial
  3371. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3372. this.ambient = parameters.ambient !== undefined ? new THREE.Color( parameters.ambient ) : new THREE.Color( 0xffffff );
  3373. this.emissive = parameters.emissive !== undefined ? new THREE.Color( parameters.emissive ) : new THREE.Color( 0x000000 );
  3374. this.specular = parameters.specular !== undefined ? new THREE.Color( parameters.specular ) : new THREE.Color( 0x111111 );
  3375. this.shininess = parameters.shininess !== undefined ? parameters.shininess : 30;
  3376. this.metal = parameters.metal !== undefined ? parameters.metal : false;
  3377. this.perPixel = parameters.perPixel !== undefined ? parameters.perPixel : false;
  3378. this.wrapAround = parameters.wrapAround !== undefined ? parameters.wrapAround: false;
  3379. this.wrapRGB = new THREE.Vector3( 1, 1, 1 );
  3380. this.map = parameters.map !== undefined ? parameters.map : null;
  3381. this.lightMap = parameters.lightMap !== undefined ? parameters.lightMap : null;
  3382. this.envMap = parameters.envMap !== undefined ? parameters.envMap : null;
  3383. this.combine = parameters.combine !== undefined ? parameters.combine : THREE.MultiplyOperation;
  3384. this.reflectivity = parameters.reflectivity !== undefined ? parameters.reflectivity : 1;
  3385. this.refractionRatio = parameters.refractionRatio !== undefined ? parameters.refractionRatio : 0.98;
  3386. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3387. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3388. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3389. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3390. this.wireframeLinecap = parameters.wireframeLinecap !== undefined ? parameters.wireframeLinecap : 'round';
  3391. this.wireframeLinejoin = parameters.wireframeLinejoin !== undefined ? parameters.wireframeLinejoin : 'round';
  3392. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors;
  3393. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false;
  3394. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false;
  3395. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false;
  3396. };
  3397. THREE.MeshPhongMaterial.prototype = new THREE.Material();
  3398. THREE.MeshPhongMaterial.prototype.constructor = THREE.MeshPhongMaterial;
  3399. /**
  3400. * @author mr.doob / http://mrdoob.com/
  3401. * @author alteredq / http://alteredqualia.com/
  3402. *
  3403. * parameters = {
  3404. * opacity: <float>,
  3405. * blending: THREE.NormalBlending,
  3406. * depthTest: <bool>,
  3407. * wireframe: <boolean>,
  3408. * wireframeLinewidth: <float>
  3409. * }
  3410. */
  3411. THREE.MeshDepthMaterial = function ( parameters ) {
  3412. THREE.Material.call( this, parameters );
  3413. parameters = parameters || {};
  3414. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading; // doesn't really apply here, normals are not used
  3415. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3416. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3417. };
  3418. THREE.MeshDepthMaterial.prototype = new THREE.Material();
  3419. THREE.MeshDepthMaterial.prototype.constructor = THREE.MeshDepthMaterial;
  3420. /**
  3421. * @author mr.doob / http://mrdoob.com/
  3422. *
  3423. * parameters = {
  3424. * opacity: <float>,
  3425. * shading: THREE.FlatShading,
  3426. * blending: THREE.NormalBlending,
  3427. * depthTest: <bool>,
  3428. * wireframe: <boolean>,
  3429. * wireframeLinewidth: <float>
  3430. * }
  3431. */
  3432. THREE.MeshNormalMaterial = function ( parameters ) {
  3433. THREE.Material.call( this, parameters );
  3434. parameters = parameters || {};
  3435. this.shading = parameters.shading ? parameters.shading : THREE.FlatShading;
  3436. this.wireframe = parameters.wireframe ? parameters.wireframe : false;
  3437. this.wireframeLinewidth = parameters.wireframeLinewidth ? parameters.wireframeLinewidth : 1;
  3438. };
  3439. THREE.MeshNormalMaterial.prototype = new THREE.Material();
  3440. THREE.MeshNormalMaterial.prototype.constructor = THREE.MeshNormalMaterial;
  3441. /**
  3442. * @author mr.doob / http://mrdoob.com/
  3443. */
  3444. THREE.MeshFaceMaterial = function () {
  3445. };
  3446. /**
  3447. * @author mr.doob / http://mrdoob.com/
  3448. * @author alteredq / http://alteredqualia.com/
  3449. *
  3450. * parameters = {
  3451. * color: <hex>,
  3452. * opacity: <float>,
  3453. * map: new THREE.Texture( <Image> ),
  3454. *
  3455. * size: <float>,
  3456. *
  3457. * blending: THREE.NormalBlending,
  3458. * depthTest: <bool>,
  3459. *
  3460. * vertexColors: <bool>,
  3461. *
  3462. * fog: <bool>
  3463. * }
  3464. */
  3465. THREE.ParticleBasicMaterial = function ( parameters ) {
  3466. THREE.Material.call( this, parameters );
  3467. parameters = parameters || {};
  3468. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3469. this.map = parameters.map !== undefined ? parameters.map : null;
  3470. this.size = parameters.size !== undefined ? parameters.size : 1;
  3471. this.sizeAttenuation = parameters.sizeAttenuation !== undefined ? parameters.sizeAttenuation : true;
  3472. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : false;
  3473. this.fog = parameters.fog !== undefined ? parameters.fog : true;
  3474. };
  3475. THREE.ParticleBasicMaterial.prototype = new THREE.Material();
  3476. THREE.ParticleBasicMaterial.prototype.constructor = THREE.ParticleBasicMaterial;
  3477. /**
  3478. * @author mr.doob / http://mrdoob.com/
  3479. *
  3480. * parameters = {
  3481. * color: <hex>,
  3482. * program: <function>,
  3483. * opacity: <float>,
  3484. * blending: THREE.NormalBlending
  3485. * }
  3486. */
  3487. THREE.ParticleCanvasMaterial = function ( parameters ) {
  3488. THREE.Material.call( this, parameters );
  3489. parameters = parameters || {};
  3490. this.color = parameters.color !== undefined ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  3491. this.program = parameters.program !== undefined ? parameters.program : function ( context, color ) {};
  3492. };
  3493. THREE.ParticleCanvasMaterial.prototype = new THREE.Material();
  3494. THREE.ParticleCanvasMaterial.prototype.constructor = THREE.ParticleCanvasMaterial;
  3495. /**
  3496. * @author mr.doob / http://mrdoob.com/
  3497. */
  3498. THREE.ParticleDOMMaterial = function ( domElement ) {
  3499. THREE.Material.call( this );
  3500. this.domElement = domElement;
  3501. };
  3502. /**
  3503. * @author alteredq / http://alteredqualia.com/
  3504. *
  3505. * parameters = {
  3506. * fragmentShader: <string>,
  3507. * vertexShader: <string>,
  3508. *
  3509. * uniforms: { "parameter1": { type: "f", value: 1.0 }, "parameter2": { type: "i" value2: 2 } },
  3510. *
  3511. * shading: THREE.SmoothShading,
  3512. * blending: THREE.NormalBlending,
  3513. * depthTest: <bool>,
  3514. *
  3515. * wireframe: <boolean>,
  3516. * wireframeLinewidth: <float>,
  3517. *
  3518. * lights: <bool>,
  3519. *
  3520. * vertexColors: THREE.NoColors / THREE.VertexColors / THREE.FaceColors,
  3521. *
  3522. * skinning: <bool>,
  3523. * morphTargets: <bool>,
  3524. * morphNormals: <bool>,
  3525. *
  3526. * fog: <bool>
  3527. * }
  3528. */
  3529. THREE.ShaderMaterial = function ( parameters ) {
  3530. THREE.Material.call( this, parameters );
  3531. parameters = parameters || {};
  3532. this.fragmentShader = parameters.fragmentShader !== undefined ? parameters.fragmentShader : "void main() {}";
  3533. this.vertexShader = parameters.vertexShader !== undefined ? parameters.vertexShader : "void main() {}";
  3534. this.uniforms = parameters.uniforms !== undefined ? parameters.uniforms : {};
  3535. this.attributes = parameters.attributes;
  3536. this.shading = parameters.shading !== undefined ? parameters.shading : THREE.SmoothShading;
  3537. this.wireframe = parameters.wireframe !== undefined ? parameters.wireframe : false;
  3538. this.wireframeLinewidth = parameters.wireframeLinewidth !== undefined ? parameters.wireframeLinewidth : 1;
  3539. this.fog = parameters.fog !== undefined ? parameters.fog : false; // set to use scene fog
  3540. this.lights = parameters.lights !== undefined ? parameters.lights : false; // set to use scene lights
  3541. this.vertexColors = parameters.vertexColors !== undefined ? parameters.vertexColors : THREE.NoColors; // set to use "color" attribute stream
  3542. this.skinning = parameters.skinning !== undefined ? parameters.skinning : false; // set to use skinning attribute streams
  3543. this.morphTargets = parameters.morphTargets !== undefined ? parameters.morphTargets : false; // set to use morph targets
  3544. this.morphNormals = parameters.morphNormals !== undefined ? parameters.morphNormals : false; // set to use morph normals
  3545. };
  3546. THREE.ShaderMaterial.prototype = new THREE.Material();
  3547. THREE.ShaderMaterial.prototype.constructor = THREE.ShaderMaterial;
  3548. /**
  3549. * @author mr.doob / http://mrdoob.com/
  3550. * @author alteredq / http://alteredqualia.com/
  3551. * @author szimek / https://github.com/szimek/
  3552. */
  3553. THREE.Texture = function ( image, mapping, wrapS, wrapT, magFilter, minFilter, format, type ) {
  3554. this.id = THREE.TextureCount ++;
  3555. this.image = image;
  3556. this.mapping = mapping !== undefined ? mapping : new THREE.UVMapping();
  3557. this.wrapS = wrapS !== undefined ? wrapS : THREE.ClampToEdgeWrapping;
  3558. this.wrapT = wrapT !== undefined ? wrapT : THREE.ClampToEdgeWrapping;
  3559. this.magFilter = magFilter !== undefined ? magFilter : THREE.LinearFilter;
  3560. this.minFilter = minFilter !== undefined ? minFilter : THREE.LinearMipMapLinearFilter;
  3561. this.format = format !== undefined ? format : THREE.RGBAFormat;
  3562. this.type = type !== undefined ? type : THREE.UnsignedByteType;
  3563. this.offset = new THREE.Vector2( 0, 0 );
  3564. this.repeat = new THREE.Vector2( 1, 1 );
  3565. this.generateMipmaps = true;
  3566. this.premultiplyAlpha = false;
  3567. this.needsUpdate = false;
  3568. this.onUpdate = null;
  3569. };
  3570. THREE.Texture.prototype = {
  3571. constructor: THREE.Texture,
  3572. clone: function () {
  3573. var clonedTexture = new THREE.Texture( this.image, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter, this.format, this.type );
  3574. clonedTexture.offset.copy( this.offset );
  3575. clonedTexture.repeat.copy( this.repeat );
  3576. return clonedTexture;
  3577. }
  3578. };
  3579. THREE.TextureCount = 0;
  3580. THREE.MultiplyOperation = 0;
  3581. THREE.MixOperation = 1;
  3582. // Mapping modes
  3583. THREE.UVMapping = function () {};
  3584. THREE.CubeReflectionMapping = function () {};
  3585. THREE.CubeRefractionMapping = function () {};
  3586. THREE.SphericalReflectionMapping = function () {};
  3587. THREE.SphericalRefractionMapping = function () {};
  3588. // Wrapping modes
  3589. THREE.RepeatWrapping = 0;
  3590. THREE.ClampToEdgeWrapping = 1;
  3591. THREE.MirroredRepeatWrapping = 2;
  3592. // Filters
  3593. THREE.NearestFilter = 3;
  3594. THREE.NearestMipMapNearestFilter = 4;
  3595. THREE.NearestMipMapLinearFilter = 5;
  3596. THREE.LinearFilter = 6;
  3597. THREE.LinearMipMapNearestFilter = 7;
  3598. THREE.LinearMipMapLinearFilter = 8;
  3599. // Types
  3600. THREE.ByteType = 9;
  3601. THREE.UnsignedByteType = 10;
  3602. THREE.ShortType = 11;
  3603. THREE.UnsignedShortType = 12;
  3604. THREE.IntType = 13;
  3605. THREE.UnsignedIntType = 14;
  3606. THREE.FloatType = 15;
  3607. // Formats
  3608. THREE.AlphaFormat = 16;
  3609. THREE.RGBFormat = 17;
  3610. THREE.RGBAFormat = 18;
  3611. THREE.LuminanceFormat = 19;
  3612. THREE.LuminanceAlphaFormat = 20;
  3613. /**
  3614. * @author alteredq / http://alteredqualia.com/
  3615. */
  3616. THREE.DataTexture = function ( data, width, height, format, type, mapping, wrapS, wrapT, magFilter, minFilter ) {
  3617. THREE.Texture.call( this, null, mapping, wrapS, wrapT, magFilter, minFilter, format, type );
  3618. this.image = { data: data, width: width, height: height };
  3619. };
  3620. THREE.DataTexture.prototype = new THREE.Texture();
  3621. THREE.DataTexture.prototype.constructor = THREE.DataTexture;
  3622. THREE.DataTexture.prototype.clone = function () {
  3623. var clonedTexture = new THREE.DataTexture( this.image.data, this.image.width, this.image.height, this.format, this.type, this.mapping, this.wrapS, this.wrapT, this.magFilter, this.minFilter );
  3624. clonedTexture.offset.copy( this.offset );
  3625. clonedTexture.repeat.copy( this.repeat );
  3626. return clonedTexture;
  3627. };
  3628. /**
  3629. * @author mr.doob / http://mrdoob.com/
  3630. */
  3631. THREE.Particle = function ( material ) {
  3632. THREE.Object3D.call( this );
  3633. this.material = material;
  3634. };
  3635. THREE.Particle.prototype = new THREE.Object3D();
  3636. THREE.Particle.prototype.constructor = THREE.Particle;
  3637. /**
  3638. * @author alteredq / http://alteredqualia.com/
  3639. */
  3640. THREE.ParticleSystem = function ( geometry, material ) {
  3641. THREE.Object3D.call( this );
  3642. this.geometry = geometry;
  3643. this.material = ( material !== undefined ) ? material : new THREE.ParticleBasicMaterial( { color: Math.random() * 0xffffff } );
  3644. this.sortParticles = false;
  3645. if ( this.geometry ) {
  3646. // calc bound radius
  3647. if( !this.geometry.boundingSphere ) {
  3648. this.geometry.computeBoundingSphere();
  3649. }
  3650. this.boundRadius = geometry.boundingSphere.radius;
  3651. }
  3652. this.frustumCulled = false;
  3653. };
  3654. THREE.ParticleSystem.prototype = new THREE.Object3D();
  3655. THREE.ParticleSystem.prototype.constructor = THREE.ParticleSystem;
  3656. /**
  3657. * @author mr.doob / http://mrdoob.com/
  3658. */
  3659. THREE.Line = function ( geometry, material, type ) {
  3660. THREE.Object3D.call( this );
  3661. this.geometry = geometry;
  3662. this.material = ( material !== undefined ) ? material : new THREE.LineBasicMaterial( { color: Math.random() * 0xffffff } );
  3663. this.type = ( type !== undefined ) ? type : THREE.LineStrip;
  3664. if ( this.geometry ) {
  3665. if ( ! this.geometry.boundingSphere ) {
  3666. this.geometry.computeBoundingSphere();
  3667. }
  3668. }
  3669. };
  3670. THREE.LineStrip = 0;
  3671. THREE.LinePieces = 1;
  3672. THREE.Line.prototype = new THREE.Object3D();
  3673. THREE.Line.prototype.constructor = THREE.Line;
  3674. /**
  3675. * @author mr.doob / http://mrdoob.com/
  3676. * @author alteredq / http://alteredqualia.com/
  3677. * @author mikael emtinger / http://gomo.se/
  3678. */
  3679. THREE.Mesh = function ( geometry, material ) {
  3680. THREE.Object3D.call( this );
  3681. this.geometry = geometry;
  3682. this.material = ( material !== undefined ) ? material : new THREE.MeshBasicMaterial( { color: Math.random() * 0xffffff, wireframe: true } );
  3683. if ( this.geometry ) {
  3684. // calc bound radius
  3685. if( ! this.geometry.boundingSphere ) {
  3686. this.geometry.computeBoundingSphere();
  3687. }
  3688. this.boundRadius = geometry.boundingSphere.radius;
  3689. // setup morph targets
  3690. if( this.geometry.morphTargets.length ) {
  3691. this.morphTargetBase = -1;
  3692. this.morphTargetForcedOrder = [];
  3693. this.morphTargetInfluences = [];
  3694. this.morphTargetDictionary = {};
  3695. for( var m = 0; m < this.geometry.morphTargets.length; m ++ ) {
  3696. this.morphTargetInfluences.push( 0 );
  3697. this.morphTargetDictionary[ this.geometry.morphTargets[ m ].name ] = m;
  3698. }
  3699. }
  3700. }
  3701. }
  3702. THREE.Mesh.prototype = new THREE.Object3D();
  3703. THREE.Mesh.prototype.constructor = THREE.Mesh;
  3704. THREE.Mesh.prototype.supr = THREE.Object3D.prototype;
  3705. /*
  3706. * Get Morph Target Index by Name
  3707. */
  3708. THREE.Mesh.prototype.getMorphTargetIndexByName = function( name ) {
  3709. if ( this.morphTargetDictionary[ name ] !== undefined ) {
  3710. return this.morphTargetDictionary[ name ];
  3711. }
  3712. console.log( "THREE.Mesh.getMorphTargetIndexByName: morph target " + name + " does not exist. Returning 0." );
  3713. return 0;
  3714. }
  3715. /**
  3716. * @author mikael emtinger / http://gomo.se/
  3717. * @author alteredq / http://alteredqualia.com/
  3718. */
  3719. THREE.Bone = function( belongsToSkin ) {
  3720. THREE.Object3D.call( this );
  3721. this.skin = belongsToSkin;
  3722. this.skinMatrix = new THREE.Matrix4();
  3723. };
  3724. THREE.Bone.prototype = new THREE.Object3D();
  3725. THREE.Bone.prototype.constructor = THREE.Bone;
  3726. THREE.Bone.prototype.supr = THREE.Object3D.prototype;
  3727. THREE.Bone.prototype.update = function( parentSkinMatrix, forceUpdate ) {
  3728. // update local
  3729. if ( this.matrixAutoUpdate ) {
  3730. forceUpdate |= this.updateMatrix();
  3731. }
  3732. // update skin matrix
  3733. if ( forceUpdate || this.matrixWorldNeedsUpdate ) {
  3734. if( parentSkinMatrix ) {
  3735. this.skinMatrix.multiply( parentSkinMatrix, this.matrix );
  3736. } else {
  3737. this.skinMatrix.copy( this.matrix );
  3738. }
  3739. this.matrixWorldNeedsUpdate = false;
  3740. forceUpdate = true;
  3741. }
  3742. // update children
  3743. var child, i, l = this.children.length;
  3744. for ( i = 0; i < l; i ++ ) {
  3745. this.children[ i ].update( this.skinMatrix, forceUpdate );
  3746. }
  3747. };
  3748. /**
  3749. * @author mikael emtinger / http://gomo.se/
  3750. * @author alteredq / http://alteredqualia.com/
  3751. */
  3752. THREE.SkinnedMesh = function ( geometry, material ) {
  3753. THREE.Mesh.call( this, geometry, material );
  3754. // init bones
  3755. this.identityMatrix = new THREE.Matrix4();
  3756. this.bones = [];
  3757. this.boneMatrices = [];
  3758. var b, bone, gbone, p, q, s;
  3759. if ( this.geometry.bones !== undefined ) {
  3760. for ( b = 0; b < this.geometry.bones.length; b ++ ) {
  3761. gbone = this.geometry.bones[ b ];
  3762. p = gbone.pos;
  3763. q = gbone.rotq;
  3764. s = gbone.scl;
  3765. bone = this.addBone();
  3766. bone.name = gbone.name;
  3767. bone.position.set( p[0], p[1], p[2] );
  3768. bone.quaternion.set( q[0], q[1], q[2], q[3] );
  3769. bone.useQuaternion = true;
  3770. if ( s !== undefined ) {
  3771. bone.scale.set( s[0], s[1], s[2] );
  3772. } else {
  3773. bone.scale.set( 1, 1, 1 );
  3774. }
  3775. }
  3776. for ( b = 0; b < this.bones.length; b ++ ) {
  3777. gbone = this.geometry.bones[ b ];
  3778. bone = this.bones[ b ];
  3779. if ( gbone.parent === -1 ) {
  3780. this.add( bone );
  3781. } else {
  3782. this.bones[ gbone.parent ].add( bone );
  3783. }
  3784. }
  3785. this.boneMatrices = new Float32Array( 16 * this.bones.length );
  3786. this.pose();
  3787. }
  3788. };
  3789. THREE.SkinnedMesh.prototype = new THREE.Mesh();
  3790. THREE.SkinnedMesh.prototype.constructor = THREE.SkinnedMesh;
  3791. THREE.SkinnedMesh.prototype.addBone = function( bone ) {
  3792. if ( bone === undefined ) {
  3793. bone = new THREE.Bone( this );
  3794. }
  3795. this.bones.push( bone );
  3796. return bone;
  3797. };
  3798. THREE.SkinnedMesh.prototype.updateMatrixWorld = function ( force ) {
  3799. this.matrixAutoUpdate && this.updateMatrix();
  3800. // update matrixWorld
  3801. if ( this.matrixWorldNeedsUpdate || force ) {
  3802. if ( this.parent ) {
  3803. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  3804. } else {
  3805. this.matrixWorld.copy( this.matrix );
  3806. }
  3807. this.matrixWorldNeedsUpdate = false;
  3808. force = true;
  3809. }
  3810. // update children
  3811. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  3812. var child = this.children[ i ];
  3813. if ( child instanceof THREE.Bone ) {
  3814. child.update( this.identityMatrix, false );
  3815. } else {
  3816. child.updateMatrixWorld( true );
  3817. }
  3818. }
  3819. // flatten bone matrices to array
  3820. var b, bl = this.bones.length,
  3821. ba = this.bones,
  3822. bm = this.boneMatrices;
  3823. for ( b = 0; b < bl; b ++ ) {
  3824. ba[ b ].skinMatrix.flattenToArrayOffset( bm, b * 16 );
  3825. }
  3826. };
  3827. /*
  3828. * Pose
  3829. */
  3830. THREE.SkinnedMesh.prototype.pose = function() {
  3831. this.updateMatrixWorld( true );
  3832. var bim, bone, boneInverses = [];
  3833. for ( var b = 0; b < this.bones.length; b ++ ) {
  3834. bone = this.bones[ b ];
  3835. var inverseMatrix = new THREE.Matrix4();
  3836. inverseMatrix.getInverse( bone.skinMatrix );
  3837. boneInverses.push( inverseMatrix );
  3838. bone.skinMatrix.flattenToArrayOffset( this.boneMatrices, b * 16 );
  3839. }
  3840. // project vertices to local
  3841. if ( this.geometry.skinVerticesA === undefined ) {
  3842. this.geometry.skinVerticesA = [];
  3843. this.geometry.skinVerticesB = [];
  3844. var orgVertex, vertex;
  3845. for ( var i = 0; i < this.geometry.skinIndices.length; i ++ ) {
  3846. orgVertex = this.geometry.vertices[ i ].position;
  3847. var indexA = this.geometry.skinIndices[ i ].x;
  3848. var indexB = this.geometry.skinIndices[ i ].y;
  3849. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  3850. this.geometry.skinVerticesA.push( boneInverses[ indexA ].multiplyVector3( vertex ) );
  3851. vertex = new THREE.Vector3( orgVertex.x, orgVertex.y, orgVertex.z );
  3852. this.geometry.skinVerticesB.push( boneInverses[ indexB ].multiplyVector3( vertex ) );
  3853. // todo: add more influences
  3854. // normalize weights
  3855. if ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y !== 1 ) {
  3856. var len = ( 1.0 - ( this.geometry.skinWeights[ i ].x + this.geometry.skinWeights[ i ].y ) ) * 0.5;
  3857. this.geometry.skinWeights[ i ].x += len;
  3858. this.geometry.skinWeights[ i ].y += len;
  3859. }
  3860. }
  3861. }
  3862. };
  3863. /**
  3864. * @author alteredq / http://alteredqualia.com/
  3865. */
  3866. THREE.MorphAnimMesh = function ( geometry, material ) {
  3867. THREE.Mesh.call( this, geometry, material );
  3868. // API
  3869. this.duration = 1000; // milliseconds
  3870. this.mirroredLoop = false;
  3871. this.time = 0;
  3872. // internals
  3873. this.lastKeyframe = 0;
  3874. this.currentKeyframe = 0;
  3875. this.direction = 1;
  3876. this.directionBackwards = false;
  3877. this.setFrameRange( 0, this.geometry.morphTargets.length - 1 );
  3878. };
  3879. THREE.MorphAnimMesh.prototype = new THREE.Mesh();
  3880. THREE.MorphAnimMesh.prototype.constructor = THREE.MorphAnimMesh;
  3881. THREE.MorphAnimMesh.prototype.setFrameRange = function ( start, end ) {
  3882. this.startKeyframe = start;
  3883. this.endKeyframe = end;
  3884. this.length = this.endKeyframe - this.startKeyframe + 1;
  3885. };
  3886. THREE.MorphAnimMesh.prototype.setDirectionForward = function () {
  3887. this.direction = 1;
  3888. this.directionBackwards = false;
  3889. };
  3890. THREE.MorphAnimMesh.prototype.setDirectionBackward = function () {
  3891. this.direction = -1;
  3892. this.directionBackwards = true;
  3893. };
  3894. THREE.MorphAnimMesh.prototype.parseAnimations = function () {
  3895. var geometry = this.geometry;
  3896. if ( ! geometry.animations ) geometry.animations = {};
  3897. var firstAnimation, animations = geometry.animations;
  3898. var pattern = /([a-z]+)(\d+)/;
  3899. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  3900. var morph = geometry.morphTargets[ i ];
  3901. var parts = morph.name.match( pattern );
  3902. if ( parts && parts.length > 1 ) {
  3903. var label = parts[ 1 ];
  3904. var num = parts[ 2 ];
  3905. if ( ! animations[ label ] ) animations[ label ] = { start: Infinity, end: -Infinity };
  3906. var animation = animations[ label ];
  3907. if ( i < animation.start ) animation.start = i;
  3908. if ( i > animation.end ) animation.end = i;
  3909. if ( ! firstAnimation ) firstAnimation = label;
  3910. }
  3911. }
  3912. geometry.firstAnimation = firstAnimation;
  3913. };
  3914. THREE.MorphAnimMesh.prototype.setAnimationLabel = function ( label, start, end ) {
  3915. if ( ! this.geometry.animations ) this.geometry.animations = {};
  3916. this.geometry.animations[ label ] = { start: start, end: end };
  3917. };
  3918. THREE.MorphAnimMesh.prototype.playAnimation = function ( label, fps ) {
  3919. var animation = this.geometry.animations[ label ];
  3920. if ( animation ) {
  3921. this.setFrameRange( animation.start, animation.end );
  3922. this.duration = 1000 * ( ( animation.end - animation.start ) / fps );
  3923. this.time = 0;
  3924. } else {
  3925. console.warn( "animation[" + label + "] undefined" );
  3926. }
  3927. };
  3928. THREE.MorphAnimMesh.prototype.updateAnimation = function ( delta ) {
  3929. var frameTime = this.duration / this.length;
  3930. this.time += this.direction * delta;
  3931. if ( this.mirroredLoop ) {
  3932. if ( this.time > this.duration || this.time < 0 ) {
  3933. this.direction *= -1;
  3934. if ( this.time > this.duration ) {
  3935. this.time = this.duration;
  3936. this.directionBackwards = true;
  3937. }
  3938. if ( this.time < 0 ) {
  3939. this.time = 0;
  3940. this.directionBackwards = false;
  3941. }
  3942. }
  3943. } else {
  3944. this.time = this.time % this.duration;
  3945. if ( this.time < 0 ) this.time += this.duration;
  3946. }
  3947. var keyframe = this.startKeyframe + THREE.Math.clamp( Math.floor( this.time / frameTime ), 0, this.length - 1 );
  3948. if ( keyframe !== this.currentKeyframe ) {
  3949. this.morphTargetInfluences[ this.lastKeyframe ] = 0;
  3950. this.morphTargetInfluences[ this.currentKeyframe ] = 1;
  3951. this.morphTargetInfluences[ keyframe ] = 0;
  3952. this.lastKeyframe = this.currentKeyframe;
  3953. this.currentKeyframe = keyframe;
  3954. }
  3955. var mix = ( this.time % frameTime ) / frameTime;
  3956. if ( this.directionBackwards ) {
  3957. mix = 1 - mix;
  3958. }
  3959. this.morphTargetInfluences[ this.currentKeyframe ] = mix;
  3960. this.morphTargetInfluences[ this.lastKeyframe ] = 1 - mix;
  3961. };
  3962. /**
  3963. * @author alteredq / http://alteredqualia.com/
  3964. */
  3965. THREE.Ribbon = function ( geometry, material ) {
  3966. THREE.Object3D.call( this );
  3967. this.geometry = geometry;
  3968. this.material = material;
  3969. };
  3970. THREE.Ribbon.prototype = new THREE.Object3D();
  3971. THREE.Ribbon.prototype.constructor = THREE.Ribbon;
  3972. /**
  3973. * @author mikael emtinger / http://gomo.se/
  3974. * @author alteredq / http://alteredqualia.com/
  3975. * @author mr.doob / http://mrdoob.com/
  3976. */
  3977. THREE.LOD = function () {
  3978. THREE.Object3D.call( this );
  3979. this.LODs = [];
  3980. };
  3981. THREE.LOD.prototype = new THREE.Object3D();
  3982. THREE.LOD.prototype.constructor = THREE.LOD;
  3983. THREE.LOD.prototype.supr = THREE.Object3D.prototype;
  3984. THREE.LOD.prototype.addLevel = function ( object3D, visibleAtDistance ) {
  3985. if ( visibleAtDistance === undefined ) {
  3986. visibleAtDistance = 0;
  3987. }
  3988. visibleAtDistance = Math.abs( visibleAtDistance );
  3989. for ( var l = 0; l < this.LODs.length; l ++ ) {
  3990. if ( visibleAtDistance < this.LODs[ l ].visibleAtDistance ) {
  3991. break;
  3992. }
  3993. }
  3994. this.LODs.splice( l, 0, { visibleAtDistance: visibleAtDistance, object3D: object3D } );
  3995. this.add( object3D );
  3996. };
  3997. THREE.LOD.prototype.update = function ( camera ) {
  3998. if ( this.LODs.length > 1 ) {
  3999. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  4000. var inverse = camera.matrixWorldInverse;
  4001. 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] );
  4002. this.LODs[ 0 ].object3D.visible = true;
  4003. for ( var l = 1; l < this.LODs.length; l ++ ) {
  4004. if( distance >= this.LODs[ l ].visibleAtDistance ) {
  4005. this.LODs[ l - 1 ].object3D.visible = false;
  4006. this.LODs[ l ].object3D.visible = true;
  4007. } else {
  4008. break;
  4009. }
  4010. }
  4011. for( ; l < this.LODs.length; l ++ ) {
  4012. this.LODs[ l ].object3D.visible = false;
  4013. }
  4014. }
  4015. };
  4016. /**
  4017. * @author mikael emtinger / http://gomo.se/
  4018. */
  4019. THREE.Sprite = function ( parameters ) {
  4020. THREE.Object3D.call( this );
  4021. this.color = ( parameters.color !== undefined ) ? new THREE.Color( parameters.color ) : new THREE.Color( 0xffffff );
  4022. this.map = ( parameters.map !== undefined ) ? parameters.map : new THREE.Texture();
  4023. this.blending = ( parameters.blending !== undefined ) ? parameters.blending : THREE.NormalBlending;
  4024. this.blendSrc = parameters.blendSrc !== undefined ? parameters.blendSrc : THREE.SrcAlphaFactor;
  4025. this.blendDst = parameters.blendDst !== undefined ? parameters.blendDst : THREE.OneMinusSrcAlphaFactor;
  4026. this.blendEquation = parameters.blendEquation !== undefined ? parameters.blendEquation : THREE.AddEquation;
  4027. this.useScreenCoordinates = ( parameters.useScreenCoordinates !== undefined ) ? parameters.useScreenCoordinates : true;
  4028. this.mergeWith3D = ( parameters.mergeWith3D !== undefined ) ? parameters.mergeWith3D : !this.useScreenCoordinates;
  4029. this.affectedByDistance = ( parameters.affectedByDistance !== undefined ) ? parameters.affectedByDistance : !this.useScreenCoordinates;
  4030. this.scaleByViewport = ( parameters.scaleByViewport !== undefined ) ? parameters.scaleByViewport : !this.affectedByDistance;
  4031. this.alignment = ( parameters.alignment instanceof THREE.Vector2 ) ? parameters.alignment : THREE.SpriteAlignment.center;
  4032. this.rotation3d = this.rotation;
  4033. this.rotation = 0;
  4034. this.opacity = 1;
  4035. this.uvOffset = new THREE.Vector2( 0, 0 );
  4036. this.uvScale = new THREE.Vector2( 1, 1 );
  4037. };
  4038. THREE.Sprite.prototype = new THREE.Object3D();
  4039. THREE.Sprite.prototype.constructor = THREE.Sprite;
  4040. /*
  4041. * Custom update matrix
  4042. */
  4043. THREE.Sprite.prototype.updateMatrix = function () {
  4044. this.matrix.setPosition( this.position );
  4045. this.rotation3d.set( 0, 0, this.rotation );
  4046. this.matrix.setRotationFromEuler( this.rotation3d );
  4047. if ( this.scale.x !== 1 || this.scale.y !== 1 ) {
  4048. this.matrix.scale( this.scale );
  4049. this.boundRadiusScale = Math.max( this.scale.x, this.scale.y );
  4050. }
  4051. this.matrixWorldNeedsUpdate = true;
  4052. };
  4053. /*
  4054. * Alignment
  4055. */
  4056. THREE.SpriteAlignment = {};
  4057. THREE.SpriteAlignment.topLeft = new THREE.Vector2( 1, -1 );
  4058. THREE.SpriteAlignment.topCenter = new THREE.Vector2( 0, -1 );
  4059. THREE.SpriteAlignment.topRight = new THREE.Vector2( -1, -1 );
  4060. THREE.SpriteAlignment.centerLeft = new THREE.Vector2( 1, 0 );
  4061. THREE.SpriteAlignment.center = new THREE.Vector2( 0, 0 );
  4062. THREE.SpriteAlignment.centerRight = new THREE.Vector2( -1, 0 );
  4063. THREE.SpriteAlignment.bottomLeft = new THREE.Vector2( 1, 1 );
  4064. THREE.SpriteAlignment.bottomCenter = new THREE.Vector2( 0, 1 );
  4065. THREE.SpriteAlignment.bottomRight = new THREE.Vector2( -1, 1 );
  4066. /**
  4067. * @author mr.doob / http://mrdoob.com/
  4068. */
  4069. THREE.Scene = function () {
  4070. THREE.Object3D.call( this );
  4071. this.fog = null;
  4072. this.overrideMaterial = null;
  4073. this.matrixAutoUpdate = false;
  4074. this.__objects = [];
  4075. this.__lights = [];
  4076. this.__objectsAdded = [];
  4077. this.__objectsRemoved = [];
  4078. };
  4079. THREE.Scene.prototype = new THREE.Object3D();
  4080. THREE.Scene.prototype.constructor = THREE.Scene;
  4081. THREE.Scene.prototype.__addObject = function ( object ) {
  4082. if ( object instanceof THREE.Light ) {
  4083. if ( this.__lights.indexOf( object ) === - 1 ) {
  4084. this.__lights.push( object );
  4085. }
  4086. } else if ( !( object instanceof THREE.Camera || object instanceof THREE.Bone ) ) {
  4087. if ( this.__objects.indexOf( object ) === - 1 ) {
  4088. this.__objects.push( object );
  4089. this.__objectsAdded.push( object );
  4090. // check if previously removed
  4091. var i = this.__objectsRemoved.indexOf( object );
  4092. if ( i !== -1 ) {
  4093. this.__objectsRemoved.splice( i, 1 );
  4094. }
  4095. }
  4096. }
  4097. for ( var c = 0; c < object.children.length; c ++ ) {
  4098. this.__addObject( object.children[ c ] );
  4099. }
  4100. };
  4101. THREE.Scene.prototype.__removeObject = function ( object ) {
  4102. if ( object instanceof THREE.Light ) {
  4103. var i = this.__lights.indexOf( object );
  4104. if ( i !== -1 ) {
  4105. this.__lights.splice( i, 1 );
  4106. }
  4107. } else if ( !( object instanceof THREE.Camera ) ) {
  4108. var i = this.__objects.indexOf( object );
  4109. if( i !== -1 ) {
  4110. this.__objects.splice( i, 1 );
  4111. this.__objectsRemoved.push( object );
  4112. // check if previously added
  4113. var ai = this.__objectsAdded.indexOf( object );
  4114. if ( ai !== -1 ) {
  4115. this.__objectsAdded.splice( ai, 1 );
  4116. }
  4117. }
  4118. }
  4119. for ( var c = 0; c < object.children.length; c ++ ) {
  4120. this.__removeObject( object.children[ c ] );
  4121. }
  4122. };
  4123. /**
  4124. * @author mr.doob / http://mrdoob.com/
  4125. * @author alteredq / http://alteredqualia.com/
  4126. */
  4127. THREE.Fog = function ( hex, near, far ) {
  4128. this.color = new THREE.Color( hex );
  4129. this.near = ( near !== undefined ) ? near : 1;
  4130. this.far = ( far !== undefined ) ? far : 1000;
  4131. };
  4132. /**
  4133. * @author mr.doob / http://mrdoob.com/
  4134. * @author alteredq / http://alteredqualia.com/
  4135. */
  4136. THREE.FogExp2 = function ( hex, density ) {
  4137. this.color = new THREE.Color( hex );
  4138. this.density = ( density !== undefined ) ? density : 0.00025;
  4139. };
  4140. /**
  4141. * @author mr.doob / http://mrdoob.com/
  4142. */
  4143. THREE.DOMRenderer = function () {
  4144. var _renderData, _elements,
  4145. _width, _height, _widthHalf, _heightHalf, _transformProp,
  4146. _projector = new THREE.Projector();
  4147. var getSupportedProp = function ( proparray ) {
  4148. var root = document.documentElement
  4149. for ( var i = 0; i < proparray.length; i ++ ) {
  4150. if ( typeof root.style[ proparray[ i ] ] === "string" ) {
  4151. return proparray[i];
  4152. }
  4153. }
  4154. return null;
  4155. };
  4156. _transformProp = getSupportedProp( [ 'transform', 'MozTransform', 'WebkitTransform', 'msTransform', 'OTransform' ] );
  4157. this.domElement = document.createElement( 'div' );
  4158. this.setSize = function ( width, height ) {
  4159. _width = width;
  4160. _height = height;
  4161. _widthHalf = _width / 2;
  4162. _heightHalf = _height / 2;
  4163. };
  4164. this.render = function ( scene, camera ) {
  4165. var e, el, m, ml, element, material, dom, v1x, v1y;
  4166. _renderData = _projector.projectScene( scene, camera );
  4167. _elements = _renderData.elements;
  4168. for ( e = 0, el = _elements.length; e < el; e ++ ) {
  4169. element = _elements[ e ];
  4170. if ( element instanceof THREE.RenderableParticle && element.material instanceof THREE.ParticleDOMMaterial ) {
  4171. dom = element.material.domElement;
  4172. v1x = element.x * _widthHalf + _widthHalf - ( dom.offsetWidth >> 1 );
  4173. v1y = element.y * _heightHalf + _heightHalf - ( dom.offsetHeight >> 1 );
  4174. dom.style.left = v1x + 'px';
  4175. dom.style.top = v1y + 'px';
  4176. dom.style.zIndex = Math.abs( Math.floor( ( 1 - element.z ) * camera.far / camera.near ) )
  4177. if ( _transformProp ) {
  4178. var scaleX = element.scale.x * _widthHalf;
  4179. var scaleY = element.scale.y * _heightHalf;
  4180. var scaleVal = "scale(" + scaleX + "," + scaleY + ")";
  4181. dom.style[ _transformProp ] = scaleVal;
  4182. }
  4183. }
  4184. }
  4185. };
  4186. };
  4187. /**
  4188. * @author mr.doob / http://mrdoob.com/
  4189. */
  4190. THREE.CanvasRenderer = function ( parameters ) {
  4191. parameters = parameters || {};
  4192. var _this = this,
  4193. _renderData, _elements, _lights,
  4194. _projector = new THREE.Projector(),
  4195. _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  4196. _canvasWidth, _canvasHeight, _canvasWidthHalf, _canvasHeightHalf,
  4197. _context = _canvas.getContext( '2d' ),
  4198. _clearColor = new THREE.Color( 0x000000 ),
  4199. _clearOpacity = 0,
  4200. _contextGlobalAlpha = 1,
  4201. _contextGlobalCompositeOperation = 0,
  4202. _contextStrokeStyle = null,
  4203. _contextFillStyle = null,
  4204. _contextLineWidth = null,
  4205. _contextLineCap = null,
  4206. _contextLineJoin = null,
  4207. _v1, _v2, _v3, _v4,
  4208. _v5 = new THREE.RenderableVertex(),
  4209. _v6 = new THREE.RenderableVertex(),
  4210. _v1x, _v1y, _v2x, _v2y, _v3x, _v3y,
  4211. _v4x, _v4y, _v5x, _v5y, _v6x, _v6y,
  4212. _color = new THREE.Color(),
  4213. _color1 = new THREE.Color(),
  4214. _color2 = new THREE.Color(),
  4215. _color3 = new THREE.Color(),
  4216. _color4 = new THREE.Color(),
  4217. _patterns = [], _imagedatas = [],
  4218. _near, _far,
  4219. _image, _uvs,
  4220. _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y,
  4221. _clipRect = new THREE.Rectangle(),
  4222. _clearRect = new THREE.Rectangle(),
  4223. _bboxRect = new THREE.Rectangle(),
  4224. _enableLighting = false,
  4225. _ambientLight = new THREE.Color(),
  4226. _directionalLights = new THREE.Color(),
  4227. _pointLights = new THREE.Color(),
  4228. _pi2 = Math.PI * 2,
  4229. _vector3 = new THREE.Vector3(), // Needed for PointLight
  4230. _pixelMap, _pixelMapContext, _pixelMapImage, _pixelMapData,
  4231. _gradientMap, _gradientMapContext, _gradientMapQuality = 16;
  4232. _pixelMap = document.createElement( 'canvas' );
  4233. _pixelMap.width = _pixelMap.height = 2;
  4234. _pixelMapContext = _pixelMap.getContext( '2d' );
  4235. _pixelMapContext.fillStyle = 'rgba(0,0,0,1)';
  4236. _pixelMapContext.fillRect( 0, 0, 2, 2 );
  4237. _pixelMapImage = _pixelMapContext.getImageData( 0, 0, 2, 2 );
  4238. _pixelMapData = _pixelMapImage.data;
  4239. _gradientMap = document.createElement( 'canvas' );
  4240. _gradientMap.width = _gradientMap.height = _gradientMapQuality;
  4241. _gradientMapContext = _gradientMap.getContext( '2d' );
  4242. _gradientMapContext.translate( - _gradientMapQuality / 2, - _gradientMapQuality / 2 );
  4243. _gradientMapContext.scale( _gradientMapQuality, _gradientMapQuality );
  4244. _gradientMapQuality --; // Fix UVs
  4245. this.domElement = _canvas;
  4246. this.autoClear = true;
  4247. this.sortObjects = true;
  4248. this.sortElements = true;
  4249. this.info = {
  4250. render: {
  4251. vertices: 0,
  4252. faces: 0
  4253. }
  4254. }
  4255. this.setSize = function ( width, height ) {
  4256. _canvasWidth = width;
  4257. _canvasHeight = height;
  4258. _canvasWidthHalf = Math.floor( _canvasWidth / 2 );
  4259. _canvasHeightHalf = Math.floor( _canvasHeight / 2 );
  4260. _canvas.width = _canvasWidth;
  4261. _canvas.height = _canvasHeight;
  4262. _clipRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4263. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4264. _contextGlobalAlpha = 1;
  4265. _contextGlobalCompositeOperation = 0;
  4266. _contextStrokeStyle = null;
  4267. _contextFillStyle = null;
  4268. _contextLineWidth = null;
  4269. _contextLineCap = null;
  4270. _contextLineJoin = null;
  4271. };
  4272. this.setClearColor = function ( color, opacity ) {
  4273. _clearColor.copy( color );
  4274. _clearOpacity = opacity !== undefined ? opacity : 1;
  4275. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4276. };
  4277. this.setClearColorHex = function ( hex, opacity ) {
  4278. _clearColor.setHex( hex );
  4279. _clearOpacity = opacity !== undefined ? opacity : 1;
  4280. _clearRect.set( - _canvasWidthHalf, - _canvasHeightHalf, _canvasWidthHalf, _canvasHeightHalf );
  4281. };
  4282. this.clear = function () {
  4283. _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  4284. if ( !_clearRect.isEmpty() ) {
  4285. _clearRect.minSelf( _clipRect );
  4286. _clearRect.inflate( 2 );
  4287. if ( _clearOpacity < 1 ) {
  4288. _context.clearRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  4289. }
  4290. if ( _clearOpacity > 0 ) {
  4291. setBlending( THREE.NormalBlending );
  4292. setOpacity( 1 );
  4293. setFillStyle( 'rgba(' + Math.floor( _clearColor.r * 255 ) + ',' + Math.floor( _clearColor.g * 255 ) + ',' + Math.floor( _clearColor.b * 255 ) + ',' + _clearOpacity + ')' );
  4294. _context.fillRect( Math.floor( _clearRect.getX() ), Math.floor( _clearRect.getY() ), Math.floor( _clearRect.getWidth() ), Math.floor( _clearRect.getHeight() ) );
  4295. }
  4296. _clearRect.empty();
  4297. }
  4298. };
  4299. this.render = function ( scene, camera ) {
  4300. var e, el, element, material;
  4301. this.autoClear ? this.clear() : _context.setTransform( 1, 0, 0, - 1, _canvasWidthHalf, _canvasHeightHalf );
  4302. _this.info.render.vertices = 0;
  4303. _this.info.render.faces = 0;
  4304. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  4305. _elements = _renderData.elements;
  4306. _lights = _renderData.lights;
  4307. /* DEBUG
  4308. _context.fillStyle = 'rgba( 0, 255, 255, 0.5 )';
  4309. _context.fillRect( _clipRect.getX(), _clipRect.getY(), _clipRect.getWidth(), _clipRect.getHeight() );
  4310. */
  4311. _enableLighting = _lights.length > 0;
  4312. if ( _enableLighting ) {
  4313. calculateLights( _lights );
  4314. }
  4315. for ( e = 0, el = _elements.length; e < el; e++ ) {
  4316. element = _elements[ e ];
  4317. material = element.material;
  4318. material = material instanceof THREE.MeshFaceMaterial ? element.faceMaterial : material;
  4319. if ( material == null || material.opacity == 0 ) continue;
  4320. _bboxRect.empty();
  4321. if ( element instanceof THREE.RenderableParticle ) {
  4322. _v1 = element;
  4323. _v1.x *= _canvasWidthHalf; _v1.y *= _canvasHeightHalf;
  4324. renderParticle( _v1, element, material, scene );
  4325. } else if ( element instanceof THREE.RenderableLine ) {
  4326. _v1 = element.v1; _v2 = element.v2;
  4327. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4328. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4329. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4330. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4331. if ( _clipRect.intersects( _bboxRect ) ) {
  4332. renderLine( _v1, _v2, element, material, scene );
  4333. }
  4334. } else if ( element instanceof THREE.RenderableFace3 ) {
  4335. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  4336. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4337. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4338. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  4339. if ( material.overdraw ) {
  4340. expand( _v1.positionScreen, _v2.positionScreen );
  4341. expand( _v2.positionScreen, _v3.positionScreen );
  4342. expand( _v3.positionScreen, _v1.positionScreen );
  4343. }
  4344. _bboxRect.add3Points( _v1.positionScreen.x, _v1.positionScreen.y,
  4345. _v2.positionScreen.x, _v2.positionScreen.y,
  4346. _v3.positionScreen.x, _v3.positionScreen.y );
  4347. if ( _clipRect.intersects( _bboxRect ) ) {
  4348. renderFace3( _v1, _v2, _v3, 0, 1, 2, element, material, scene );
  4349. }
  4350. } else if ( element instanceof THREE.RenderableFace4 ) {
  4351. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  4352. _v1.positionScreen.x *= _canvasWidthHalf; _v1.positionScreen.y *= _canvasHeightHalf;
  4353. _v2.positionScreen.x *= _canvasWidthHalf; _v2.positionScreen.y *= _canvasHeightHalf;
  4354. _v3.positionScreen.x *= _canvasWidthHalf; _v3.positionScreen.y *= _canvasHeightHalf;
  4355. _v4.positionScreen.x *= _canvasWidthHalf; _v4.positionScreen.y *= _canvasHeightHalf;
  4356. _v5.positionScreen.copy( _v2.positionScreen );
  4357. _v6.positionScreen.copy( _v4.positionScreen );
  4358. if ( material.overdraw ) {
  4359. expand( _v1.positionScreen, _v2.positionScreen );
  4360. expand( _v2.positionScreen, _v4.positionScreen );
  4361. expand( _v4.positionScreen, _v1.positionScreen );
  4362. expand( _v3.positionScreen, _v5.positionScreen );
  4363. expand( _v3.positionScreen, _v6.positionScreen );
  4364. }
  4365. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4366. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4367. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4368. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  4369. if ( _clipRect.intersects( _bboxRect ) ) {
  4370. renderFace4( _v1, _v2, _v3, _v4, _v5, _v6, element, material, scene );
  4371. }
  4372. }
  4373. /*
  4374. _context.lineWidth = 1;
  4375. _context.strokeStyle = 'rgba( 0, 255, 0, 0.5 )';
  4376. _context.strokeRect( _bboxRect.getX(), _bboxRect.getY(), _bboxRect.getWidth(), _bboxRect.getHeight() );
  4377. */
  4378. _clearRect.addRectangle( _bboxRect );
  4379. }
  4380. /* DEBUG
  4381. _context.lineWidth = 1;
  4382. _context.strokeStyle = 'rgba( 255, 0, 0, 0.5 )';
  4383. _context.strokeRect( _clearRect.getX(), _clearRect.getY(), _clearRect.getWidth(), _clearRect.getHeight() );
  4384. */
  4385. _context.setTransform( 1, 0, 0, 1, 0, 0 );
  4386. //
  4387. function calculateLights( lights ) {
  4388. var l, ll, light, lightColor;
  4389. _ambientLight.setRGB( 0, 0, 0 );
  4390. _directionalLights.setRGB( 0, 0, 0 );
  4391. _pointLights.setRGB( 0, 0, 0 );
  4392. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  4393. light = lights[ l ];
  4394. lightColor = light.color;
  4395. if ( light instanceof THREE.AmbientLight ) {
  4396. _ambientLight.r += lightColor.r;
  4397. _ambientLight.g += lightColor.g;
  4398. _ambientLight.b += lightColor.b;
  4399. } else if ( light instanceof THREE.DirectionalLight ) {
  4400. // for particles
  4401. _directionalLights.r += lightColor.r;
  4402. _directionalLights.g += lightColor.g;
  4403. _directionalLights.b += lightColor.b;
  4404. } else if ( light instanceof THREE.PointLight ) {
  4405. // for particles
  4406. _pointLights.r += lightColor.r;
  4407. _pointLights.g += lightColor.g;
  4408. _pointLights.b += lightColor.b;
  4409. }
  4410. }
  4411. }
  4412. function calculateLight( lights, position, normal, color ) {
  4413. var l, ll, light, lightColor, lightPosition, amount;
  4414. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  4415. light = lights[ l ];
  4416. lightColor = light.color;
  4417. if ( light instanceof THREE.DirectionalLight ) {
  4418. lightPosition = light.matrixWorld.getPosition();
  4419. amount = normal.dot( lightPosition );
  4420. if ( amount <= 0 ) continue;
  4421. amount *= light.intensity;
  4422. color.r += lightColor.r * amount;
  4423. color.g += lightColor.g * amount;
  4424. color.b += lightColor.b * amount;
  4425. } else if ( light instanceof THREE.PointLight ) {
  4426. lightPosition = light.matrixWorld.getPosition();
  4427. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  4428. if ( amount <= 0 ) continue;
  4429. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  4430. if ( amount == 0 ) continue;
  4431. amount *= light.intensity;
  4432. color.r += lightColor.r * amount;
  4433. color.g += lightColor.g * amount;
  4434. color.b += lightColor.b * amount;
  4435. }
  4436. }
  4437. }
  4438. function renderParticle ( v1, element, material, scene ) {
  4439. setOpacity( material.opacity );
  4440. setBlending( material.blending );
  4441. var width, height, scaleX, scaleY,
  4442. bitmap, bitmapWidth, bitmapHeight;
  4443. if ( material instanceof THREE.ParticleBasicMaterial ) {
  4444. if ( material.map ) {
  4445. bitmap = material.map.image;
  4446. bitmapWidth = bitmap.width >> 1;
  4447. bitmapHeight = bitmap.height >> 1;
  4448. scaleX = element.scale.x * _canvasWidthHalf;
  4449. scaleY = element.scale.y * _canvasHeightHalf;
  4450. width = scaleX * bitmapWidth;
  4451. height = scaleY * bitmapHeight;
  4452. // TODO: Rotations break this...
  4453. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  4454. if ( !_clipRect.intersects( _bboxRect ) ) {
  4455. return;
  4456. }
  4457. _context.save();
  4458. _context.translate( v1.x, v1.y );
  4459. _context.rotate( - element.rotation );
  4460. _context.scale( scaleX, - scaleY );
  4461. _context.translate( - bitmapWidth, - bitmapHeight );
  4462. _context.drawImage( bitmap, 0, 0 );
  4463. _context.restore();
  4464. }
  4465. /* DEBUG
  4466. _context.beginPath();
  4467. _context.moveTo( v1.x - 10, v1.y );
  4468. _context.lineTo( v1.x + 10, v1.y );
  4469. _context.moveTo( v1.x, v1.y - 10 );
  4470. _context.lineTo( v1.x, v1.y + 10 );
  4471. _context.closePath();
  4472. _context.strokeStyle = 'rgb(255,255,0)';
  4473. _context.stroke();
  4474. */
  4475. } else if ( material instanceof THREE.ParticleCanvasMaterial ) {
  4476. width = element.scale.x * _canvasWidthHalf;
  4477. height = element.scale.y * _canvasHeightHalf;
  4478. _bboxRect.set( v1.x - width, v1.y - height, v1.x + width, v1.y + height );
  4479. if ( !_clipRect.intersects( _bboxRect ) ) {
  4480. return;
  4481. }
  4482. setStrokeStyle( material.color.getContextStyle() );
  4483. setFillStyle( material.color.getContextStyle() );
  4484. _context.save();
  4485. _context.translate( v1.x, v1.y );
  4486. _context.rotate( - element.rotation );
  4487. _context.scale( width, height );
  4488. material.program( _context );
  4489. _context.restore();
  4490. }
  4491. }
  4492. function renderLine( v1, v2, element, material, scene ) {
  4493. setOpacity( material.opacity );
  4494. setBlending( material.blending );
  4495. _context.beginPath();
  4496. _context.moveTo( v1.positionScreen.x, v1.positionScreen.y );
  4497. _context.lineTo( v2.positionScreen.x, v2.positionScreen.y );
  4498. _context.closePath();
  4499. if ( material instanceof THREE.LineBasicMaterial ) {
  4500. setLineWidth( material.linewidth );
  4501. setLineCap( material.linecap );
  4502. setLineJoin( material.linejoin );
  4503. setStrokeStyle( material.color.getContextStyle() );
  4504. _context.stroke();
  4505. _bboxRect.inflate( material.linewidth * 2 );
  4506. }
  4507. }
  4508. function renderFace3( v1, v2, v3, uv1, uv2, uv3, element, material, scene ) {
  4509. _this.info.render.vertices += 3;
  4510. _this.info.render.faces ++;
  4511. setOpacity( material.opacity );
  4512. setBlending( material.blending );
  4513. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  4514. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  4515. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  4516. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y );
  4517. if ( material instanceof THREE.MeshBasicMaterial ) {
  4518. if ( material.map/* && !material.wireframe*/ ) {
  4519. if ( material.map.mapping instanceof THREE.UVMapping ) {
  4520. _uvs = element.uvs[ 0 ];
  4521. 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 );
  4522. }
  4523. } else if ( material.envMap ) {
  4524. if ( material.envMap.mapping instanceof THREE.SphericalReflectionMapping ) {
  4525. var cameraMatrix = camera.matrixWorldInverse;
  4526. _vector3.copy( element.vertexNormalsWorld[ uv1 ] );
  4527. _uv1x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4528. _uv1y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4529. _vector3.copy( element.vertexNormalsWorld[ uv2 ] );
  4530. _uv2x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4531. _uv2y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4532. _vector3.copy( element.vertexNormalsWorld[ uv3 ] );
  4533. _uv3x = ( _vector3.x * cameraMatrix.elements[0] + _vector3.y * cameraMatrix.elements[4] + _vector3.z * cameraMatrix.elements[8] ) * 0.5 + 0.5;
  4534. _uv3y = - ( _vector3.x * cameraMatrix.elements[1] + _vector3.y * cameraMatrix.elements[5] + _vector3.z * cameraMatrix.elements[9] ) * 0.5 + 0.5;
  4535. patternPath( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _uv1x, _uv1y, _uv2x, _uv2y, _uv3x, _uv3y, material.envMap );
  4536. }/* else if ( material.envMap.mapping == THREE.SphericalRefractionMapping ) {
  4537. }*/
  4538. } else {
  4539. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4540. }
  4541. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  4542. if ( material.map && !material.wireframe ) {
  4543. if ( material.map.mapping instanceof THREE.UVMapping ) {
  4544. _uvs = element.uvs[ 0 ];
  4545. 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 );
  4546. }
  4547. setBlending( THREE.SubtractiveBlending );
  4548. }
  4549. if ( _enableLighting ) {
  4550. if ( !material.wireframe && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 3 ) {
  4551. _color1.r = _color2.r = _color3.r = _ambientLight.r;
  4552. _color1.g = _color2.g = _color3.g = _ambientLight.g;
  4553. _color1.b = _color2.b = _color3.b = _ambientLight.b;
  4554. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  4555. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  4556. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color3 );
  4557. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  4558. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  4559. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  4560. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  4561. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  4562. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  4563. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  4564. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  4565. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  4566. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  4567. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  4568. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  4569. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4570. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  4571. } else {
  4572. _color.r = _ambientLight.r;
  4573. _color.g = _ambientLight.g;
  4574. _color.b = _ambientLight.b;
  4575. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  4576. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  4577. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  4578. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  4579. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4580. }
  4581. } else {
  4582. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4583. }
  4584. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  4585. _near = camera.near;
  4586. _far = camera.far;
  4587. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  4588. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  4589. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  4590. _color4.r = ( _color2.r + _color3.r ) * 0.5;
  4591. _color4.g = ( _color2.g + _color3.g ) * 0.5;
  4592. _color4.b = ( _color2.b + _color3.b ) * 0.5;
  4593. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4594. clipImage( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, 0, 0, 1, 0, 0, 1, _image );
  4595. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  4596. _color.r = normalToComponent( element.normalWorld.x );
  4597. _color.g = normalToComponent( element.normalWorld.y );
  4598. _color.b = normalToComponent( element.normalWorld.z );
  4599. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4600. }
  4601. }
  4602. function renderFace4( v1, v2, v3, v4, v5, v6, element, material, scene ) {
  4603. _this.info.render.vertices += 4;
  4604. _this.info.render.faces ++;
  4605. setOpacity( material.opacity );
  4606. setBlending( material.blending );
  4607. if ( material.map || material.envMap ) {
  4608. // Let renderFace3() handle this
  4609. renderFace3( v1, v2, v4, 0, 1, 3, element, material, scene );
  4610. renderFace3( v5, v3, v6, 1, 2, 3, element, material, scene );
  4611. return;
  4612. }
  4613. _v1x = v1.positionScreen.x; _v1y = v1.positionScreen.y;
  4614. _v2x = v2.positionScreen.x; _v2y = v2.positionScreen.y;
  4615. _v3x = v3.positionScreen.x; _v3y = v3.positionScreen.y;
  4616. _v4x = v4.positionScreen.x; _v4y = v4.positionScreen.y;
  4617. _v5x = v5.positionScreen.x; _v5y = v5.positionScreen.y;
  4618. _v6x = v6.positionScreen.x; _v6y = v6.positionScreen.y;
  4619. if ( material instanceof THREE.MeshBasicMaterial ) {
  4620. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4621. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4622. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  4623. if ( _enableLighting ) {
  4624. if ( !material.wireframe && material.shading == THREE.SmoothShading && element.vertexNormalsWorld.length == 4 ) {
  4625. _color1.r = _color2.r = _color3.r = _color4.r = _ambientLight.r;
  4626. _color1.g = _color2.g = _color3.g = _color4.g = _ambientLight.g;
  4627. _color1.b = _color2.b = _color3.b = _color4.b = _ambientLight.b;
  4628. calculateLight( _lights, element.v1.positionWorld, element.vertexNormalsWorld[ 0 ], _color1 );
  4629. calculateLight( _lights, element.v2.positionWorld, element.vertexNormalsWorld[ 1 ], _color2 );
  4630. calculateLight( _lights, element.v4.positionWorld, element.vertexNormalsWorld[ 3 ], _color3 );
  4631. calculateLight( _lights, element.v3.positionWorld, element.vertexNormalsWorld[ 2 ], _color4 );
  4632. _color1.r = Math.max( 0, Math.min( material.color.r * _color1.r, 1 ) );
  4633. _color1.g = Math.max( 0, Math.min( material.color.g * _color1.g, 1 ) );
  4634. _color1.b = Math.max( 0, Math.min( material.color.b * _color1.b, 1 ) );
  4635. _color2.r = Math.max( 0, Math.min( material.color.r * _color2.r, 1 ) );
  4636. _color2.g = Math.max( 0, Math.min( material.color.g * _color2.g, 1 ) );
  4637. _color2.b = Math.max( 0, Math.min( material.color.b * _color2.b, 1 ) );
  4638. _color3.r = Math.max( 0, Math.min( material.color.r * _color3.r, 1 ) );
  4639. _color3.g = Math.max( 0, Math.min( material.color.g * _color3.g, 1 ) );
  4640. _color3.b = Math.max( 0, Math.min( material.color.b * _color3.b, 1 ) );
  4641. _color4.r = Math.max( 0, Math.min( material.color.r * _color4.r, 1 ) );
  4642. _color4.g = Math.max( 0, Math.min( material.color.g * _color4.g, 1 ) );
  4643. _color4.b = Math.max( 0, Math.min( material.color.b * _color4.b, 1 ) );
  4644. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4645. // TODO: UVs are incorrect, v4->v3?
  4646. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  4647. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  4648. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  4649. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  4650. } else {
  4651. _color.r = _ambientLight.r;
  4652. _color.g = _ambientLight.g;
  4653. _color.b = _ambientLight.b;
  4654. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  4655. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  4656. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  4657. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  4658. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4659. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4660. }
  4661. } else {
  4662. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4663. material.wireframe ? strokePath( material.color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( material.color );
  4664. }
  4665. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  4666. _color.r = normalToComponent( element.normalWorld.x );
  4667. _color.g = normalToComponent( element.normalWorld.y );
  4668. _color.b = normalToComponent( element.normalWorld.z );
  4669. drawQuad( _v1x, _v1y, _v2x, _v2y, _v3x, _v3y, _v4x, _v4y );
  4670. material.wireframe ? strokePath( _color, material.wireframeLinewidth, material.wireframeLinecap, material.wireframeLinejoin ) : fillPath( _color );
  4671. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  4672. _near = camera.near;
  4673. _far = camera.far;
  4674. _color1.r = _color1.g = _color1.b = 1 - smoothstep( v1.positionScreen.z, _near, _far );
  4675. _color2.r = _color2.g = _color2.b = 1 - smoothstep( v2.positionScreen.z, _near, _far );
  4676. _color3.r = _color3.g = _color3.b = 1 - smoothstep( v4.positionScreen.z, _near, _far );
  4677. _color4.r = _color4.g = _color4.b = 1 - smoothstep( v3.positionScreen.z, _near, _far );
  4678. _image = getGradientTexture( _color1, _color2, _color3, _color4 );
  4679. // TODO: UVs are incorrect, v4->v3?
  4680. drawTriangle( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y );
  4681. clipImage( _v1x, _v1y, _v2x, _v2y, _v4x, _v4y, 0, 0, 1, 0, 0, 1, _image );
  4682. drawTriangle( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y );
  4683. clipImage( _v5x, _v5y, _v3x, _v3y, _v6x, _v6y, 1, 0, 1, 1, 0, 1, _image );
  4684. }
  4685. }
  4686. //
  4687. function drawTriangle( x0, y0, x1, y1, x2, y2 ) {
  4688. _context.beginPath();
  4689. _context.moveTo( x0, y0 );
  4690. _context.lineTo( x1, y1 );
  4691. _context.lineTo( x2, y2 );
  4692. _context.lineTo( x0, y0 );
  4693. _context.closePath();
  4694. }
  4695. function drawQuad( x0, y0, x1, y1, x2, y2, x3, y3 ) {
  4696. _context.beginPath();
  4697. _context.moveTo( x0, y0 );
  4698. _context.lineTo( x1, y1 );
  4699. _context.lineTo( x2, y2 );
  4700. _context.lineTo( x3, y3 );
  4701. _context.lineTo( x0, y0 );
  4702. _context.closePath();
  4703. }
  4704. function strokePath( color, linewidth, linecap, linejoin ) {
  4705. setLineWidth( linewidth );
  4706. setLineCap( linecap );
  4707. setLineJoin( linejoin );
  4708. setStrokeStyle( color.getContextStyle() );
  4709. _context.stroke();
  4710. _bboxRect.inflate( linewidth * 2 );
  4711. }
  4712. function fillPath( color ) {
  4713. setFillStyle( color.getContextStyle() );
  4714. _context.fill();
  4715. }
  4716. function patternPath( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, texture ) {
  4717. if ( texture.image.width == 0 ) return;
  4718. if ( texture.needsUpdate == true || _patterns[ texture.id ] == undefined ) {
  4719. var repeatX = texture.wrapS == THREE.RepeatWrapping;
  4720. var repeatY = texture.wrapT == THREE.RepeatWrapping;
  4721. _patterns[ texture.id ] = _context.createPattern( texture.image, repeatX && repeatY ? 'repeat' : repeatX && !repeatY ? 'repeat-x' : !repeatX && repeatY ? 'repeat-y' : 'no-repeat' );
  4722. texture.needsUpdate = false;
  4723. }
  4724. setFillStyle( _patterns[ texture.id ] );
  4725. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  4726. var a, b, c, d, e, f, det, idet,
  4727. offsetX = texture.offset.x / texture.repeat.x,
  4728. offsetY = texture.offset.y / texture.repeat.y,
  4729. width = texture.image.width * texture.repeat.x,
  4730. height = texture.image.height * texture.repeat.y;
  4731. u0 = ( u0 + offsetX ) * width;
  4732. v0 = ( v0 + offsetY ) * height;
  4733. u1 = ( u1 + offsetX ) * width;
  4734. v1 = ( v1 + offsetY ) * height;
  4735. u2 = ( u2 + offsetX ) * width;
  4736. v2 = ( v2 + offsetY ) * height;
  4737. x1 -= x0; y1 -= y0;
  4738. x2 -= x0; y2 -= y0;
  4739. u1 -= u0; v1 -= v0;
  4740. u2 -= u0; v2 -= v0;
  4741. det = u1 * v2 - u2 * v1;
  4742. if ( det == 0 ) {
  4743. if ( _imagedatas[ texture.id ] === undefined ) {
  4744. var canvas = document.createElement( 'canvas' )
  4745. canvas.width = texture.image.width;
  4746. canvas.height = texture.image.height;
  4747. var context = canvas.getContext( '2d' );
  4748. context.drawImage( texture.image, 0, 0 );
  4749. _imagedatas[ texture.id ] = context.getImageData( 0, 0, texture.image.width, texture.image.height ).data;
  4750. // variables cannot be deleted in ES5 strict mode
  4751. //delete canvas;
  4752. }
  4753. var data = _imagedatas[ texture.id ];
  4754. var index = ( Math.floor( u0 ) + Math.floor( v0 ) * texture.image.width ) * 4;
  4755. _color.setRGB( data[ index ] / 255, data[ index + 1 ] / 255, data[ index + 2 ] / 255 );
  4756. fillPath( _color );
  4757. return;
  4758. }
  4759. idet = 1 / det;
  4760. a = ( v2 * x1 - v1 * x2 ) * idet;
  4761. b = ( v2 * y1 - v1 * y2 ) * idet;
  4762. c = ( u1 * x2 - u2 * x1 ) * idet;
  4763. d = ( u1 * y2 - u2 * y1 ) * idet;
  4764. e = x0 - a * u0 - c * v0;
  4765. f = y0 - b * u0 - d * v0;
  4766. _context.save();
  4767. _context.transform( a, b, c, d, e, f );
  4768. _context.fill();
  4769. _context.restore();
  4770. }
  4771. function clipImage( x0, y0, x1, y1, x2, y2, u0, v0, u1, v1, u2, v2, image ) {
  4772. // http://extremelysatisfactorytotalitarianism.com/blog/?p=2120
  4773. var a, b, c, d, e, f, det, idet,
  4774. width = image.width - 1,
  4775. height = image.height - 1;
  4776. u0 *= width; v0 *= height;
  4777. u1 *= width; v1 *= height;
  4778. u2 *= width; v2 *= height;
  4779. x1 -= x0; y1 -= y0;
  4780. x2 -= x0; y2 -= y0;
  4781. u1 -= u0; v1 -= v0;
  4782. u2 -= u0; v2 -= v0;
  4783. det = u1 * v2 - u2 * v1;
  4784. idet = 1 / det;
  4785. a = ( v2 * x1 - v1 * x2 ) * idet;
  4786. b = ( v2 * y1 - v1 * y2 ) * idet;
  4787. c = ( u1 * x2 - u2 * x1 ) * idet;
  4788. d = ( u1 * y2 - u2 * y1 ) * idet;
  4789. e = x0 - a * u0 - c * v0;
  4790. f = y0 - b * u0 - d * v0;
  4791. _context.save();
  4792. _context.transform( a, b, c, d, e, f );
  4793. _context.clip();
  4794. _context.drawImage( image, 0, 0 );
  4795. _context.restore();
  4796. }
  4797. function getGradientTexture( color1, color2, color3, color4 ) {
  4798. // http://mrdoob.com/blog/post/710
  4799. var c1r = ~~ ( color1.r * 255 ), c1g = ~~ ( color1.g * 255 ), c1b = ~~ ( color1.b * 255 ),
  4800. c2r = ~~ ( color2.r * 255 ), c2g = ~~ ( color2.g * 255 ), c2b = ~~ ( color2.b * 255 ),
  4801. c3r = ~~ ( color3.r * 255 ), c3g = ~~ ( color3.g * 255 ), c3b = ~~ ( color3.b * 255 ),
  4802. c4r = ~~ ( color4.r * 255 ), c4g = ~~ ( color4.g * 255 ), c4b = ~~ ( color4.b * 255 );
  4803. _pixelMapData[ 0 ] = c1r < 0 ? 0 : c1r > 255 ? 255 : c1r;
  4804. _pixelMapData[ 1 ] = c1g < 0 ? 0 : c1g > 255 ? 255 : c1g;
  4805. _pixelMapData[ 2 ] = c1b < 0 ? 0 : c1b > 255 ? 255 : c1b;
  4806. _pixelMapData[ 4 ] = c2r < 0 ? 0 : c2r > 255 ? 255 : c2r;
  4807. _pixelMapData[ 5 ] = c2g < 0 ? 0 : c2g > 255 ? 255 : c2g;
  4808. _pixelMapData[ 6 ] = c2b < 0 ? 0 : c2b > 255 ? 255 : c2b;
  4809. _pixelMapData[ 8 ] = c3r < 0 ? 0 : c3r > 255 ? 255 : c3r;
  4810. _pixelMapData[ 9 ] = c3g < 0 ? 0 : c3g > 255 ? 255 : c3g;
  4811. _pixelMapData[ 10 ] = c3b < 0 ? 0 : c3b > 255 ? 255 : c3b;
  4812. _pixelMapData[ 12 ] = c4r < 0 ? 0 : c4r > 255 ? 255 : c4r;
  4813. _pixelMapData[ 13 ] = c4g < 0 ? 0 : c4g > 255 ? 255 : c4g;
  4814. _pixelMapData[ 14 ] = c4b < 0 ? 0 : c4b > 255 ? 255 : c4b;
  4815. _pixelMapContext.putImageData( _pixelMapImage, 0, 0 );
  4816. _gradientMapContext.drawImage( _pixelMap, 0, 0 );
  4817. return _gradientMap;
  4818. }
  4819. function smoothstep( value, min, max ) {
  4820. var x = ( value - min ) / ( max - min );
  4821. return x * x * ( 3 - 2 * x );
  4822. }
  4823. function normalToComponent( normal ) {
  4824. var component = ( normal + 1 ) * 0.5;
  4825. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  4826. }
  4827. // Hide anti-alias gaps
  4828. function expand( v1, v2 ) {
  4829. var x = v2.x - v1.x, y = v2.y - v1.y,
  4830. det = x * x + y * y, idet;
  4831. if ( det == 0 ) return;
  4832. idet = 1 / Math.sqrt( det );
  4833. x *= idet; y *= idet;
  4834. v2.x += x; v2.y += y;
  4835. v1.x -= x; v1.y -= y;
  4836. }
  4837. };
  4838. // Context cached methods.
  4839. function setOpacity( value ) {
  4840. if ( _contextGlobalAlpha != value ) {
  4841. _context.globalAlpha = _contextGlobalAlpha = value;
  4842. }
  4843. }
  4844. function setBlending( value ) {
  4845. if ( _contextGlobalCompositeOperation != value ) {
  4846. switch ( value ) {
  4847. case THREE.NormalBlending:
  4848. _context.globalCompositeOperation = 'source-over';
  4849. break;
  4850. case THREE.AdditiveBlending:
  4851. _context.globalCompositeOperation = 'lighter';
  4852. break;
  4853. case THREE.SubtractiveBlending:
  4854. _context.globalCompositeOperation = 'darker';
  4855. break;
  4856. }
  4857. _contextGlobalCompositeOperation = value;
  4858. }
  4859. }
  4860. function setLineWidth( value ) {
  4861. if ( _contextLineWidth != value ) {
  4862. _context.lineWidth = _contextLineWidth = value;
  4863. }
  4864. }
  4865. function setLineCap( value ) {
  4866. // "butt", "round", "square"
  4867. if ( _contextLineCap != value ) {
  4868. _context.lineCap = _contextLineCap = value;
  4869. }
  4870. }
  4871. function setLineJoin( value ) {
  4872. // "round", "bevel", "miter"
  4873. if ( _contextLineJoin != value ) {
  4874. _context.lineJoin = _contextLineJoin = value;
  4875. }
  4876. }
  4877. function setStrokeStyle( style ) {
  4878. if ( _contextStrokeStyle != style ) {
  4879. _context.strokeStyle = _contextStrokeStyle = style;
  4880. }
  4881. }
  4882. function setFillStyle( style ) {
  4883. if ( _contextFillStyle != style ) {
  4884. _context.fillStyle = _contextFillStyle = style;
  4885. }
  4886. }
  4887. };
  4888. /**
  4889. * @author mr.doob / http://mrdoob.com/
  4890. */
  4891. THREE.SVGRenderer = function () {
  4892. var _this = this,
  4893. _renderData, _elements, _lights,
  4894. _projector = new THREE.Projector(),
  4895. _svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
  4896. _svgWidth, _svgHeight, _svgWidthHalf, _svgHeightHalf,
  4897. _v1, _v2, _v3, _v4,
  4898. _clipRect = new THREE.Rectangle(),
  4899. _bboxRect = new THREE.Rectangle(),
  4900. _enableLighting = false,
  4901. _color = new THREE.Color(),
  4902. _ambientLight = new THREE.Color(),
  4903. _directionalLights = new THREE.Color(),
  4904. _pointLights = new THREE.Color(),
  4905. _w, // z-buffer to w-buffer
  4906. _vector3 = new THREE.Vector3(), // Needed for PointLight
  4907. _svgPathPool = [], _svgCirclePool = [], _svgLinePool = [],
  4908. _svgNode, _pathCount, _circleCount, _lineCount,
  4909. _quality = 1;
  4910. this.domElement = _svg;
  4911. this.autoClear = true;
  4912. this.sortObjects = true;
  4913. this.sortElements = true;
  4914. this.info = {
  4915. render: {
  4916. vertices: 0,
  4917. faces: 0
  4918. }
  4919. }
  4920. this.setQuality = function( quality ) {
  4921. switch(quality) {
  4922. case "high": _quality = 1; break;
  4923. case "low": _quality = 0; break;
  4924. }
  4925. };
  4926. this.setSize = function( width, height ) {
  4927. _svgWidth = width; _svgHeight = height;
  4928. _svgWidthHalf = _svgWidth / 2; _svgHeightHalf = _svgHeight / 2;
  4929. _svg.setAttribute( 'viewBox', ( - _svgWidthHalf ) + ' ' + ( - _svgHeightHalf ) + ' ' + _svgWidth + ' ' + _svgHeight );
  4930. _svg.setAttribute( 'width', _svgWidth );
  4931. _svg.setAttribute( 'height', _svgHeight );
  4932. _clipRect.set( - _svgWidthHalf, - _svgHeightHalf, _svgWidthHalf, _svgHeightHalf );
  4933. };
  4934. this.clear = function () {
  4935. while ( _svg.childNodes.length > 0 ) {
  4936. _svg.removeChild( _svg.childNodes[ 0 ] );
  4937. }
  4938. };
  4939. this.render = function ( scene, camera ) {
  4940. var e, el, element, material;
  4941. this.autoClear && this.clear();
  4942. _this.info.render.vertices = 0;
  4943. _this.info.render.faces = 0;
  4944. _renderData = _projector.projectScene( scene, camera, this.sortElements );
  4945. _elements = _renderData.elements;
  4946. _lights = _renderData.lights;
  4947. _pathCount = 0; _circleCount = 0; _lineCount = 0;
  4948. _enableLighting = _lights.length > 0;
  4949. if ( _enableLighting ) {
  4950. calculateLights( _lights );
  4951. }
  4952. for ( e = 0, el = _elements.length; e < el; e ++ ) {
  4953. element = _elements[ e ];
  4954. material = element.material;
  4955. material = material instanceof THREE.MeshFaceMaterial ? element.faceMaterial : material;
  4956. if ( material == null || material.opacity == 0 ) continue;
  4957. _bboxRect.empty();
  4958. if ( element instanceof THREE.RenderableParticle ) {
  4959. _v1 = element;
  4960. _v1.x *= _svgWidthHalf; _v1.y *= -_svgHeightHalf;
  4961. renderParticle( _v1, element, material, scene );
  4962. } else if ( element instanceof THREE.RenderableLine ) {
  4963. _v1 = element.v1; _v2 = element.v2;
  4964. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  4965. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  4966. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4967. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4968. if ( !_clipRect.intersects( _bboxRect ) ) {
  4969. continue;
  4970. }
  4971. renderLine( _v1, _v2, element, material, scene );
  4972. } else if ( element instanceof THREE.RenderableFace3 ) {
  4973. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3;
  4974. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= - _svgHeightHalf;
  4975. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= - _svgHeightHalf;
  4976. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= - _svgHeightHalf;
  4977. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4978. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4979. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4980. if ( !_clipRect.intersects( _bboxRect ) ) {
  4981. continue;
  4982. }
  4983. renderFace3( _v1, _v2, _v3, element, material, scene );
  4984. } else if ( element instanceof THREE.RenderableFace4 ) {
  4985. _v1 = element.v1; _v2 = element.v2; _v3 = element.v3; _v4 = element.v4;
  4986. _v1.positionScreen.x *= _svgWidthHalf; _v1.positionScreen.y *= -_svgHeightHalf;
  4987. _v2.positionScreen.x *= _svgWidthHalf; _v2.positionScreen.y *= -_svgHeightHalf;
  4988. _v3.positionScreen.x *= _svgWidthHalf; _v3.positionScreen.y *= -_svgHeightHalf;
  4989. _v4.positionScreen.x *= _svgWidthHalf; _v4.positionScreen.y *= -_svgHeightHalf;
  4990. _bboxRect.addPoint( _v1.positionScreen.x, _v1.positionScreen.y );
  4991. _bboxRect.addPoint( _v2.positionScreen.x, _v2.positionScreen.y );
  4992. _bboxRect.addPoint( _v3.positionScreen.x, _v3.positionScreen.y );
  4993. _bboxRect.addPoint( _v4.positionScreen.x, _v4.positionScreen.y );
  4994. if ( !_clipRect.intersects( _bboxRect) ) {
  4995. continue;
  4996. }
  4997. renderFace4( _v1, _v2, _v3, _v4, element, material, scene );
  4998. }
  4999. }
  5000. };
  5001. function calculateLights( lights ) {
  5002. var l, ll, light, lightColor;
  5003. _ambientLight.setRGB( 0, 0, 0 );
  5004. _directionalLights.setRGB( 0, 0, 0 );
  5005. _pointLights.setRGB( 0, 0, 0 );
  5006. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  5007. light = lights[ l ];
  5008. lightColor = light.color;
  5009. if ( light instanceof THREE.AmbientLight ) {
  5010. _ambientLight.r += lightColor.r;
  5011. _ambientLight.g += lightColor.g;
  5012. _ambientLight.b += lightColor.b;
  5013. } else if ( light instanceof THREE.DirectionalLight ) {
  5014. _directionalLights.r += lightColor.r;
  5015. _directionalLights.g += lightColor.g;
  5016. _directionalLights.b += lightColor.b;
  5017. } else if ( light instanceof THREE.PointLight ) {
  5018. _pointLights.r += lightColor.r;
  5019. _pointLights.g += lightColor.g;
  5020. _pointLights.b += lightColor.b;
  5021. }
  5022. }
  5023. }
  5024. function calculateLight( lights, position, normal, color ) {
  5025. var l, ll, light, lightColor, lightPosition, amount;
  5026. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  5027. light = lights[ l ];
  5028. lightColor = light.color;
  5029. if ( light instanceof THREE.DirectionalLight ) {
  5030. lightPosition = light.matrixWorld.getPosition();
  5031. amount = normal.dot( lightPosition );
  5032. if ( amount <= 0 ) continue;
  5033. amount *= light.intensity;
  5034. color.r += lightColor.r * amount;
  5035. color.g += lightColor.g * amount;
  5036. color.b += lightColor.b * amount;
  5037. } else if ( light instanceof THREE.PointLight ) {
  5038. lightPosition = light.matrixWorld.getPosition();
  5039. amount = normal.dot( _vector3.sub( lightPosition, position ).normalize() );
  5040. if ( amount <= 0 ) continue;
  5041. amount *= light.distance == 0 ? 1 : 1 - Math.min( position.distanceTo( lightPosition ) / light.distance, 1 );
  5042. if ( amount == 0 ) continue;
  5043. amount *= light.intensity;
  5044. color.r += lightColor.r * amount;
  5045. color.g += lightColor.g * amount;
  5046. color.b += lightColor.b * amount;
  5047. }
  5048. }
  5049. }
  5050. function renderParticle( v1, element, material, scene ) {
  5051. /*
  5052. _svgNode = getCircleNode( _circleCount++ );
  5053. _svgNode.setAttribute( 'cx', v1.x );
  5054. _svgNode.setAttribute( 'cy', v1.y );
  5055. _svgNode.setAttribute( 'r', element.scale.x * _svgWidthHalf );
  5056. if ( material instanceof THREE.ParticleCircleMaterial ) {
  5057. if ( _enableLighting ) {
  5058. _color.r = _ambientLight.r + _directionalLights.r + _pointLights.r;
  5059. _color.g = _ambientLight.g + _directionalLights.g + _pointLights.g;
  5060. _color.b = _ambientLight.b + _directionalLights.b + _pointLights.b;
  5061. _color.r = material.color.r * _color.r;
  5062. _color.g = material.color.g * _color.g;
  5063. _color.b = material.color.b * _color.b;
  5064. _color.updateStyleString();
  5065. } else {
  5066. _color = material.color;
  5067. }
  5068. _svgNode.setAttribute( 'style', 'fill: ' + _color.__styleString );
  5069. }
  5070. _svg.appendChild( _svgNode );
  5071. */
  5072. }
  5073. function renderLine ( v1, v2, element, material, scene ) {
  5074. _svgNode = getLineNode( _lineCount ++ );
  5075. _svgNode.setAttribute( 'x1', v1.positionScreen.x );
  5076. _svgNode.setAttribute( 'y1', v1.positionScreen.y );
  5077. _svgNode.setAttribute( 'x2', v2.positionScreen.x );
  5078. _svgNode.setAttribute( 'y2', v2.positionScreen.y );
  5079. if ( material instanceof THREE.LineBasicMaterial ) {
  5080. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + material.color.getContextStyle() + '; stroke-width: ' + material.linewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.linecap + '; stroke-linejoin: ' + material.linejoin );
  5081. _svg.appendChild( _svgNode );
  5082. }
  5083. }
  5084. function renderFace3( v1, v2, v3, element, material, scene ) {
  5085. _this.info.render.vertices += 3;
  5086. _this.info.render.faces ++;
  5087. _svgNode = getPathNode( _pathCount ++ );
  5088. _svgNode.setAttribute( 'd', 'M ' + v1.positionScreen.x + ' ' + v1.positionScreen.y + ' L ' + v2.positionScreen.x + ' ' + v2.positionScreen.y + ' L ' + v3.positionScreen.x + ',' + v3.positionScreen.y + 'z' );
  5089. if ( material instanceof THREE.MeshBasicMaterial ) {
  5090. _color.copy( material.color );
  5091. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  5092. if ( _enableLighting ) {
  5093. _color.r = _ambientLight.r;
  5094. _color.g = _ambientLight.g;
  5095. _color.b = _ambientLight.b;
  5096. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  5097. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  5098. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  5099. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  5100. } else {
  5101. _color.copy( material.color );
  5102. }
  5103. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  5104. _w = 1 - ( material.__2near / (material.__farPlusNear - element.z * material.__farMinusNear) );
  5105. _color.setRGB( _w, _w, _w );
  5106. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  5107. _color.setRGB( normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) );
  5108. }
  5109. if ( material.wireframe ) {
  5110. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + _color.getContextStyle() + '; stroke-width: ' + material.wireframeLinewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.wireframeLinecap + '; stroke-linejoin: ' + material.wireframeLinejoin );
  5111. } else {
  5112. _svgNode.setAttribute( 'style', 'fill: ' + _color.getContextStyle() + '; fill-opacity: ' + material.opacity );
  5113. }
  5114. _svg.appendChild( _svgNode );
  5115. }
  5116. function renderFace4( v1, v2, v3, v4, element, material, scene ) {
  5117. _this.info.render.vertices += 4;
  5118. _this.info.render.faces ++;
  5119. _svgNode = getPathNode( _pathCount ++ );
  5120. _svgNode.setAttribute( 'd', 'M ' + v1.positionScreen.x + ' ' + v1.positionScreen.y + ' L ' + v2.positionScreen.x + ' ' + v2.positionScreen.y + ' L ' + v3.positionScreen.x + ',' + v3.positionScreen.y + ' L ' + v4.positionScreen.x + ',' + v4.positionScreen.y + 'z' );
  5121. if ( material instanceof THREE.MeshBasicMaterial ) {
  5122. _color.copy( material.color );
  5123. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  5124. if ( _enableLighting ) {
  5125. _color.r = _ambientLight.r;
  5126. _color.g = _ambientLight.g;
  5127. _color.b = _ambientLight.b;
  5128. calculateLight( _lights, element.centroidWorld, element.normalWorld, _color );
  5129. _color.r = Math.max( 0, Math.min( material.color.r * _color.r, 1 ) );
  5130. _color.g = Math.max( 0, Math.min( material.color.g * _color.g, 1 ) );
  5131. _color.b = Math.max( 0, Math.min( material.color.b * _color.b, 1 ) );
  5132. } else {
  5133. _color.copy( material.color );
  5134. }
  5135. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  5136. _w = 1 - ( material.__2near / (material.__farPlusNear - element.z * material.__farMinusNear) );
  5137. _color.setRGB( _w, _w, _w );
  5138. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  5139. _color.setRGB( normalToComponent( element.normalWorld.x ), normalToComponent( element.normalWorld.y ), normalToComponent( element.normalWorld.z ) );
  5140. }
  5141. if ( material.wireframe ) {
  5142. _svgNode.setAttribute( 'style', 'fill: none; stroke: ' + _color.getContextStyle() + '; stroke-width: ' + material.wireframeLinewidth + '; stroke-opacity: ' + material.opacity + '; stroke-linecap: ' + material.wireframeLinecap + '; stroke-linejoin: ' + material.wireframeLinejoin );
  5143. } else {
  5144. _svgNode.setAttribute( 'style', 'fill: ' + _color.getContextStyle() + '; fill-opacity: ' + material.opacity );
  5145. }
  5146. _svg.appendChild( _svgNode );
  5147. }
  5148. function getLineNode( id ) {
  5149. if ( _svgLinePool[ id ] == null ) {
  5150. _svgLinePool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'line' );
  5151. if ( _quality == 0 ) {
  5152. _svgLinePool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5153. }
  5154. return _svgLinePool[ id ];
  5155. }
  5156. return _svgLinePool[ id ];
  5157. }
  5158. function getPathNode( id ) {
  5159. if ( _svgPathPool[ id ] == null ) {
  5160. _svgPathPool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'path' );
  5161. if ( _quality == 0 ) {
  5162. _svgPathPool[ id ].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5163. }
  5164. return _svgPathPool[ id ];
  5165. }
  5166. return _svgPathPool[ id ];
  5167. }
  5168. function getCircleNode( id ) {
  5169. if ( _svgCirclePool[id] == null ) {
  5170. _svgCirclePool[ id ] = document.createElementNS( 'http://www.w3.org/2000/svg', 'circle' );
  5171. if ( _quality == 0 ) {
  5172. _svgCirclePool[id].setAttribute( 'shape-rendering', 'crispEdges' ); //optimizeSpeed
  5173. }
  5174. return _svgCirclePool[ id ];
  5175. }
  5176. return _svgCirclePool[ id ];
  5177. }
  5178. function normalToComponent( normal ) {
  5179. var component = ( normal + 1 ) * 0.5;
  5180. return component < 0 ? 0 : ( component > 1 ? 1 : component );
  5181. }
  5182. function pad( str ) {
  5183. while ( str.length < 6 ) str = '0' + str;
  5184. return str;
  5185. }
  5186. };
  5187. /**
  5188. * @author alteredq / http://alteredqualia.com/
  5189. * @author mrdoob / http://mrdoob.com/
  5190. * @author mikael emtinger / http://gomo.se/
  5191. */
  5192. THREE.ShaderChunk = {
  5193. // FOG
  5194. fog_pars_fragment: [
  5195. "#ifdef USE_FOG",
  5196. "uniform vec3 fogColor;",
  5197. "#ifdef FOG_EXP2",
  5198. "uniform float fogDensity;",
  5199. "#else",
  5200. "uniform float fogNear;",
  5201. "uniform float fogFar;",
  5202. "#endif",
  5203. "#endif"
  5204. ].join("\n"),
  5205. fog_fragment: [
  5206. "#ifdef USE_FOG",
  5207. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  5208. "#ifdef FOG_EXP2",
  5209. "const float LOG2 = 1.442695;",
  5210. "float fogFactor = exp2( - fogDensity * fogDensity * depth * depth * LOG2 );",
  5211. "fogFactor = 1.0 - clamp( fogFactor, 0.0, 1.0 );",
  5212. "#else",
  5213. "float fogFactor = smoothstep( fogNear, fogFar, depth );",
  5214. "#endif",
  5215. "gl_FragColor = mix( gl_FragColor, vec4( fogColor, gl_FragColor.w ), fogFactor );",
  5216. "#endif"
  5217. ].join("\n"),
  5218. // ENVIRONMENT MAP
  5219. envmap_pars_fragment: [
  5220. "#ifdef USE_ENVMAP",
  5221. "varying vec3 vReflect;",
  5222. "uniform float reflectivity;",
  5223. "uniform samplerCube envMap;",
  5224. "uniform float flipEnvMap;",
  5225. "uniform int combine;",
  5226. "#endif"
  5227. ].join("\n"),
  5228. envmap_fragment: [
  5229. "#ifdef USE_ENVMAP",
  5230. "#ifdef DOUBLE_SIDED",
  5231. "float flipNormal = ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  5232. "vec4 cubeColor = textureCube( envMap, flipNormal * vec3( flipEnvMap * vReflect.x, vReflect.yz ) );",
  5233. "#else",
  5234. "vec4 cubeColor = textureCube( envMap, vec3( flipEnvMap * vReflect.x, vReflect.yz ) );",
  5235. "#endif",
  5236. "#ifdef GAMMA_INPUT",
  5237. "cubeColor.xyz *= cubeColor.xyz;",
  5238. "#endif",
  5239. "if ( combine == 1 ) {",
  5240. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, reflectivity );",
  5241. "} else {",
  5242. "gl_FragColor.xyz = gl_FragColor.xyz * cubeColor.xyz;",
  5243. "}",
  5244. "#endif"
  5245. ].join("\n"),
  5246. envmap_pars_vertex: [
  5247. "#ifdef USE_ENVMAP",
  5248. "varying vec3 vReflect;",
  5249. "uniform float refractionRatio;",
  5250. "uniform bool useRefract;",
  5251. "#endif"
  5252. ].join("\n"),
  5253. envmap_vertex : [
  5254. "#ifdef USE_ENVMAP",
  5255. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  5256. "vec3 nWorld = mat3( objectMatrix[ 0 ].xyz, objectMatrix[ 1 ].xyz, objectMatrix[ 2 ].xyz ) * normal;",
  5257. "if ( useRefract ) {",
  5258. "vReflect = refract( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ), refractionRatio );",
  5259. "} else {",
  5260. "vReflect = reflect( normalize( mPosition.xyz - cameraPosition ), normalize( nWorld.xyz ) );",
  5261. "}",
  5262. "#endif"
  5263. ].join("\n"),
  5264. // COLOR MAP (particles)
  5265. map_particle_pars_fragment: [
  5266. "#ifdef USE_MAP",
  5267. "uniform sampler2D map;",
  5268. "#endif"
  5269. ].join("\n"),
  5270. map_particle_fragment: [
  5271. "#ifdef USE_MAP",
  5272. "gl_FragColor = gl_FragColor * texture2D( map, gl_PointCoord );",
  5273. "#endif"
  5274. ].join("\n"),
  5275. // COLOR MAP (triangles)
  5276. map_pars_vertex: [
  5277. "#ifdef USE_MAP",
  5278. "varying vec2 vUv;",
  5279. "uniform vec4 offsetRepeat;",
  5280. "#endif"
  5281. ].join("\n"),
  5282. map_pars_fragment: [
  5283. "#ifdef USE_MAP",
  5284. "varying vec2 vUv;",
  5285. "uniform sampler2D map;",
  5286. "#endif"
  5287. ].join("\n"),
  5288. map_vertex: [
  5289. "#ifdef USE_MAP",
  5290. "vUv = uv * offsetRepeat.zw + offsetRepeat.xy;",
  5291. "#endif"
  5292. ].join("\n"),
  5293. map_fragment: [
  5294. "#ifdef USE_MAP",
  5295. "#ifdef GAMMA_INPUT",
  5296. "vec4 texelColor = texture2D( map, vUv );",
  5297. "texelColor.xyz *= texelColor.xyz;",
  5298. "gl_FragColor = gl_FragColor * texelColor;",
  5299. "#else",
  5300. "gl_FragColor = gl_FragColor * texture2D( map, vUv );",
  5301. "#endif",
  5302. "#endif"
  5303. ].join("\n"),
  5304. // LIGHT MAP
  5305. lightmap_pars_fragment: [
  5306. "#ifdef USE_LIGHTMAP",
  5307. "varying vec2 vUv2;",
  5308. "uniform sampler2D lightMap;",
  5309. "#endif"
  5310. ].join("\n"),
  5311. lightmap_pars_vertex: [
  5312. "#ifdef USE_LIGHTMAP",
  5313. "varying vec2 vUv2;",
  5314. "#endif"
  5315. ].join("\n"),
  5316. lightmap_fragment: [
  5317. "#ifdef USE_LIGHTMAP",
  5318. "gl_FragColor = gl_FragColor * texture2D( lightMap, vUv2 );",
  5319. "#endif"
  5320. ].join("\n"),
  5321. lightmap_vertex: [
  5322. "#ifdef USE_LIGHTMAP",
  5323. "vUv2 = uv2;",
  5324. "#endif"
  5325. ].join("\n"),
  5326. // LIGHTS LAMBERT
  5327. lights_lambert_pars_vertex: [
  5328. "uniform vec3 ambient;",
  5329. "uniform vec3 diffuse;",
  5330. "uniform vec3 emissive;",
  5331. "uniform vec3 ambientLightColor;",
  5332. "#if MAX_DIR_LIGHTS > 0",
  5333. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  5334. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  5335. "#endif",
  5336. "#if MAX_POINT_LIGHTS > 0",
  5337. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  5338. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5339. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5340. "#endif",
  5341. "#ifdef WRAP_AROUND",
  5342. "uniform vec3 wrapRGB;",
  5343. "#endif",
  5344. ].join("\n"),
  5345. lights_lambert_vertex: [
  5346. "vLightFront = vec3( 0.0 );",
  5347. "#ifdef DOUBLE_SIDED",
  5348. "vLightBack = vec3( 0.0 );",
  5349. "#endif",
  5350. "transformedNormal = normalize( transformedNormal );",
  5351. "#if MAX_DIR_LIGHTS > 0",
  5352. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  5353. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  5354. "vec3 dirVector = normalize( lDirection.xyz );",
  5355. "float dotProduct = dot( transformedNormal, dirVector );",
  5356. "vec3 directionalLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  5357. "#ifdef DOUBLE_SIDED",
  5358. "vec3 directionalLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  5359. "#ifdef WRAP_AROUND",
  5360. "vec3 directionalLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  5361. "#endif",
  5362. "#endif",
  5363. "#ifdef WRAP_AROUND",
  5364. "vec3 directionalLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  5365. "directionalLightWeighting = mix( directionalLightWeighting, directionalLightWeightingHalf, wrapRGB );",
  5366. "#ifdef DOUBLE_SIDED",
  5367. "directionalLightWeightingBack = mix( directionalLightWeightingBack, directionalLightWeightingHalfBack, wrapRGB );",
  5368. "#endif",
  5369. "#endif",
  5370. "vLightFront += directionalLightColor[ i ] * directionalLightWeighting;",
  5371. "#ifdef DOUBLE_SIDED",
  5372. "vLightBack += directionalLightColor[ i ] * directionalLightWeightingBack;",
  5373. "#endif",
  5374. "}",
  5375. "#endif",
  5376. "#if MAX_POINT_LIGHTS > 0",
  5377. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5378. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5379. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  5380. "float lDistance = 1.0;",
  5381. "if ( pointLightDistance[ i ] > 0.0 )",
  5382. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5383. "lVector = normalize( lVector );",
  5384. "float dotProduct = dot( transformedNormal, lVector );",
  5385. "vec3 pointLightWeighting = vec3( max( dotProduct, 0.0 ) );",
  5386. "#ifdef DOUBLE_SIDED",
  5387. "vec3 pointLightWeightingBack = vec3( max( -dotProduct, 0.0 ) );",
  5388. "#ifdef WRAP_AROUND",
  5389. "vec3 pointLightWeightingHalfBack = vec3( max( -0.5 * dotProduct + 0.5, 0.0 ) );",
  5390. "#endif",
  5391. "#endif",
  5392. "#ifdef WRAP_AROUND",
  5393. "vec3 pointLightWeightingHalf = vec3( max( 0.5 * dotProduct + 0.5, 0.0 ) );",
  5394. "pointLightWeighting = mix( pointLightWeighting, pointLightWeightingHalf, wrapRGB );",
  5395. "#ifdef DOUBLE_SIDED",
  5396. "pointLightWeightingBack = mix( pointLightWeightingBack, pointLightWeightingHalfBack, wrapRGB );",
  5397. "#endif",
  5398. "#endif",
  5399. "vLightFront += pointLightColor[ i ] * pointLightWeighting * lDistance;",
  5400. "#ifdef DOUBLE_SIDED",
  5401. "vLightBack += pointLightColor[ i ] * pointLightWeightingBack * lDistance;",
  5402. "#endif",
  5403. "}",
  5404. "#endif",
  5405. "vLightFront = vLightFront * diffuse + ambient * ambientLightColor + emissive;",
  5406. "#ifdef DOUBLE_SIDED",
  5407. "vLightBack = vLightBack * diffuse + ambient * ambientLightColor + emissive;",
  5408. "#endif",
  5409. ].join("\n"),
  5410. // LIGHTS PHONG
  5411. lights_phong_pars_vertex: [
  5412. "#if MAX_POINT_LIGHTS > 0",
  5413. "#ifndef PHONG_PER_PIXEL",
  5414. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5415. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5416. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  5417. "#endif",
  5418. "#endif"
  5419. ].join("\n"),
  5420. lights_phong_vertex: [
  5421. "#if MAX_POINT_LIGHTS > 0",
  5422. "#ifndef PHONG_PER_PIXEL",
  5423. "for( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5424. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5425. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  5426. "float lDistance = 1.0;",
  5427. "if ( pointLightDistance[ i ] > 0.0 )",
  5428. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5429. "vPointLight[ i ] = vec4( lVector, lDistance );",
  5430. "}",
  5431. "#endif",
  5432. "#endif"
  5433. ].join("\n"),
  5434. lights_phong_pars_fragment: [
  5435. "uniform vec3 ambientLightColor;",
  5436. "#if MAX_DIR_LIGHTS > 0",
  5437. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  5438. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  5439. "#endif",
  5440. "#if MAX_POINT_LIGHTS > 0",
  5441. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  5442. "#ifdef PHONG_PER_PIXEL",
  5443. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  5444. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  5445. "#else",
  5446. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  5447. "#endif",
  5448. "#endif",
  5449. "#ifdef WRAP_AROUND",
  5450. "uniform vec3 wrapRGB;",
  5451. "#endif",
  5452. "varying vec3 vViewPosition;",
  5453. "varying vec3 vNormal;"
  5454. ].join("\n"),
  5455. lights_phong_fragment: [
  5456. "vec3 normal = normalize( vNormal );",
  5457. "vec3 viewPosition = normalize( vViewPosition );",
  5458. "#ifdef DOUBLE_SIDED",
  5459. "normal = normal * ( -1.0 + 2.0 * float( gl_FrontFacing ) );",
  5460. "#endif",
  5461. "#if MAX_POINT_LIGHTS > 0",
  5462. "vec3 pointDiffuse = vec3( 0.0 );",
  5463. "vec3 pointSpecular = vec3( 0.0 );",
  5464. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  5465. "#ifdef PHONG_PER_PIXEL",
  5466. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  5467. "vec3 lVector = lPosition.xyz + vViewPosition.xyz;",
  5468. "float lDistance = 1.0;",
  5469. "if ( pointLightDistance[ i ] > 0.0 )",
  5470. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  5471. "lVector = normalize( lVector );",
  5472. "#else",
  5473. "vec3 lVector = normalize( vPointLight[ i ].xyz );",
  5474. "float lDistance = vPointLight[ i ].w;",
  5475. "#endif",
  5476. // diffuse
  5477. "float dotProduct = dot( normal, lVector );",
  5478. "#ifdef WRAP_AROUND",
  5479. "float pointDiffuseWeightFull = max( dotProduct, 0.0 );",
  5480. "float pointDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  5481. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  5482. "#else",
  5483. "float pointDiffuseWeight = max( dotProduct, 0.0 );",
  5484. "#endif",
  5485. "pointDiffuse += diffuse * pointLightColor[ i ] * pointDiffuseWeight * lDistance;",
  5486. // specular
  5487. "vec3 pointHalfVector = normalize( lVector + viewPosition );",
  5488. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  5489. "float pointSpecularWeight = max( pow( pointDotNormalHalf, shininess ), 0.0 );",
  5490. "#ifdef PHYSICALLY_BASED_SHADING",
  5491. // 2.0 => 2.0001 is hack to work around ANGLE bug
  5492. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  5493. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( lVector, pointHalfVector ), 5.0 );",
  5494. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance * specularNormalization;",
  5495. "#else",
  5496. "pointSpecular += specular * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * lDistance;",
  5497. "#endif",
  5498. "}",
  5499. "#endif",
  5500. "#if MAX_DIR_LIGHTS > 0",
  5501. "vec3 dirDiffuse = vec3( 0.0 );",
  5502. "vec3 dirSpecular = vec3( 0.0 );" ,
  5503. "for( int i = 0; i < MAX_DIR_LIGHTS; i ++ ) {",
  5504. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  5505. "vec3 dirVector = normalize( lDirection.xyz );",
  5506. // diffuse
  5507. "float dotProduct = dot( normal, dirVector );",
  5508. "#ifdef WRAP_AROUND",
  5509. "float dirDiffuseWeightFull = max( dotProduct, 0.0 );",
  5510. "float dirDiffuseWeightHalf = max( 0.5 * dotProduct + 0.5, 0.0 );",
  5511. "vec3 dirDiffuseWeight = mix( vec3( dirDiffuseWeightFull ), vec3( dirDiffuseWeightHalf ), wrapRGB );",
  5512. "#else",
  5513. "float dirDiffuseWeight = max( dotProduct, 0.0 );",
  5514. "#endif",
  5515. "dirDiffuse += diffuse * directionalLightColor[ i ] * dirDiffuseWeight;",
  5516. // specular
  5517. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  5518. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  5519. "float dirSpecularWeight = max( pow( dirDotNormalHalf, shininess ), 0.0 );",
  5520. "#ifdef PHYSICALLY_BASED_SHADING",
  5521. /*
  5522. // fresnel term from skin shader
  5523. "const float F0 = 0.128;",
  5524. "float base = 1.0 - dot( viewPosition, dirHalfVector );",
  5525. "float exponential = pow( base, 5.0 );",
  5526. "float fresnel = exponential + F0 * ( 1.0 - exponential );",
  5527. */
  5528. /*
  5529. // fresnel term from fresnel shader
  5530. "const float mFresnelBias = 0.08;",
  5531. "const float mFresnelScale = 0.3;",
  5532. "const float mFresnelPower = 5.0;",
  5533. "float fresnel = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( -viewPosition ), normal ), mFresnelPower );",
  5534. */
  5535. // 2.0 => 2.0001 is hack to work around ANGLE bug
  5536. "float specularNormalization = ( shininess + 2.0001 ) / 8.0;",
  5537. //"dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization * fresnel;",
  5538. "vec3 schlick = specular + vec3( 1.0 - specular ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  5539. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  5540. "#else",
  5541. "dirSpecular += specular * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight;",
  5542. "#endif",
  5543. "}",
  5544. "#endif",
  5545. "vec3 totalDiffuse = vec3( 0.0 );",
  5546. "vec3 totalSpecular = vec3( 0.0 );",
  5547. "#if MAX_DIR_LIGHTS > 0",
  5548. "totalDiffuse += dirDiffuse;",
  5549. "totalSpecular += dirSpecular;",
  5550. "#endif",
  5551. "#if MAX_POINT_LIGHTS > 0",
  5552. "totalDiffuse += pointDiffuse;",
  5553. "totalSpecular += pointSpecular;",
  5554. "#endif",
  5555. "#ifdef METAL",
  5556. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient + totalSpecular );",
  5557. "#else",
  5558. "gl_FragColor.xyz = gl_FragColor.xyz * ( emissive + totalDiffuse + ambientLightColor * ambient ) + totalSpecular;",
  5559. "#endif"
  5560. ].join("\n"),
  5561. // VERTEX COLORS
  5562. color_pars_fragment: [
  5563. "#ifdef USE_COLOR",
  5564. "varying vec3 vColor;",
  5565. "#endif"
  5566. ].join("\n"),
  5567. color_fragment: [
  5568. "#ifdef USE_COLOR",
  5569. "gl_FragColor = gl_FragColor * vec4( vColor, opacity );",
  5570. "#endif"
  5571. ].join("\n"),
  5572. color_pars_vertex: [
  5573. "#ifdef USE_COLOR",
  5574. "varying vec3 vColor;",
  5575. "#endif"
  5576. ].join("\n"),
  5577. color_vertex: [
  5578. "#ifdef USE_COLOR",
  5579. "#ifdef GAMMA_INPUT",
  5580. "vColor = color * color;",
  5581. "#else",
  5582. "vColor = color;",
  5583. "#endif",
  5584. "#endif"
  5585. ].join("\n"),
  5586. // SKINNING
  5587. skinning_pars_vertex: [
  5588. "#ifdef USE_SKINNING",
  5589. "uniform mat4 boneGlobalMatrices[ MAX_BONES ];",
  5590. "#endif"
  5591. ].join("\n"),
  5592. skinning_vertex: [
  5593. "#ifdef USE_SKINNING",
  5594. "gl_Position = ( boneGlobalMatrices[ int( skinIndex.x ) ] * skinVertexA ) * skinWeight.x;",
  5595. "gl_Position += ( boneGlobalMatrices[ int( skinIndex.y ) ] * skinVertexB ) * skinWeight.y;",
  5596. "gl_Position = projectionMatrix * modelViewMatrix * gl_Position;",
  5597. "#endif"
  5598. ].join("\n"),
  5599. // MORPHING
  5600. morphtarget_pars_vertex: [
  5601. "#ifdef USE_MORPHTARGETS",
  5602. "#ifndef USE_MORPHNORMALS",
  5603. "uniform float morphTargetInfluences[ 8 ];",
  5604. "#else",
  5605. "uniform float morphTargetInfluences[ 4 ];",
  5606. "#endif",
  5607. "#endif"
  5608. ].join("\n"),
  5609. morphtarget_vertex: [
  5610. "#ifdef USE_MORPHTARGETS",
  5611. "vec3 morphed = vec3( 0.0 );",
  5612. "morphed += ( morphTarget0 - position ) * morphTargetInfluences[ 0 ];",
  5613. "morphed += ( morphTarget1 - position ) * morphTargetInfluences[ 1 ];",
  5614. "morphed += ( morphTarget2 - position ) * morphTargetInfluences[ 2 ];",
  5615. "morphed += ( morphTarget3 - position ) * morphTargetInfluences[ 3 ];",
  5616. "#ifndef USE_MORPHNORMALS",
  5617. "morphed += ( morphTarget4 - position ) * morphTargetInfluences[ 4 ];",
  5618. "morphed += ( morphTarget5 - position ) * morphTargetInfluences[ 5 ];",
  5619. "morphed += ( morphTarget6 - position ) * morphTargetInfluences[ 6 ];",
  5620. "morphed += ( morphTarget7 - position ) * morphTargetInfluences[ 7 ];",
  5621. "#endif",
  5622. "morphed += position;",
  5623. "gl_Position = projectionMatrix * modelViewMatrix * vec4( morphed, 1.0 );",
  5624. "#endif"
  5625. ].join("\n"),
  5626. default_vertex : [
  5627. "#ifndef USE_MORPHTARGETS",
  5628. "#ifndef USE_SKINNING",
  5629. "gl_Position = projectionMatrix * mvPosition;",
  5630. "#endif",
  5631. "#endif"
  5632. ].join("\n"),
  5633. morphnormal_vertex: [
  5634. "#ifdef USE_MORPHNORMALS",
  5635. "vec3 morphedNormal = vec3( 0.0 );",
  5636. "morphedNormal += ( morphNormal0 - normal ) * morphTargetInfluences[ 0 ];",
  5637. "morphedNormal += ( morphNormal1 - normal ) * morphTargetInfluences[ 1 ];",
  5638. "morphedNormal += ( morphNormal2 - normal ) * morphTargetInfluences[ 2 ];",
  5639. "morphedNormal += ( morphNormal3 - normal ) * morphTargetInfluences[ 3 ];",
  5640. "morphedNormal += normal;",
  5641. "vec3 transformedNormal = normalMatrix * morphedNormal;",
  5642. "#else",
  5643. "vec3 transformedNormal = normalMatrix * normal;",
  5644. "#endif"
  5645. ].join("\n"),
  5646. // SHADOW MAP
  5647. // based on SpiderGL shadow map and Fabien Sanglard's GLSL shadow mapping examples
  5648. // http://spidergl.org/example.php?id=6
  5649. // http://fabiensanglard.net/shadowmapping
  5650. shadowmap_pars_fragment: [
  5651. "#ifdef USE_SHADOWMAP",
  5652. "uniform sampler2D shadowMap[ MAX_SHADOWS ];",
  5653. "uniform vec2 shadowMapSize[ MAX_SHADOWS ];",
  5654. "uniform float shadowDarkness[ MAX_SHADOWS ];",
  5655. "uniform float shadowBias[ MAX_SHADOWS ];",
  5656. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  5657. "float unpackDepth( const in vec4 rgba_depth ) {",
  5658. "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 );",
  5659. "float depth = dot( rgba_depth, bit_shift );",
  5660. "return depth;",
  5661. "}",
  5662. "#endif"
  5663. ].join("\n"),
  5664. shadowmap_fragment: [
  5665. "#ifdef USE_SHADOWMAP",
  5666. "#ifdef SHADOWMAP_DEBUG",
  5667. "vec3 frustumColors[3];",
  5668. "frustumColors[0] = vec3( 1.0, 0.5, 0.0 );",
  5669. "frustumColors[1] = vec3( 0.0, 1.0, 0.8 );",
  5670. "frustumColors[2] = vec3( 0.0, 0.5, 1.0 );",
  5671. "#endif",
  5672. "#ifdef SHADOWMAP_CASCADE",
  5673. "int inFrustumCount = 0;",
  5674. "#endif",
  5675. "float fDepth;",
  5676. "vec3 shadowColor = vec3( 1.0 );",
  5677. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  5678. "vec3 shadowCoord = vShadowCoord[ i ].xyz / vShadowCoord[ i ].w;",
  5679. // "if ( something && something )" breaks ATI OpenGL shader compiler
  5680. // "if ( all( something, something ) )" using this instead
  5681. "bvec4 inFrustumVec = bvec4 ( shadowCoord.x >= 0.0, shadowCoord.x <= 1.0, shadowCoord.y >= 0.0, shadowCoord.y <= 1.0 );",
  5682. "bool inFrustum = all( inFrustumVec );",
  5683. // don't shadow pixels outside of light frustum
  5684. // use just first frustum (for cascades)
  5685. // don't shadow pixels behind far plane of light frustum
  5686. "#ifdef SHADOWMAP_CASCADE",
  5687. "inFrustumCount += int( inFrustum );",
  5688. "bvec3 frustumTestVec = bvec3( inFrustum, inFrustumCount == 1, shadowCoord.z <= 1.0 );",
  5689. "#else",
  5690. "bvec2 frustumTestVec = bvec2( inFrustum, shadowCoord.z <= 1.0 );",
  5691. "#endif",
  5692. "bool frustumTest = all( frustumTestVec );",
  5693. "if ( frustumTest ) {",
  5694. "shadowCoord.z += shadowBias[ i ];",
  5695. "#ifdef SHADOWMAP_SOFT",
  5696. // Percentage-close filtering
  5697. // (9 pixel kernel)
  5698. // http://fabiensanglard.net/shadowmappingPCF/
  5699. "float shadow = 0.0;",
  5700. /*
  5701. // nested loops breaks shader compiler / validator on some ATI cards when using OpenGL
  5702. // must enroll loop manually
  5703. "for ( float y = -1.25; y <= 1.25; y += 1.25 )",
  5704. "for ( float x = -1.25; x <= 1.25; x += 1.25 ) {",
  5705. "vec4 rgbaDepth = texture2D( shadowMap[ i ], vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy );",
  5706. // doesn't seem to produce any noticeable visual difference compared to simple "texture2D" lookup
  5707. //"vec4 rgbaDepth = texture2DProj( shadowMap[ i ], vec4( vShadowCoord[ i ].w * ( vec2( x * xPixelOffset, y * yPixelOffset ) + shadowCoord.xy ), 0.05, vShadowCoord[ i ].w ) );",
  5708. "float fDepth = unpackDepth( rgbaDepth );",
  5709. "if ( fDepth < shadowCoord.z )",
  5710. "shadow += 1.0;",
  5711. "}",
  5712. "shadow /= 9.0;",
  5713. */
  5714. "const float shadowDelta = 1.0 / 9.0;",
  5715. "float xPixelOffset = 1.0 / shadowMapSize[ i ].x;",
  5716. "float yPixelOffset = 1.0 / shadowMapSize[ i ].y;",
  5717. "float dx0 = -1.25 * xPixelOffset;",
  5718. "float dy0 = -1.25 * yPixelOffset;",
  5719. "float dx1 = 1.25 * xPixelOffset;",
  5720. "float dy1 = 1.25 * yPixelOffset;",
  5721. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy0 ) ) );",
  5722. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5723. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy0 ) ) );",
  5724. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5725. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy0 ) ) );",
  5726. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5727. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, 0.0 ) ) );",
  5728. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5729. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy ) );",
  5730. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5731. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, 0.0 ) ) );",
  5732. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5733. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx0, dy1 ) ) );",
  5734. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5735. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( 0.0, dy1 ) ) );",
  5736. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5737. "fDepth = unpackDepth( texture2D( shadowMap[ i ], shadowCoord.xy + vec2( dx1, dy1 ) ) );",
  5738. "if ( fDepth < shadowCoord.z ) shadow += shadowDelta;",
  5739. "shadowColor = shadowColor * vec3( ( 1.0 - shadowDarkness[ i ] * shadow ) );",
  5740. "#else",
  5741. "vec4 rgbaDepth = texture2D( shadowMap[ i ], shadowCoord.xy );",
  5742. "float fDepth = unpackDepth( rgbaDepth );",
  5743. "if ( fDepth < shadowCoord.z )",
  5744. // spot with multiple shadows is darker
  5745. "shadowColor = shadowColor * vec3( 1.0 - shadowDarkness[ i ] );",
  5746. // spot with multiple shadows has the same color as single shadow spot
  5747. //"shadowColor = min( shadowColor, vec3( shadowDarkness[ i ] ) );",
  5748. "#endif",
  5749. "}",
  5750. "#ifdef SHADOWMAP_DEBUG",
  5751. "#ifdef SHADOWMAP_CASCADE",
  5752. "if ( inFrustum && inFrustumCount == 1 ) gl_FragColor.xyz *= frustumColors[ i ];",
  5753. "#else",
  5754. "if ( inFrustum ) gl_FragColor.xyz *= frustumColors[ i ];",
  5755. "#endif",
  5756. "#endif",
  5757. "}",
  5758. "#ifdef GAMMA_OUTPUT",
  5759. "shadowColor *= shadowColor;",
  5760. "#endif",
  5761. "gl_FragColor.xyz = gl_FragColor.xyz * shadowColor;",
  5762. "#endif"
  5763. ].join("\n"),
  5764. shadowmap_pars_vertex: [
  5765. "#ifdef USE_SHADOWMAP",
  5766. "varying vec4 vShadowCoord[ MAX_SHADOWS ];",
  5767. "uniform mat4 shadowMatrix[ MAX_SHADOWS ];",
  5768. "#endif"
  5769. ].join("\n"),
  5770. shadowmap_vertex: [
  5771. "#ifdef USE_SHADOWMAP",
  5772. "for( int i = 0; i < MAX_SHADOWS; i ++ ) {",
  5773. "#ifdef USE_MORPHTARGETS",
  5774. "vShadowCoord[ i ] = shadowMatrix[ i ] * objectMatrix * vec4( morphed, 1.0 );",
  5775. "#else",
  5776. "vShadowCoord[ i ] = shadowMatrix[ i ] * objectMatrix * vec4( position, 1.0 );",
  5777. "#endif",
  5778. "}",
  5779. "#endif"
  5780. ].join("\n"),
  5781. // ALPHATEST
  5782. alphatest_fragment: [
  5783. "#ifdef ALPHATEST",
  5784. "if ( gl_FragColor.a < ALPHATEST ) discard;",
  5785. "#endif"
  5786. ].join("\n"),
  5787. // LINEAR SPACE
  5788. linear_to_gamma_fragment: [
  5789. "#ifdef GAMMA_OUTPUT",
  5790. "gl_FragColor.xyz = sqrt( gl_FragColor.xyz );",
  5791. "#endif"
  5792. ].join("\n"),
  5793. };
  5794. THREE.UniformsUtils = {
  5795. merge: function ( uniforms ) {
  5796. var u, p, tmp, merged = {};
  5797. for ( u = 0; u < uniforms.length; u++ ) {
  5798. tmp = this.clone( uniforms[ u ] );
  5799. for ( p in tmp ) {
  5800. merged[ p ] = tmp[ p ];
  5801. }
  5802. }
  5803. return merged;
  5804. },
  5805. clone: function ( uniforms_src ) {
  5806. var u, p, parameter, parameter_src, uniforms_dst = {};
  5807. for ( u in uniforms_src ) {
  5808. uniforms_dst[ u ] = {};
  5809. for ( p in uniforms_src[ u ] ) {
  5810. parameter_src = uniforms_src[ u ][ p ];
  5811. if ( parameter_src instanceof THREE.Color ||
  5812. parameter_src instanceof THREE.Vector2 ||
  5813. parameter_src instanceof THREE.Vector3 ||
  5814. parameter_src instanceof THREE.Vector4 ||
  5815. parameter_src instanceof THREE.Matrix4 ||
  5816. parameter_src instanceof THREE.Texture ) {
  5817. uniforms_dst[ u ][ p ] = parameter_src.clone();
  5818. } else if ( parameter_src instanceof Array ) {
  5819. uniforms_dst[ u ][ p ] = parameter_src.slice();
  5820. } else {
  5821. uniforms_dst[ u ][ p ] = parameter_src;
  5822. }
  5823. }
  5824. }
  5825. return uniforms_dst;
  5826. }
  5827. };
  5828. THREE.UniformsLib = {
  5829. common: {
  5830. "diffuse" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  5831. "opacity" : { type: "f", value: 1.0 },
  5832. "map" : { type: "t", value: 0, texture: null },
  5833. "offsetRepeat" : { type: "v4", value: new THREE.Vector4( 0, 0, 1, 1 ) },
  5834. "lightMap" : { type: "t", value: 2, texture: null },
  5835. "envMap" : { type: "t", value: 1, texture: null },
  5836. "flipEnvMap" : { type: "f", value: -1 },
  5837. "useRefract" : { type: "i", value: 0 },
  5838. "reflectivity" : { type: "f", value: 1.0 },
  5839. "refractionRatio" : { type: "f", value: 0.98 },
  5840. "combine" : { type: "i", value: 0 },
  5841. "morphTargetInfluences" : { type: "f", value: 0 }
  5842. },
  5843. fog : {
  5844. "fogDensity" : { type: "f", value: 0.00025 },
  5845. "fogNear" : { type: "f", value: 1 },
  5846. "fogFar" : { type: "f", value: 2000 },
  5847. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  5848. },
  5849. lights: {
  5850. "ambientLightColor" : { type: "fv", value: [] },
  5851. "directionalLightDirection" : { type: "fv", value: [] },
  5852. "directionalLightColor" : { type: "fv", value: [] },
  5853. "pointLightColor" : { type: "fv", value: [] },
  5854. "pointLightPosition" : { type: "fv", value: [] },
  5855. "pointLightDistance" : { type: "fv1", value: [] }
  5856. },
  5857. particle: {
  5858. "psColor" : { type: "c", value: new THREE.Color( 0xeeeeee ) },
  5859. "opacity" : { type: "f", value: 1.0 },
  5860. "size" : { type: "f", value: 1.0 },
  5861. "scale" : { type: "f", value: 1.0 },
  5862. "map" : { type: "t", value: 0, texture: null },
  5863. "fogDensity" : { type: "f", value: 0.00025 },
  5864. "fogNear" : { type: "f", value: 1 },
  5865. "fogFar" : { type: "f", value: 2000 },
  5866. "fogColor" : { type: "c", value: new THREE.Color( 0xffffff ) }
  5867. },
  5868. shadowmap: {
  5869. "shadowMap": { type: "tv", value: 6, texture: [] },
  5870. "shadowMapSize": { type: "v2v", value: [] },
  5871. "shadowBias" : { type: "fv1", value: [] },
  5872. "shadowDarkness": { type: "fv1", value: [] },
  5873. "shadowMatrix" : { type: "m4v", value: [] },
  5874. }
  5875. };
  5876. THREE.ShaderLib = {
  5877. 'depth': {
  5878. uniforms: {
  5879. "mNear": { type: "f", value: 1.0 },
  5880. "mFar" : { type: "f", value: 2000.0 },
  5881. "opacity" : { type: "f", value: 1.0 }
  5882. },
  5883. vertexShader: [
  5884. "void main() {",
  5885. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  5886. "}"
  5887. ].join("\n"),
  5888. fragmentShader: [
  5889. "uniform float mNear;",
  5890. "uniform float mFar;",
  5891. "uniform float opacity;",
  5892. "void main() {",
  5893. "float depth = gl_FragCoord.z / gl_FragCoord.w;",
  5894. "float color = 1.0 - smoothstep( mNear, mFar, depth );",
  5895. "gl_FragColor = vec4( vec3( color ), opacity );",
  5896. "}"
  5897. ].join("\n")
  5898. },
  5899. 'normal': {
  5900. uniforms: {
  5901. "opacity" : { type: "f", value: 1.0 }
  5902. },
  5903. vertexShader: [
  5904. "varying vec3 vNormal;",
  5905. "void main() {",
  5906. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5907. "vNormal = normalMatrix * normal;",
  5908. "gl_Position = projectionMatrix * mvPosition;",
  5909. "}"
  5910. ].join("\n"),
  5911. fragmentShader: [
  5912. "uniform float opacity;",
  5913. "varying vec3 vNormal;",
  5914. "void main() {",
  5915. "gl_FragColor = vec4( 0.5 * normalize( vNormal ) + 0.5, opacity );",
  5916. "}"
  5917. ].join("\n")
  5918. },
  5919. 'basic': {
  5920. uniforms: THREE.UniformsUtils.merge( [
  5921. THREE.UniformsLib[ "common" ],
  5922. THREE.UniformsLib[ "fog" ],
  5923. THREE.UniformsLib[ "shadowmap" ]
  5924. ] ),
  5925. vertexShader: [
  5926. THREE.ShaderChunk[ "map_pars_vertex" ],
  5927. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  5928. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  5929. THREE.ShaderChunk[ "color_pars_vertex" ],
  5930. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  5931. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  5932. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  5933. "void main() {",
  5934. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5935. THREE.ShaderChunk[ "map_vertex" ],
  5936. THREE.ShaderChunk[ "lightmap_vertex" ],
  5937. THREE.ShaderChunk[ "envmap_vertex" ],
  5938. THREE.ShaderChunk[ "color_vertex" ],
  5939. THREE.ShaderChunk[ "skinning_vertex" ],
  5940. THREE.ShaderChunk[ "morphtarget_vertex" ],
  5941. THREE.ShaderChunk[ "default_vertex" ],
  5942. THREE.ShaderChunk[ "shadowmap_vertex" ],
  5943. "}"
  5944. ].join("\n"),
  5945. fragmentShader: [
  5946. "uniform vec3 diffuse;",
  5947. "uniform float opacity;",
  5948. THREE.ShaderChunk[ "color_pars_fragment" ],
  5949. THREE.ShaderChunk[ "map_pars_fragment" ],
  5950. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  5951. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  5952. THREE.ShaderChunk[ "fog_pars_fragment" ],
  5953. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  5954. "void main() {",
  5955. "gl_FragColor = vec4( diffuse, opacity );",
  5956. THREE.ShaderChunk[ "map_fragment" ],
  5957. THREE.ShaderChunk[ "alphatest_fragment" ],
  5958. THREE.ShaderChunk[ "lightmap_fragment" ],
  5959. THREE.ShaderChunk[ "color_fragment" ],
  5960. THREE.ShaderChunk[ "envmap_fragment" ],
  5961. THREE.ShaderChunk[ "shadowmap_fragment" ],
  5962. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  5963. THREE.ShaderChunk[ "fog_fragment" ],
  5964. "}"
  5965. ].join("\n")
  5966. },
  5967. 'lambert': {
  5968. uniforms: THREE.UniformsUtils.merge( [
  5969. THREE.UniformsLib[ "common" ],
  5970. THREE.UniformsLib[ "fog" ],
  5971. THREE.UniformsLib[ "lights" ],
  5972. THREE.UniformsLib[ "shadowmap" ],
  5973. {
  5974. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  5975. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  5976. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  5977. }
  5978. ] ),
  5979. vertexShader: [
  5980. "varying vec3 vLightFront;",
  5981. "#ifdef DOUBLE_SIDED",
  5982. "varying vec3 vLightBack;",
  5983. "#endif",
  5984. THREE.ShaderChunk[ "map_pars_vertex" ],
  5985. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  5986. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  5987. THREE.ShaderChunk[ "lights_lambert_pars_vertex" ],
  5988. THREE.ShaderChunk[ "color_pars_vertex" ],
  5989. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  5990. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  5991. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  5992. "void main() {",
  5993. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  5994. THREE.ShaderChunk[ "map_vertex" ],
  5995. THREE.ShaderChunk[ "lightmap_vertex" ],
  5996. THREE.ShaderChunk[ "envmap_vertex" ],
  5997. THREE.ShaderChunk[ "color_vertex" ],
  5998. THREE.ShaderChunk[ "morphnormal_vertex" ],
  5999. THREE.ShaderChunk[ "lights_lambert_vertex" ],
  6000. THREE.ShaderChunk[ "skinning_vertex" ],
  6001. THREE.ShaderChunk[ "morphtarget_vertex" ],
  6002. THREE.ShaderChunk[ "default_vertex" ],
  6003. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6004. "}"
  6005. ].join("\n"),
  6006. fragmentShader: [
  6007. "uniform float opacity;",
  6008. "varying vec3 vLightFront;",
  6009. "#ifdef DOUBLE_SIDED",
  6010. "varying vec3 vLightBack;",
  6011. "#endif",
  6012. THREE.ShaderChunk[ "color_pars_fragment" ],
  6013. THREE.ShaderChunk[ "map_pars_fragment" ],
  6014. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  6015. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  6016. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6017. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6018. "void main() {",
  6019. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  6020. THREE.ShaderChunk[ "map_fragment" ],
  6021. THREE.ShaderChunk[ "alphatest_fragment" ],
  6022. "#ifdef DOUBLE_SIDED",
  6023. //"float isFront = float( gl_FrontFacing );",
  6024. //"gl_FragColor.xyz *= isFront * vLightFront + ( 1.0 - isFront ) * vLightBack;",
  6025. "if ( gl_FrontFacing )",
  6026. "gl_FragColor.xyz *= vLightFront;",
  6027. "else",
  6028. "gl_FragColor.xyz *= vLightBack;",
  6029. "#else",
  6030. "gl_FragColor.xyz *= vLightFront;",
  6031. "#endif",
  6032. THREE.ShaderChunk[ "lightmap_fragment" ],
  6033. THREE.ShaderChunk[ "color_fragment" ],
  6034. THREE.ShaderChunk[ "envmap_fragment" ],
  6035. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6036. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  6037. THREE.ShaderChunk[ "fog_fragment" ],
  6038. "}"
  6039. ].join("\n")
  6040. },
  6041. 'phong': {
  6042. uniforms: THREE.UniformsUtils.merge( [
  6043. THREE.UniformsLib[ "common" ],
  6044. THREE.UniformsLib[ "fog" ],
  6045. THREE.UniformsLib[ "lights" ],
  6046. THREE.UniformsLib[ "shadowmap" ],
  6047. {
  6048. "ambient" : { type: "c", value: new THREE.Color( 0xffffff ) },
  6049. "emissive" : { type: "c", value: new THREE.Color( 0x000000 ) },
  6050. "specular" : { type: "c", value: new THREE.Color( 0x111111 ) },
  6051. "shininess": { type: "f", value: 30 },
  6052. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  6053. }
  6054. ] ),
  6055. vertexShader: [
  6056. "varying vec3 vViewPosition;",
  6057. "varying vec3 vNormal;",
  6058. THREE.ShaderChunk[ "map_pars_vertex" ],
  6059. THREE.ShaderChunk[ "lightmap_pars_vertex" ],
  6060. THREE.ShaderChunk[ "envmap_pars_vertex" ],
  6061. THREE.ShaderChunk[ "lights_phong_pars_vertex" ],
  6062. THREE.ShaderChunk[ "color_pars_vertex" ],
  6063. THREE.ShaderChunk[ "skinning_pars_vertex" ],
  6064. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  6065. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  6066. "void main() {",
  6067. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6068. THREE.ShaderChunk[ "map_vertex" ],
  6069. THREE.ShaderChunk[ "lightmap_vertex" ],
  6070. THREE.ShaderChunk[ "envmap_vertex" ],
  6071. THREE.ShaderChunk[ "color_vertex" ],
  6072. "#ifndef USE_ENVMAP",
  6073. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  6074. "#endif",
  6075. "vViewPosition = -mvPosition.xyz;",
  6076. THREE.ShaderChunk[ "morphnormal_vertex" ],
  6077. "vNormal = transformedNormal;",
  6078. THREE.ShaderChunk[ "lights_phong_vertex" ],
  6079. THREE.ShaderChunk[ "skinning_vertex" ],
  6080. THREE.ShaderChunk[ "morphtarget_vertex" ],
  6081. THREE.ShaderChunk[ "default_vertex" ],
  6082. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6083. "}"
  6084. ].join("\n"),
  6085. fragmentShader: [
  6086. "uniform vec3 diffuse;",
  6087. "uniform float opacity;",
  6088. "uniform vec3 ambient;",
  6089. "uniform vec3 emissive;",
  6090. "uniform vec3 specular;",
  6091. "uniform float shininess;",
  6092. THREE.ShaderChunk[ "color_pars_fragment" ],
  6093. THREE.ShaderChunk[ "map_pars_fragment" ],
  6094. THREE.ShaderChunk[ "lightmap_pars_fragment" ],
  6095. THREE.ShaderChunk[ "envmap_pars_fragment" ],
  6096. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6097. THREE.ShaderChunk[ "lights_phong_pars_fragment" ],
  6098. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6099. "void main() {",
  6100. "gl_FragColor = vec4( vec3 ( 1.0 ), opacity );",
  6101. THREE.ShaderChunk[ "map_fragment" ],
  6102. THREE.ShaderChunk[ "alphatest_fragment" ],
  6103. THREE.ShaderChunk[ "lights_phong_fragment" ],
  6104. THREE.ShaderChunk[ "lightmap_fragment" ],
  6105. THREE.ShaderChunk[ "color_fragment" ],
  6106. THREE.ShaderChunk[ "envmap_fragment" ],
  6107. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6108. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  6109. THREE.ShaderChunk[ "fog_fragment" ],
  6110. "}"
  6111. ].join("\n")
  6112. },
  6113. 'particle_basic': {
  6114. uniforms: THREE.UniformsUtils.merge( [
  6115. THREE.UniformsLib[ "particle" ],
  6116. THREE.UniformsLib[ "shadowmap" ]
  6117. ] ),
  6118. vertexShader: [
  6119. "uniform float size;",
  6120. "uniform float scale;",
  6121. THREE.ShaderChunk[ "color_pars_vertex" ],
  6122. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  6123. "void main() {",
  6124. THREE.ShaderChunk[ "color_vertex" ],
  6125. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6126. "#ifdef USE_SIZEATTENUATION",
  6127. "gl_PointSize = size * ( scale / length( mvPosition.xyz ) );",
  6128. "#else",
  6129. "gl_PointSize = size;",
  6130. "#endif",
  6131. "gl_Position = projectionMatrix * mvPosition;",
  6132. THREE.ShaderChunk[ "shadowmap_vertex" ],
  6133. "}"
  6134. ].join("\n"),
  6135. fragmentShader: [
  6136. "uniform vec3 psColor;",
  6137. "uniform float opacity;",
  6138. THREE.ShaderChunk[ "color_pars_fragment" ],
  6139. THREE.ShaderChunk[ "map_particle_pars_fragment" ],
  6140. THREE.ShaderChunk[ "fog_pars_fragment" ],
  6141. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  6142. "void main() {",
  6143. "gl_FragColor = vec4( psColor, opacity );",
  6144. THREE.ShaderChunk[ "map_particle_fragment" ],
  6145. THREE.ShaderChunk[ "alphatest_fragment" ],
  6146. THREE.ShaderChunk[ "color_fragment" ],
  6147. THREE.ShaderChunk[ "shadowmap_fragment" ],
  6148. THREE.ShaderChunk[ "fog_fragment" ],
  6149. "}"
  6150. ].join("\n")
  6151. },
  6152. // Depth encoding into RGBA texture
  6153. // based on SpiderGL shadow map example
  6154. // http://spidergl.org/example.php?id=6
  6155. // originally from
  6156. // http://www.gamedev.net/topic/442138-packing-a-float-into-a-a8r8g8b8-texture-shader/page__whichpage__1%25EF%25BF%25BD
  6157. // see also here:
  6158. // http://aras-p.info/blog/2009/07/30/encoding-floats-to-rgba-the-final/
  6159. 'depthRGBA': {
  6160. uniforms: {},
  6161. vertexShader: [
  6162. THREE.ShaderChunk[ "morphtarget_pars_vertex" ],
  6163. "void main() {",
  6164. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  6165. THREE.ShaderChunk[ "morphtarget_vertex" ],
  6166. THREE.ShaderChunk[ "default_vertex" ],
  6167. "}"
  6168. ].join("\n"),
  6169. fragmentShader: [
  6170. "vec4 pack_depth( const in float depth ) {",
  6171. "const vec4 bit_shift = vec4( 256.0 * 256.0 * 256.0, 256.0 * 256.0, 256.0, 1.0 );",
  6172. "const vec4 bit_mask = vec4( 0.0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0 );",
  6173. "vec4 res = fract( depth * bit_shift );",
  6174. "res -= res.xxyz * bit_mask;",
  6175. "return res;",
  6176. "}",
  6177. "void main() {",
  6178. "gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z );",
  6179. //"gl_FragData[ 0 ] = pack_depth( gl_FragCoord.z / gl_FragCoord.w );",
  6180. //"float z = ( ( gl_FragCoord.z / gl_FragCoord.w ) - 3.0 ) / ( 4000.0 - 3.0 );",
  6181. //"gl_FragData[ 0 ] = pack_depth( z );",
  6182. //"gl_FragData[ 0 ] = vec4( z, z, z, 1.0 );",
  6183. "}"
  6184. ].join("\n")
  6185. }
  6186. };/**
  6187. * @author supereggbert / http://www.paulbrunt.co.uk/
  6188. * @author mrdoob / http://mrdoob.com/
  6189. * @author alteredq / http://alteredqualia.com/
  6190. * @author szimek / https://github.com/szimek/
  6191. */
  6192. THREE.WebGLRenderer = function ( parameters ) {
  6193. // constructor parameters
  6194. parameters = parameters || {};
  6195. var _canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ),
  6196. _precision = parameters.precision !== undefined ? parameters.precision : 'highp',
  6197. _alpha = parameters.alpha !== undefined ? parameters.alpha : true,
  6198. _premultipliedAlpha = parameters.premultipliedAlpha !== undefined ? parameters.premultipliedAlpha : true,
  6199. _antialias = parameters.antialias !== undefined ? parameters.antialias : false,
  6200. _stencil = parameters.stencil !== undefined ? parameters.stencil : true,
  6201. _preserveDrawingBuffer = parameters.preserveDrawingBuffer !== undefined ? parameters.preserveDrawingBuffer : false,
  6202. _clearColor = parameters.clearColor !== undefined ? new THREE.Color( parameters.clearColor ) : new THREE.Color( 0x000000 ),
  6203. _clearAlpha = parameters.clearAlpha !== undefined ? parameters.clearAlpha : 0,
  6204. _maxLights = parameters.maxLights !== undefined ? parameters.maxLights : 4;
  6205. // public properties
  6206. this.domElement = _canvas;
  6207. this.context = null;
  6208. // clearing
  6209. this.autoClear = true;
  6210. this.autoClearColor = true;
  6211. this.autoClearDepth = true;
  6212. this.autoClearStencil = true;
  6213. // scene graph
  6214. this.sortObjects = true;
  6215. this.autoUpdateObjects = true;
  6216. this.autoUpdateScene = true;
  6217. // physically based shading
  6218. this.gammaInput = false;
  6219. this.gammaOutput = false;
  6220. this.physicallyBasedShading = false;
  6221. // shadow map
  6222. this.shadowMapEnabled = false;
  6223. this.shadowMapAutoUpdate = true;
  6224. this.shadowMapSoft = true;
  6225. this.shadowMapCullFrontFaces = true;
  6226. this.shadowMapDebug = false;
  6227. this.shadowMapCascade = false;
  6228. // morphs
  6229. this.maxMorphTargets = 8;
  6230. this.maxMorphNormals = 4;
  6231. // flags
  6232. this.autoScaleCubemaps = true;
  6233. // custom render plugins
  6234. this.renderPluginsPre = [];
  6235. this.renderPluginsPost = [];
  6236. // info
  6237. this.info = {
  6238. memory: {
  6239. programs: 0,
  6240. geometries: 0,
  6241. textures: 0
  6242. },
  6243. render: {
  6244. calls: 0,
  6245. vertices: 0,
  6246. faces: 0,
  6247. points: 0
  6248. }
  6249. };
  6250. // internal properties
  6251. var _this = this,
  6252. _gl,
  6253. _programs = [],
  6254. // internal state cache
  6255. _currentProgram = null,
  6256. _currentFramebuffer = null,
  6257. _currentMaterialId = -1,
  6258. _currentGeometryGroupHash = null,
  6259. _currentCamera = null,
  6260. _geometryGroupCounter = 0,
  6261. // GL state cache
  6262. _oldDoubleSided = null,
  6263. _oldFlipSided = null,
  6264. _oldBlending = null,
  6265. _oldBlendEquation = null,
  6266. _oldBlendSrc = null,
  6267. _oldBlendDst = null,
  6268. _oldDepthTest = null,
  6269. _oldDepthWrite = null,
  6270. _oldPolygonOffset = null,
  6271. _oldPolygonOffsetFactor = null,
  6272. _oldPolygonOffsetUnits = null,
  6273. _oldLineWidth = null,
  6274. _viewportX = 0,
  6275. _viewportY = 0,
  6276. _viewportWidth = 0,
  6277. _viewportHeight = 0,
  6278. _currentWidth = 0,
  6279. _currentHeight = 0,
  6280. // frustum
  6281. _frustum = new THREE.Frustum(),
  6282. // camera matrices cache
  6283. _projScreenMatrix = new THREE.Matrix4(),
  6284. _projScreenMatrixPS = new THREE.Matrix4(),
  6285. _vector3 = new THREE.Vector4(),
  6286. // light arrays cache
  6287. _direction = new THREE.Vector3(),
  6288. _lights = {
  6289. ambient: [ 0, 0, 0 ],
  6290. directional: { length: 0, colors: new Array(), positions: new Array() },
  6291. point: { length: 0, colors: new Array(), positions: new Array(), distances: new Array() }
  6292. };
  6293. // initialize
  6294. _gl = initGL();
  6295. setDefaultGLState();
  6296. this.context = _gl;
  6297. // GPU capabilities
  6298. var _maxVertexTextures = _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ),
  6299. _maxTextureSize = _gl.getParameter( _gl.MAX_TEXTURE_SIZE ),
  6300. _maxCubemapSize = _gl.getParameter( _gl.MAX_CUBE_MAP_TEXTURE_SIZE );
  6301. // API
  6302. this.getContext = function () {
  6303. return _gl;
  6304. };
  6305. this.supportsVertexTextures = function () {
  6306. return _maxVertexTextures > 0;
  6307. };
  6308. this.setSize = function ( width, height ) {
  6309. _canvas.width = width;
  6310. _canvas.height = height;
  6311. this.setViewport( 0, 0, _canvas.width, _canvas.height );
  6312. };
  6313. this.setViewport = function ( x, y, width, height ) {
  6314. _viewportX = x;
  6315. _viewportY = y;
  6316. _viewportWidth = width;
  6317. _viewportHeight = height;
  6318. _gl.viewport( _viewportX, _viewportY, _viewportWidth, _viewportHeight );
  6319. };
  6320. this.setScissor = function ( x, y, width, height ) {
  6321. _gl.scissor( x, y, width, height );
  6322. };
  6323. this.enableScissorTest = function ( enable ) {
  6324. enable ? _gl.enable( _gl.SCISSOR_TEST ) : _gl.disable( _gl.SCISSOR_TEST );
  6325. };
  6326. // Clearing
  6327. this.setClearColorHex = function ( hex, alpha ) {
  6328. _clearColor.setHex( hex );
  6329. _clearAlpha = alpha;
  6330. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  6331. };
  6332. this.setClearColor = function ( color, alpha ) {
  6333. _clearColor.copy( color );
  6334. _clearAlpha = alpha;
  6335. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  6336. };
  6337. this.getClearColor = function () {
  6338. return _clearColor;
  6339. };
  6340. this.getClearAlpha = function () {
  6341. return _clearAlpha;
  6342. };
  6343. this.clear = function ( color, depth, stencil ) {
  6344. var bits = 0;
  6345. if ( color === undefined || color ) bits |= _gl.COLOR_BUFFER_BIT;
  6346. if ( depth === undefined || depth ) bits |= _gl.DEPTH_BUFFER_BIT;
  6347. if ( stencil === undefined || stencil ) bits |= _gl.STENCIL_BUFFER_BIT;
  6348. _gl.clear( bits );
  6349. };
  6350. this.clearTarget = function ( renderTarget, color, depth, stencil ) {
  6351. this.setRenderTarget( renderTarget );
  6352. this.clear( color, depth, stencil );
  6353. };
  6354. // Plugins
  6355. this.addPostPlugin = function ( plugin ) {
  6356. plugin.init( this );
  6357. this.renderPluginsPost.push( plugin );
  6358. };
  6359. this.addPrePlugin = function ( plugin ) {
  6360. plugin.init( this );
  6361. this.renderPluginsPre.push( plugin );
  6362. };
  6363. // Deallocation
  6364. this.deallocateObject = function ( object ) {
  6365. if ( ! object.__webglInit ) return;
  6366. object.__webglInit = false;
  6367. delete object._modelViewMatrix;
  6368. delete object._normalMatrix;
  6369. delete object._normalMatrixArray;
  6370. delete object._modelViewMatrixArray;
  6371. delete object._objectMatrixArray;
  6372. if ( object instanceof THREE.Mesh ) {
  6373. for ( var g in object.geometry.geometryGroups ) {
  6374. deleteMeshBuffers( object.geometry.geometryGroups[ g ] );
  6375. }
  6376. } else if ( object instanceof THREE.Ribbon ) {
  6377. deleteRibbonBuffers( object.geometry );
  6378. } else if ( object instanceof THREE.Line ) {
  6379. deleteLineBuffers( object.geometry );
  6380. } else if ( object instanceof THREE.ParticleSystem ) {
  6381. deleteParticleBuffers( object.geometry );
  6382. }
  6383. };
  6384. this.deallocateTexture = function ( texture ) {
  6385. if ( ! texture.__webglInit ) return;
  6386. texture.__webglInit = false;
  6387. _gl.deleteTexture( texture.__webglTexture );
  6388. _this.info.memory.textures --;
  6389. };
  6390. this.deallocateRenderTarget = function ( renderTarget ) {
  6391. if ( !renderTarget || ! renderTarget.__webglTexture ) return;
  6392. _gl.deleteTexture( renderTarget.__webglTexture );
  6393. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  6394. for ( var i = 0; i < 6; i ++ ) {
  6395. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer[ i ] );
  6396. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer[ i ] );
  6397. }
  6398. } else {
  6399. _gl.deleteFramebuffer( renderTarget.__webglFramebuffer );
  6400. _gl.deleteRenderbuffer( renderTarget.__webglRenderbuffer );
  6401. }
  6402. };
  6403. // Rendering
  6404. this.updateShadowMap = function ( scene, camera ) {
  6405. _currentProgram = null;
  6406. _oldBlending = -1;
  6407. _oldDepthTest = -1;
  6408. _oldDepthWrite = -1;
  6409. _currentGeometryGroupHash = -1;
  6410. _currentMaterialId = -1;
  6411. this.shadowMapPlugin.update( scene, camera );
  6412. };
  6413. // Internal functions
  6414. // Buffer allocation
  6415. function createParticleBuffers ( geometry ) {
  6416. geometry.__webglVertexBuffer = _gl.createBuffer();
  6417. geometry.__webglColorBuffer = _gl.createBuffer();
  6418. _this.info.geometries ++;
  6419. };
  6420. function createLineBuffers ( geometry ) {
  6421. geometry.__webglVertexBuffer = _gl.createBuffer();
  6422. geometry.__webglColorBuffer = _gl.createBuffer();
  6423. _this.info.memory.geometries ++;
  6424. };
  6425. function createRibbonBuffers ( geometry ) {
  6426. geometry.__webglVertexBuffer = _gl.createBuffer();
  6427. geometry.__webglColorBuffer = _gl.createBuffer();
  6428. _this.info.memory.geometries ++;
  6429. };
  6430. function createMeshBuffers ( geometryGroup ) {
  6431. geometryGroup.__webglVertexBuffer = _gl.createBuffer();
  6432. geometryGroup.__webglNormalBuffer = _gl.createBuffer();
  6433. geometryGroup.__webglTangentBuffer = _gl.createBuffer();
  6434. geometryGroup.__webglColorBuffer = _gl.createBuffer();
  6435. geometryGroup.__webglUVBuffer = _gl.createBuffer();
  6436. geometryGroup.__webglUV2Buffer = _gl.createBuffer();
  6437. geometryGroup.__webglSkinVertexABuffer = _gl.createBuffer();
  6438. geometryGroup.__webglSkinVertexBBuffer = _gl.createBuffer();
  6439. geometryGroup.__webglSkinIndicesBuffer = _gl.createBuffer();
  6440. geometryGroup.__webglSkinWeightsBuffer = _gl.createBuffer();
  6441. geometryGroup.__webglFaceBuffer = _gl.createBuffer();
  6442. geometryGroup.__webglLineBuffer = _gl.createBuffer();
  6443. var m, ml;
  6444. if ( geometryGroup.numMorphTargets ) {
  6445. geometryGroup.__webglMorphTargetsBuffers = [];
  6446. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6447. geometryGroup.__webglMorphTargetsBuffers.push( _gl.createBuffer() );
  6448. }
  6449. }
  6450. if ( geometryGroup.numMorphNormals ) {
  6451. geometryGroup.__webglMorphNormalsBuffers = [];
  6452. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6453. geometryGroup.__webglMorphNormalsBuffers.push( _gl.createBuffer() );
  6454. }
  6455. }
  6456. _this.info.memory.geometries ++;
  6457. };
  6458. // Buffer deallocation
  6459. function deleteParticleBuffers ( geometry ) {
  6460. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6461. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6462. _this.info.memory.geometries --;
  6463. };
  6464. function deleteLineBuffers ( geometry ) {
  6465. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6466. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6467. _this.info.memory.geometries --;
  6468. };
  6469. function deleteRibbonBuffers ( geometry ) {
  6470. _gl.deleteBuffer( geometry.__webglVertexBuffer );
  6471. _gl.deleteBuffer( geometry.__webglColorBuffer );
  6472. _this.info.memory.geometries --;
  6473. };
  6474. function deleteMeshBuffers ( geometryGroup ) {
  6475. _gl.deleteBuffer( geometryGroup.__webglVertexBuffer );
  6476. _gl.deleteBuffer( geometryGroup.__webglNormalBuffer );
  6477. _gl.deleteBuffer( geometryGroup.__webglTangentBuffer );
  6478. _gl.deleteBuffer( geometryGroup.__webglColorBuffer );
  6479. _gl.deleteBuffer( geometryGroup.__webglUVBuffer );
  6480. _gl.deleteBuffer( geometryGroup.__webglUV2Buffer );
  6481. _gl.deleteBuffer( geometryGroup.__webglSkinVertexABuffer );
  6482. _gl.deleteBuffer( geometryGroup.__webglSkinVertexBBuffer );
  6483. _gl.deleteBuffer( geometryGroup.__webglSkinIndicesBuffer );
  6484. _gl.deleteBuffer( geometryGroup.__webglSkinWeightsBuffer );
  6485. _gl.deleteBuffer( geometryGroup.__webglFaceBuffer );
  6486. _gl.deleteBuffer( geometryGroup.__webglLineBuffer );
  6487. var m, ml;
  6488. if ( geometryGroup.numMorphTargets ) {
  6489. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6490. _gl.deleteBuffer( geometryGroup.__webglMorphTargetsBuffers[ m ] );
  6491. }
  6492. }
  6493. if ( geometryGroup.numMorphNormals ) {
  6494. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6495. _gl.deleteBuffer( geometryGroup.__webglMorphNormalsBuffers[ m ] );
  6496. }
  6497. }
  6498. if ( geometryGroup.__webglCustomAttributesList ) {
  6499. for ( var id in geometryGroup.__webglCustomAttributesList ) {
  6500. _gl.deleteBuffer( geometryGroup.__webglCustomAttributesList[ id ].buffer );
  6501. }
  6502. }
  6503. _this.info.memory.geometries --;
  6504. };
  6505. // Buffer initialization
  6506. function initCustomAttributes ( geometry, object ) {
  6507. var nvertices = geometry.vertices.length;
  6508. var material = object.material;
  6509. if ( material.attributes ) {
  6510. if ( geometry.__webglCustomAttributesList === undefined ) {
  6511. geometry.__webglCustomAttributesList = [];
  6512. }
  6513. for ( var a in material.attributes ) {
  6514. var attribute = material.attributes[ a ];
  6515. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  6516. attribute.__webglInitialized = true;
  6517. var size = 1; // "f" and "i"
  6518. if ( attribute.type === "v2" ) size = 2;
  6519. else if ( attribute.type === "v3" ) size = 3;
  6520. else if ( attribute.type === "v4" ) size = 4;
  6521. else if ( attribute.type === "c" ) size = 3;
  6522. attribute.size = size;
  6523. attribute.array = new Float32Array( nvertices * size );
  6524. attribute.buffer = _gl.createBuffer();
  6525. attribute.buffer.belongsToAttribute = a;
  6526. attribute.needsUpdate = true;
  6527. }
  6528. geometry.__webglCustomAttributesList.push( attribute );
  6529. }
  6530. }
  6531. };
  6532. function initParticleBuffers ( geometry, object ) {
  6533. var nvertices = geometry.vertices.length;
  6534. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6535. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6536. geometry.__sortArray = [];
  6537. geometry.__webglParticleCount = nvertices;
  6538. initCustomAttributes ( geometry, object );
  6539. };
  6540. function initLineBuffers ( geometry, object ) {
  6541. var nvertices = geometry.vertices.length;
  6542. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6543. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6544. geometry.__webglLineCount = nvertices;
  6545. initCustomAttributes ( geometry, object );
  6546. };
  6547. function initRibbonBuffers ( geometry ) {
  6548. var nvertices = geometry.vertices.length;
  6549. geometry.__vertexArray = new Float32Array( nvertices * 3 );
  6550. geometry.__colorArray = new Float32Array( nvertices * 3 );
  6551. geometry.__webglVertexCount = nvertices;
  6552. };
  6553. function initMeshBuffers ( geometryGroup, object ) {
  6554. var geometry = object.geometry,
  6555. faces3 = geometryGroup.faces3,
  6556. faces4 = geometryGroup.faces4,
  6557. nvertices = faces3.length * 3 + faces4.length * 4,
  6558. ntris = faces3.length * 1 + faces4.length * 2,
  6559. nlines = faces3.length * 3 + faces4.length * 4,
  6560. material = getBufferMaterial( object, geometryGroup ),
  6561. uvType = bufferGuessUVType( material ),
  6562. normalType = bufferGuessNormalType( material ),
  6563. vertexColorType = bufferGuessVertexColorType( material );
  6564. //console.log( "uvType", uvType, "normalType", normalType, "vertexColorType", vertexColorType, object, geometryGroup, material );
  6565. geometryGroup.__vertexArray = new Float32Array( nvertices * 3 );
  6566. if ( normalType ) {
  6567. geometryGroup.__normalArray = new Float32Array( nvertices * 3 );
  6568. }
  6569. if ( geometry.hasTangents ) {
  6570. geometryGroup.__tangentArray = new Float32Array( nvertices * 4 );
  6571. }
  6572. if ( vertexColorType ) {
  6573. geometryGroup.__colorArray = new Float32Array( nvertices * 3 );
  6574. }
  6575. if ( uvType ) {
  6576. if ( geometry.faceUvs.length > 0 || geometry.faceVertexUvs.length > 0 ) {
  6577. geometryGroup.__uvArray = new Float32Array( nvertices * 2 );
  6578. }
  6579. if ( geometry.faceUvs.length > 1 || geometry.faceVertexUvs.length > 1 ) {
  6580. geometryGroup.__uv2Array = new Float32Array( nvertices * 2 );
  6581. }
  6582. }
  6583. if ( object.geometry.skinWeights.length && object.geometry.skinIndices.length ) {
  6584. geometryGroup.__skinVertexAArray = new Float32Array( nvertices * 4 );
  6585. geometryGroup.__skinVertexBArray = new Float32Array( nvertices * 4 );
  6586. geometryGroup.__skinIndexArray = new Float32Array( nvertices * 4 );
  6587. geometryGroup.__skinWeightArray = new Float32Array( nvertices * 4 );
  6588. }
  6589. geometryGroup.__faceArray = new Uint16Array( ntris * 3 );
  6590. geometryGroup.__lineArray = new Uint16Array( nlines * 2 );
  6591. var m, ml;
  6592. if ( geometryGroup.numMorphTargets ) {
  6593. geometryGroup.__morphTargetsArrays = [];
  6594. for ( m = 0, ml = geometryGroup.numMorphTargets; m < ml; m ++ ) {
  6595. geometryGroup.__morphTargetsArrays.push( new Float32Array( nvertices * 3 ) );
  6596. }
  6597. }
  6598. if ( geometryGroup.numMorphNormals ) {
  6599. geometryGroup.__morphNormalsArrays = [];
  6600. for ( m = 0, ml = geometryGroup.numMorphNormals; m < ml; m ++ ) {
  6601. geometryGroup.__morphNormalsArrays.push( new Float32Array( nvertices * 3 ) );
  6602. }
  6603. }
  6604. geometryGroup.__webglFaceCount = ntris * 3;
  6605. geometryGroup.__webglLineCount = nlines * 2;
  6606. // custom attributes
  6607. if ( material.attributes ) {
  6608. if ( geometryGroup.__webglCustomAttributesList === undefined ) {
  6609. geometryGroup.__webglCustomAttributesList = [];
  6610. }
  6611. for ( var a in material.attributes ) {
  6612. // Do a shallow copy of the attribute object so different geometryGroup chunks use different
  6613. // attribute buffers which are correctly indexed in the setMeshBuffers function
  6614. var originalAttribute = material.attributes[ a ];
  6615. var attribute = {};
  6616. for ( var property in originalAttribute ) {
  6617. attribute[ property ] = originalAttribute[ property ];
  6618. }
  6619. if( !attribute.__webglInitialized || attribute.createUniqueBuffers ) {
  6620. attribute.__webglInitialized = true;
  6621. var size = 1; // "f" and "i"
  6622. if( attribute.type === "v2" ) size = 2;
  6623. else if( attribute.type === "v3" ) size = 3;
  6624. else if( attribute.type === "v4" ) size = 4;
  6625. else if( attribute.type === "c" ) size = 3;
  6626. attribute.size = size;
  6627. attribute.array = new Float32Array( nvertices * size );
  6628. attribute.buffer = _gl.createBuffer();
  6629. attribute.buffer.belongsToAttribute = a;
  6630. originalAttribute.needsUpdate = true;
  6631. attribute.__original = originalAttribute;
  6632. }
  6633. geometryGroup.__webglCustomAttributesList.push( attribute );
  6634. }
  6635. }
  6636. geometryGroup.__inittedArrays = true;
  6637. };
  6638. function getBufferMaterial( object, geometryGroup ) {
  6639. if ( object.material && ! ( object.material instanceof THREE.MeshFaceMaterial ) ) {
  6640. return object.material;
  6641. } else if ( geometryGroup.materialIndex >= 0 ) {
  6642. return object.geometry.materials[ geometryGroup.materialIndex ];
  6643. }
  6644. };
  6645. function materialNeedsSmoothNormals ( material ) {
  6646. return material && material.shading !== undefined && material.shading === THREE.SmoothShading;
  6647. };
  6648. function bufferGuessNormalType ( material ) {
  6649. // only MeshBasicMaterial and MeshDepthMaterial don't need normals
  6650. if ( ( material instanceof THREE.MeshBasicMaterial && !material.envMap ) || material instanceof THREE.MeshDepthMaterial ) {
  6651. return false;
  6652. }
  6653. if ( materialNeedsSmoothNormals( material ) ) {
  6654. return THREE.SmoothShading;
  6655. } else {
  6656. return THREE.FlatShading;
  6657. }
  6658. };
  6659. function bufferGuessVertexColorType ( material ) {
  6660. if ( material.vertexColors ) {
  6661. return material.vertexColors;
  6662. }
  6663. return false;
  6664. };
  6665. function bufferGuessUVType ( material ) {
  6666. // material must use some texture to require uvs
  6667. if ( material.map || material.lightMap || material instanceof THREE.ShaderMaterial ) {
  6668. return true;
  6669. }
  6670. return false;
  6671. };
  6672. // Buffer setting
  6673. function setParticleBuffers ( geometry, hint, object ) {
  6674. var v, c, vertex, offset, index, color,
  6675. vertices = geometry.vertices,
  6676. vl = vertices.length,
  6677. colors = geometry.colors,
  6678. cl = colors.length,
  6679. vertexArray = geometry.__vertexArray,
  6680. colorArray = geometry.__colorArray,
  6681. sortArray = geometry.__sortArray,
  6682. dirtyVertices = geometry.__dirtyVertices,
  6683. dirtyElements = geometry.__dirtyElements,
  6684. dirtyColors = geometry.__dirtyColors,
  6685. customAttributes = geometry.__webglCustomAttributesList,
  6686. i, il,
  6687. a, ca, cal, value,
  6688. customAttribute;
  6689. if ( object.sortParticles ) {
  6690. _projScreenMatrixPS.copy( _projScreenMatrix );
  6691. _projScreenMatrixPS.multiplySelf( object.matrixWorld );
  6692. for ( v = 0; v < vl; v ++ ) {
  6693. vertex = vertices[ v ].position;
  6694. _vector3.copy( vertex );
  6695. _projScreenMatrixPS.multiplyVector3( _vector3 );
  6696. sortArray[ v ] = [ _vector3.z, v ];
  6697. }
  6698. sortArray.sort( function( a, b ) { return b[ 0 ] - a[ 0 ]; } );
  6699. for ( v = 0; v < vl; v ++ ) {
  6700. vertex = vertices[ sortArray[v][1] ].position;
  6701. offset = v * 3;
  6702. vertexArray[ offset ] = vertex.x;
  6703. vertexArray[ offset + 1 ] = vertex.y;
  6704. vertexArray[ offset + 2 ] = vertex.z;
  6705. }
  6706. for ( c = 0; c < cl; c ++ ) {
  6707. offset = c * 3;
  6708. color = colors[ sortArray[c][1] ];
  6709. colorArray[ offset ] = color.r;
  6710. colorArray[ offset + 1 ] = color.g;
  6711. colorArray[ offset + 2 ] = color.b;
  6712. }
  6713. if ( customAttributes ) {
  6714. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6715. customAttribute = customAttributes[ i ];
  6716. if ( ! ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) ) continue;
  6717. offset = 0;
  6718. cal = customAttribute.value.length;
  6719. if ( customAttribute.size === 1 ) {
  6720. for ( ca = 0; ca < cal; ca ++ ) {
  6721. index = sortArray[ ca ][ 1 ];
  6722. customAttribute.array[ ca ] = customAttribute.value[ index ];
  6723. }
  6724. } else if ( customAttribute.size === 2 ) {
  6725. for ( ca = 0; ca < cal; ca ++ ) {
  6726. index = sortArray[ ca ][ 1 ];
  6727. value = customAttribute.value[ index ];
  6728. customAttribute.array[ offset ] = value.x;
  6729. customAttribute.array[ offset + 1 ] = value.y;
  6730. offset += 2;
  6731. }
  6732. } else if ( customAttribute.size === 3 ) {
  6733. if ( customAttribute.type === "c" ) {
  6734. for ( ca = 0; ca < cal; ca ++ ) {
  6735. index = sortArray[ ca ][ 1 ];
  6736. value = customAttribute.value[ index ];
  6737. customAttribute.array[ offset ] = value.r;
  6738. customAttribute.array[ offset + 1 ] = value.g;
  6739. customAttribute.array[ offset + 2 ] = value.b;
  6740. offset += 3;
  6741. }
  6742. } else {
  6743. for ( ca = 0; ca < cal; ca ++ ) {
  6744. index = sortArray[ ca ][ 1 ];
  6745. value = customAttribute.value[ index ];
  6746. customAttribute.array[ offset ] = value.x;
  6747. customAttribute.array[ offset + 1 ] = value.y;
  6748. customAttribute.array[ offset + 2 ] = value.z;
  6749. offset += 3;
  6750. }
  6751. }
  6752. } else if ( customAttribute.size === 4 ) {
  6753. for ( ca = 0; ca < cal; ca ++ ) {
  6754. index = sortArray[ ca ][ 1 ];
  6755. value = customAttribute.value[ index ];
  6756. customAttribute.array[ offset ] = value.x;
  6757. customAttribute.array[ offset + 1 ] = value.y;
  6758. customAttribute.array[ offset + 2 ] = value.z;
  6759. customAttribute.array[ offset + 3 ] = value.w;
  6760. offset += 4;
  6761. }
  6762. }
  6763. }
  6764. }
  6765. } else {
  6766. if ( dirtyVertices ) {
  6767. for ( v = 0; v < vl; v ++ ) {
  6768. vertex = vertices[ v ].position;
  6769. offset = v * 3;
  6770. vertexArray[ offset ] = vertex.x;
  6771. vertexArray[ offset + 1 ] = vertex.y;
  6772. vertexArray[ offset + 2 ] = vertex.z;
  6773. }
  6774. }
  6775. if ( dirtyColors ) {
  6776. for ( c = 0; c < cl; c ++ ) {
  6777. color = colors[ c ];
  6778. offset = c * 3;
  6779. colorArray[ offset ] = color.r;
  6780. colorArray[ offset + 1 ] = color.g;
  6781. colorArray[ offset + 2 ] = color.b;
  6782. }
  6783. }
  6784. if ( customAttributes ) {
  6785. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6786. customAttribute = customAttributes[ i ];
  6787. if ( customAttribute.needsUpdate &&
  6788. ( customAttribute.boundTo === undefined ||
  6789. customAttribute.boundTo === "vertices") ) {
  6790. cal = customAttribute.value.length;
  6791. offset = 0;
  6792. if ( customAttribute.size === 1 ) {
  6793. for ( ca = 0; ca < cal; ca ++ ) {
  6794. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  6795. }
  6796. } else if ( customAttribute.size === 2 ) {
  6797. for ( ca = 0; ca < cal; ca ++ ) {
  6798. value = customAttribute.value[ ca ];
  6799. customAttribute.array[ offset ] = value.x;
  6800. customAttribute.array[ offset + 1 ] = value.y;
  6801. offset += 2;
  6802. }
  6803. } else if ( customAttribute.size === 3 ) {
  6804. if ( customAttribute.type === "c" ) {
  6805. for ( ca = 0; ca < cal; ca ++ ) {
  6806. value = customAttribute.value[ ca ];
  6807. customAttribute.array[ offset ] = value.r;
  6808. customAttribute.array[ offset + 1 ] = value.g;
  6809. customAttribute.array[ offset + 2 ] = value.b;
  6810. offset += 3;
  6811. }
  6812. } else {
  6813. for ( ca = 0; ca < cal; ca ++ ) {
  6814. value = customAttribute.value[ ca ];
  6815. customAttribute.array[ offset ] = value.x;
  6816. customAttribute.array[ offset + 1 ] = value.y;
  6817. customAttribute.array[ offset + 2 ] = value.z;
  6818. offset += 3;
  6819. }
  6820. }
  6821. } else if ( customAttribute.size === 4 ) {
  6822. for ( ca = 0; ca < cal; ca ++ ) {
  6823. value = customAttribute.value[ ca ];
  6824. customAttribute.array[ offset ] = value.x;
  6825. customAttribute.array[ offset + 1 ] = value.y;
  6826. customAttribute.array[ offset + 2 ] = value.z;
  6827. customAttribute.array[ offset + 3 ] = value.w;
  6828. offset += 4;
  6829. }
  6830. }
  6831. }
  6832. }
  6833. }
  6834. }
  6835. if ( dirtyVertices || object.sortParticles ) {
  6836. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6837. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6838. }
  6839. if ( dirtyColors || object.sortParticles ) {
  6840. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6841. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6842. }
  6843. if ( customAttributes ) {
  6844. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6845. customAttribute = customAttributes[ i ];
  6846. if ( customAttribute.needsUpdate || object.sortParticles ) {
  6847. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  6848. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  6849. }
  6850. }
  6851. }
  6852. };
  6853. function setLineBuffers ( geometry, hint ) {
  6854. var v, c, vertex, offset, color,
  6855. vertices = geometry.vertices,
  6856. colors = geometry.colors,
  6857. vl = vertices.length,
  6858. cl = colors.length,
  6859. vertexArray = geometry.__vertexArray,
  6860. colorArray = geometry.__colorArray,
  6861. dirtyVertices = geometry.__dirtyVertices,
  6862. dirtyColors = geometry.__dirtyColors,
  6863. customAttributes = geometry.__webglCustomAttributesList,
  6864. i, il,
  6865. a, ca, cal, value,
  6866. customAttribute;
  6867. if ( dirtyVertices ) {
  6868. for ( v = 0; v < vl; v ++ ) {
  6869. vertex = vertices[ v ].position;
  6870. offset = v * 3;
  6871. vertexArray[ offset ] = vertex.x;
  6872. vertexArray[ offset + 1 ] = vertex.y;
  6873. vertexArray[ offset + 2 ] = vertex.z;
  6874. }
  6875. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6876. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6877. }
  6878. if ( dirtyColors ) {
  6879. for ( c = 0; c < cl; c ++ ) {
  6880. color = colors[ c ];
  6881. offset = c * 3;
  6882. colorArray[ offset ] = color.r;
  6883. colorArray[ offset + 1 ] = color.g;
  6884. colorArray[ offset + 2 ] = color.b;
  6885. }
  6886. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6887. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6888. }
  6889. if ( customAttributes ) {
  6890. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  6891. customAttribute = customAttributes[ i ];
  6892. if ( customAttribute.needsUpdate &&
  6893. ( customAttribute.boundTo === undefined ||
  6894. customAttribute.boundTo === "vertices" ) ) {
  6895. offset = 0;
  6896. cal = customAttribute.value.length;
  6897. if ( customAttribute.size === 1 ) {
  6898. for ( ca = 0; ca < cal; ca ++ ) {
  6899. customAttribute.array[ ca ] = customAttribute.value[ ca ];
  6900. }
  6901. } else if ( customAttribute.size === 2 ) {
  6902. for ( ca = 0; ca < cal; ca ++ ) {
  6903. value = customAttribute.value[ ca ];
  6904. customAttribute.array[ offset ] = value.x;
  6905. customAttribute.array[ offset + 1 ] = value.y;
  6906. offset += 2;
  6907. }
  6908. } else if ( customAttribute.size === 3 ) {
  6909. if ( customAttribute.type === "c" ) {
  6910. for ( ca = 0; ca < cal; ca ++ ) {
  6911. value = customAttribute.value[ ca ];
  6912. customAttribute.array[ offset ] = value.r;
  6913. customAttribute.array[ offset + 1 ] = value.g;
  6914. customAttribute.array[ offset + 2 ] = value.b;
  6915. offset += 3;
  6916. }
  6917. } else {
  6918. for ( ca = 0; ca < cal; ca ++ ) {
  6919. value = customAttribute.value[ ca ];
  6920. customAttribute.array[ offset ] = value.x;
  6921. customAttribute.array[ offset + 1 ] = value.y;
  6922. customAttribute.array[ offset + 2 ] = value.z;
  6923. offset += 3;
  6924. }
  6925. }
  6926. } else if ( customAttribute.size === 4 ) {
  6927. for ( ca = 0; ca < cal; ca ++ ) {
  6928. value = customAttribute.value[ ca ];
  6929. customAttribute.array[ offset ] = value.x;
  6930. customAttribute.array[ offset + 1 ] = value.y;
  6931. customAttribute.array[ offset + 2 ] = value.z;
  6932. customAttribute.array[ offset + 3 ] = value.w;
  6933. offset += 4;
  6934. }
  6935. }
  6936. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  6937. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  6938. }
  6939. }
  6940. }
  6941. };
  6942. function setRibbonBuffers ( geometry, hint ) {
  6943. var v, c, vertex, offset, color,
  6944. vertices = geometry.vertices,
  6945. colors = geometry.colors,
  6946. vl = vertices.length,
  6947. cl = colors.length,
  6948. vertexArray = geometry.__vertexArray,
  6949. colorArray = geometry.__colorArray,
  6950. dirtyVertices = geometry.__dirtyVertices,
  6951. dirtyColors = geometry.__dirtyColors;
  6952. if ( dirtyVertices ) {
  6953. for ( v = 0; v < vl; v ++ ) {
  6954. vertex = vertices[ v ].position;
  6955. offset = v * 3;
  6956. vertexArray[ offset ] = vertex.x;
  6957. vertexArray[ offset + 1 ] = vertex.y;
  6958. vertexArray[ offset + 2 ] = vertex.z;
  6959. }
  6960. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglVertexBuffer );
  6961. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  6962. }
  6963. if ( dirtyColors ) {
  6964. for ( c = 0; c < cl; c ++ ) {
  6965. color = colors[ c ];
  6966. offset = c * 3;
  6967. colorArray[ offset ] = color.r;
  6968. colorArray[ offset + 1 ] = color.g;
  6969. colorArray[ offset + 2 ] = color.b;
  6970. }
  6971. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometry.__webglColorBuffer );
  6972. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  6973. }
  6974. };
  6975. function setMeshBuffers( geometryGroup, object, hint, dispose, material ) {
  6976. if ( ! geometryGroup.__inittedArrays ) {
  6977. // console.log( object );
  6978. return;
  6979. }
  6980. var normalType = bufferGuessNormalType( material ),
  6981. vertexColorType = bufferGuessVertexColorType( material ),
  6982. uvType = bufferGuessUVType( material ),
  6983. needsSmoothNormals = ( normalType === THREE.SmoothShading );
  6984. var f, fl, fi, face,
  6985. vertexNormals, faceNormal, normal,
  6986. vertexColors, faceColor,
  6987. vertexTangents,
  6988. uv, uv2, v1, v2, v3, v4, t1, t2, t3, t4, n1, n2, n3, n4,
  6989. c1, c2, c3, c4,
  6990. sw1, sw2, sw3, sw4,
  6991. si1, si2, si3, si4,
  6992. sa1, sa2, sa3, sa4,
  6993. sb1, sb2, sb3, sb4,
  6994. m, ml, i, il,
  6995. vn, uvi, uv2i,
  6996. vk, vkl, vka,
  6997. nka, chf, faceVertexNormals,
  6998. a,
  6999. vertexIndex = 0,
  7000. offset = 0,
  7001. offset_uv = 0,
  7002. offset_uv2 = 0,
  7003. offset_face = 0,
  7004. offset_normal = 0,
  7005. offset_tangent = 0,
  7006. offset_line = 0,
  7007. offset_color = 0,
  7008. offset_skin = 0,
  7009. offset_morphTarget = 0,
  7010. offset_custom = 0,
  7011. offset_customSrc = 0,
  7012. value,
  7013. vertexArray = geometryGroup.__vertexArray,
  7014. uvArray = geometryGroup.__uvArray,
  7015. uv2Array = geometryGroup.__uv2Array,
  7016. normalArray = geometryGroup.__normalArray,
  7017. tangentArray = geometryGroup.__tangentArray,
  7018. colorArray = geometryGroup.__colorArray,
  7019. skinVertexAArray = geometryGroup.__skinVertexAArray,
  7020. skinVertexBArray = geometryGroup.__skinVertexBArray,
  7021. skinIndexArray = geometryGroup.__skinIndexArray,
  7022. skinWeightArray = geometryGroup.__skinWeightArray,
  7023. morphTargetsArrays = geometryGroup.__morphTargetsArrays,
  7024. morphNormalsArrays = geometryGroup.__morphNormalsArrays,
  7025. customAttributes = geometryGroup.__webglCustomAttributesList,
  7026. customAttribute,
  7027. faceArray = geometryGroup.__faceArray,
  7028. lineArray = geometryGroup.__lineArray,
  7029. geometry = object.geometry, // this is shared for all chunks
  7030. dirtyVertices = geometry.__dirtyVertices,
  7031. dirtyElements = geometry.__dirtyElements,
  7032. dirtyUvs = geometry.__dirtyUvs,
  7033. dirtyNormals = geometry.__dirtyNormals,
  7034. dirtyTangents = geometry.__dirtyTangents,
  7035. dirtyColors = geometry.__dirtyColors,
  7036. dirtyMorphTargets = geometry.__dirtyMorphTargets,
  7037. vertices = geometry.vertices,
  7038. chunk_faces3 = geometryGroup.faces3,
  7039. chunk_faces4 = geometryGroup.faces4,
  7040. obj_faces = geometry.faces,
  7041. obj_uvs = geometry.faceVertexUvs[ 0 ],
  7042. obj_uvs2 = geometry.faceVertexUvs[ 1 ],
  7043. obj_colors = geometry.colors,
  7044. obj_skinVerticesA = geometry.skinVerticesA,
  7045. obj_skinVerticesB = geometry.skinVerticesB,
  7046. obj_skinIndices = geometry.skinIndices,
  7047. obj_skinWeights = geometry.skinWeights,
  7048. morphTargets = geometry.morphTargets,
  7049. morphNormals = geometry.morphNormals;
  7050. if ( dirtyVertices ) {
  7051. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7052. face = obj_faces[ chunk_faces3[ f ] ];
  7053. v1 = vertices[ face.a ].position;
  7054. v2 = vertices[ face.b ].position;
  7055. v3 = vertices[ face.c ].position;
  7056. vertexArray[ offset ] = v1.x;
  7057. vertexArray[ offset + 1 ] = v1.y;
  7058. vertexArray[ offset + 2 ] = v1.z;
  7059. vertexArray[ offset + 3 ] = v2.x;
  7060. vertexArray[ offset + 4 ] = v2.y;
  7061. vertexArray[ offset + 5 ] = v2.z;
  7062. vertexArray[ offset + 6 ] = v3.x;
  7063. vertexArray[ offset + 7 ] = v3.y;
  7064. vertexArray[ offset + 8 ] = v3.z;
  7065. offset += 9;
  7066. }
  7067. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7068. face = obj_faces[ chunk_faces4[ f ] ];
  7069. v1 = vertices[ face.a ].position;
  7070. v2 = vertices[ face.b ].position;
  7071. v3 = vertices[ face.c ].position;
  7072. v4 = vertices[ face.d ].position;
  7073. vertexArray[ offset ] = v1.x;
  7074. vertexArray[ offset + 1 ] = v1.y;
  7075. vertexArray[ offset + 2 ] = v1.z;
  7076. vertexArray[ offset + 3 ] = v2.x;
  7077. vertexArray[ offset + 4 ] = v2.y;
  7078. vertexArray[ offset + 5 ] = v2.z;
  7079. vertexArray[ offset + 6 ] = v3.x;
  7080. vertexArray[ offset + 7 ] = v3.y;
  7081. vertexArray[ offset + 8 ] = v3.z;
  7082. vertexArray[ offset + 9 ] = v4.x;
  7083. vertexArray[ offset + 10 ] = v4.y;
  7084. vertexArray[ offset + 11 ] = v4.z;
  7085. offset += 12;
  7086. }
  7087. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  7088. _gl.bufferData( _gl.ARRAY_BUFFER, vertexArray, hint );
  7089. }
  7090. if ( dirtyMorphTargets ) {
  7091. for ( vk = 0, vkl = morphTargets.length; vk < vkl; vk ++ ) {
  7092. offset_morphTarget = 0;
  7093. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7094. chf = chunk_faces3[ f ];
  7095. face = obj_faces[ chf ];
  7096. // morph positions
  7097. v1 = morphTargets[ vk ].vertices[ face.a ].position;
  7098. v2 = morphTargets[ vk ].vertices[ face.b ].position;
  7099. v3 = morphTargets[ vk ].vertices[ face.c ].position;
  7100. vka = morphTargetsArrays[ vk ];
  7101. vka[ offset_morphTarget ] = v1.x;
  7102. vka[ offset_morphTarget + 1 ] = v1.y;
  7103. vka[ offset_morphTarget + 2 ] = v1.z;
  7104. vka[ offset_morphTarget + 3 ] = v2.x;
  7105. vka[ offset_morphTarget + 4 ] = v2.y;
  7106. vka[ offset_morphTarget + 5 ] = v2.z;
  7107. vka[ offset_morphTarget + 6 ] = v3.x;
  7108. vka[ offset_morphTarget + 7 ] = v3.y;
  7109. vka[ offset_morphTarget + 8 ] = v3.z;
  7110. // morph normals
  7111. if ( material.morphNormals ) {
  7112. if ( needsSmoothNormals ) {
  7113. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  7114. n1 = faceVertexNormals.a;
  7115. n2 = faceVertexNormals.b;
  7116. n3 = faceVertexNormals.c;
  7117. } else {
  7118. n1 = morphNormals[ vk ].faceNormals[ chf ];
  7119. n2 = n1;
  7120. n3 = n1;
  7121. }
  7122. nka = morphNormalsArrays[ vk ];
  7123. nka[ offset_morphTarget ] = n1.x;
  7124. nka[ offset_morphTarget + 1 ] = n1.y;
  7125. nka[ offset_morphTarget + 2 ] = n1.z;
  7126. nka[ offset_morphTarget + 3 ] = n2.x;
  7127. nka[ offset_morphTarget + 4 ] = n2.y;
  7128. nka[ offset_morphTarget + 5 ] = n2.z;
  7129. nka[ offset_morphTarget + 6 ] = n3.x;
  7130. nka[ offset_morphTarget + 7 ] = n3.y;
  7131. nka[ offset_morphTarget + 8 ] = n3.z;
  7132. }
  7133. //
  7134. offset_morphTarget += 9;
  7135. }
  7136. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7137. chf = chunk_faces4[ f ];
  7138. face = obj_faces[ chf ];
  7139. // morph positions
  7140. v1 = morphTargets[ vk ].vertices[ face.a ].position;
  7141. v2 = morphTargets[ vk ].vertices[ face.b ].position;
  7142. v3 = morphTargets[ vk ].vertices[ face.c ].position;
  7143. v4 = morphTargets[ vk ].vertices[ face.d ].position;
  7144. vka = morphTargetsArrays[ vk ];
  7145. vka[ offset_morphTarget ] = v1.x;
  7146. vka[ offset_morphTarget + 1 ] = v1.y;
  7147. vka[ offset_morphTarget + 2 ] = v1.z;
  7148. vka[ offset_morphTarget + 3 ] = v2.x;
  7149. vka[ offset_morphTarget + 4 ] = v2.y;
  7150. vka[ offset_morphTarget + 5 ] = v2.z;
  7151. vka[ offset_morphTarget + 6 ] = v3.x;
  7152. vka[ offset_morphTarget + 7 ] = v3.y;
  7153. vka[ offset_morphTarget + 8 ] = v3.z;
  7154. vka[ offset_morphTarget + 9 ] = v4.x;
  7155. vka[ offset_morphTarget + 10 ] = v4.y;
  7156. vka[ offset_morphTarget + 11 ] = v4.z;
  7157. // morph normals
  7158. if ( material.morphNormals ) {
  7159. if ( needsSmoothNormals ) {
  7160. faceVertexNormals = morphNormals[ vk ].vertexNormals[ chf ];
  7161. n1 = faceVertexNormals.a;
  7162. n2 = faceVertexNormals.b;
  7163. n3 = faceVertexNormals.c;
  7164. n4 = faceVertexNormals.d;
  7165. } else {
  7166. n1 = morphNormals[ vk ].faceNormals[ chf ];
  7167. n2 = n1;
  7168. n3 = n1;
  7169. n4 = n1;
  7170. }
  7171. nka = morphNormalsArrays[ vk ];
  7172. nka[ offset_morphTarget ] = n1.x;
  7173. nka[ offset_morphTarget + 1 ] = n1.y;
  7174. nka[ offset_morphTarget + 2 ] = n1.z;
  7175. nka[ offset_morphTarget + 3 ] = n2.x;
  7176. nka[ offset_morphTarget + 4 ] = n2.y;
  7177. nka[ offset_morphTarget + 5 ] = n2.z;
  7178. nka[ offset_morphTarget + 6 ] = n3.x;
  7179. nka[ offset_morphTarget + 7 ] = n3.y;
  7180. nka[ offset_morphTarget + 8 ] = n3.z;
  7181. nka[ offset_morphTarget + 9 ] = n4.x;
  7182. nka[ offset_morphTarget + 10 ] = n4.y;
  7183. nka[ offset_morphTarget + 11 ] = n4.z;
  7184. }
  7185. //
  7186. offset_morphTarget += 12;
  7187. }
  7188. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ vk ] );
  7189. _gl.bufferData( _gl.ARRAY_BUFFER, morphTargetsArrays[ vk ], hint );
  7190. if ( material.morphNormals ) {
  7191. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ vk ] );
  7192. _gl.bufferData( _gl.ARRAY_BUFFER, morphNormalsArrays[ vk ], hint );
  7193. }
  7194. }
  7195. }
  7196. if ( obj_skinWeights.length ) {
  7197. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7198. face = obj_faces[ chunk_faces3[ f ] ];
  7199. // weights
  7200. sw1 = obj_skinWeights[ face.a ];
  7201. sw2 = obj_skinWeights[ face.b ];
  7202. sw3 = obj_skinWeights[ face.c ];
  7203. skinWeightArray[ offset_skin ] = sw1.x;
  7204. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  7205. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  7206. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  7207. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  7208. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  7209. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  7210. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  7211. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  7212. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  7213. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  7214. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  7215. // indices
  7216. si1 = obj_skinIndices[ face.a ];
  7217. si2 = obj_skinIndices[ face.b ];
  7218. si3 = obj_skinIndices[ face.c ];
  7219. skinIndexArray[ offset_skin ] = si1.x;
  7220. skinIndexArray[ offset_skin + 1 ] = si1.y;
  7221. skinIndexArray[ offset_skin + 2 ] = si1.z;
  7222. skinIndexArray[ offset_skin + 3 ] = si1.w;
  7223. skinIndexArray[ offset_skin + 4 ] = si2.x;
  7224. skinIndexArray[ offset_skin + 5 ] = si2.y;
  7225. skinIndexArray[ offset_skin + 6 ] = si2.z;
  7226. skinIndexArray[ offset_skin + 7 ] = si2.w;
  7227. skinIndexArray[ offset_skin + 8 ] = si3.x;
  7228. skinIndexArray[ offset_skin + 9 ] = si3.y;
  7229. skinIndexArray[ offset_skin + 10 ] = si3.z;
  7230. skinIndexArray[ offset_skin + 11 ] = si3.w;
  7231. // vertices A
  7232. sa1 = obj_skinVerticesA[ face.a ];
  7233. sa2 = obj_skinVerticesA[ face.b ];
  7234. sa3 = obj_skinVerticesA[ face.c ];
  7235. skinVertexAArray[ offset_skin ] = sa1.x;
  7236. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  7237. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  7238. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7239. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  7240. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  7241. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  7242. skinVertexAArray[ offset_skin + 7 ] = 1;
  7243. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  7244. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  7245. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  7246. skinVertexAArray[ offset_skin + 11 ] = 1;
  7247. // vertices B
  7248. sb1 = obj_skinVerticesB[ face.a ];
  7249. sb2 = obj_skinVerticesB[ face.b ];
  7250. sb3 = obj_skinVerticesB[ face.c ];
  7251. skinVertexBArray[ offset_skin ] = sb1.x;
  7252. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  7253. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  7254. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7255. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  7256. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  7257. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  7258. skinVertexBArray[ offset_skin + 7 ] = 1;
  7259. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  7260. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  7261. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  7262. skinVertexBArray[ offset_skin + 11 ] = 1;
  7263. offset_skin += 12;
  7264. }
  7265. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7266. face = obj_faces[ chunk_faces4[ f ] ];
  7267. // weights
  7268. sw1 = obj_skinWeights[ face.a ];
  7269. sw2 = obj_skinWeights[ face.b ];
  7270. sw3 = obj_skinWeights[ face.c ];
  7271. sw4 = obj_skinWeights[ face.d ];
  7272. skinWeightArray[ offset_skin ] = sw1.x;
  7273. skinWeightArray[ offset_skin + 1 ] = sw1.y;
  7274. skinWeightArray[ offset_skin + 2 ] = sw1.z;
  7275. skinWeightArray[ offset_skin + 3 ] = sw1.w;
  7276. skinWeightArray[ offset_skin + 4 ] = sw2.x;
  7277. skinWeightArray[ offset_skin + 5 ] = sw2.y;
  7278. skinWeightArray[ offset_skin + 6 ] = sw2.z;
  7279. skinWeightArray[ offset_skin + 7 ] = sw2.w;
  7280. skinWeightArray[ offset_skin + 8 ] = sw3.x;
  7281. skinWeightArray[ offset_skin + 9 ] = sw3.y;
  7282. skinWeightArray[ offset_skin + 10 ] = sw3.z;
  7283. skinWeightArray[ offset_skin + 11 ] = sw3.w;
  7284. skinWeightArray[ offset_skin + 12 ] = sw4.x;
  7285. skinWeightArray[ offset_skin + 13 ] = sw4.y;
  7286. skinWeightArray[ offset_skin + 14 ] = sw4.z;
  7287. skinWeightArray[ offset_skin + 15 ] = sw4.w;
  7288. // indices
  7289. si1 = obj_skinIndices[ face.a ];
  7290. si2 = obj_skinIndices[ face.b ];
  7291. si3 = obj_skinIndices[ face.c ];
  7292. si4 = obj_skinIndices[ face.d ];
  7293. skinIndexArray[ offset_skin ] = si1.x;
  7294. skinIndexArray[ offset_skin + 1 ] = si1.y;
  7295. skinIndexArray[ offset_skin + 2 ] = si1.z;
  7296. skinIndexArray[ offset_skin + 3 ] = si1.w;
  7297. skinIndexArray[ offset_skin + 4 ] = si2.x;
  7298. skinIndexArray[ offset_skin + 5 ] = si2.y;
  7299. skinIndexArray[ offset_skin + 6 ] = si2.z;
  7300. skinIndexArray[ offset_skin + 7 ] = si2.w;
  7301. skinIndexArray[ offset_skin + 8 ] = si3.x;
  7302. skinIndexArray[ offset_skin + 9 ] = si3.y;
  7303. skinIndexArray[ offset_skin + 10 ] = si3.z;
  7304. skinIndexArray[ offset_skin + 11 ] = si3.w;
  7305. skinIndexArray[ offset_skin + 12 ] = si4.x;
  7306. skinIndexArray[ offset_skin + 13 ] = si4.y;
  7307. skinIndexArray[ offset_skin + 14 ] = si4.z;
  7308. skinIndexArray[ offset_skin + 15 ] = si4.w;
  7309. // vertices A
  7310. sa1 = obj_skinVerticesA[ face.a ];
  7311. sa2 = obj_skinVerticesA[ face.b ];
  7312. sa3 = obj_skinVerticesA[ face.c ];
  7313. sa4 = obj_skinVerticesA[ face.d ];
  7314. skinVertexAArray[ offset_skin ] = sa1.x;
  7315. skinVertexAArray[ offset_skin + 1 ] = sa1.y;
  7316. skinVertexAArray[ offset_skin + 2 ] = sa1.z;
  7317. skinVertexAArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7318. skinVertexAArray[ offset_skin + 4 ] = sa2.x;
  7319. skinVertexAArray[ offset_skin + 5 ] = sa2.y;
  7320. skinVertexAArray[ offset_skin + 6 ] = sa2.z;
  7321. skinVertexAArray[ offset_skin + 7 ] = 1;
  7322. skinVertexAArray[ offset_skin + 8 ] = sa3.x;
  7323. skinVertexAArray[ offset_skin + 9 ] = sa3.y;
  7324. skinVertexAArray[ offset_skin + 10 ] = sa3.z;
  7325. skinVertexAArray[ offset_skin + 11 ] = 1;
  7326. skinVertexAArray[ offset_skin + 12 ] = sa4.x;
  7327. skinVertexAArray[ offset_skin + 13 ] = sa4.y;
  7328. skinVertexAArray[ offset_skin + 14 ] = sa4.z;
  7329. skinVertexAArray[ offset_skin + 15 ] = 1;
  7330. // vertices B
  7331. sb1 = obj_skinVerticesB[ face.a ];
  7332. sb2 = obj_skinVerticesB[ face.b ];
  7333. sb3 = obj_skinVerticesB[ face.c ];
  7334. sb4 = obj_skinVerticesB[ face.d ];
  7335. skinVertexBArray[ offset_skin ] = sb1.x;
  7336. skinVertexBArray[ offset_skin + 1 ] = sb1.y;
  7337. skinVertexBArray[ offset_skin + 2 ] = sb1.z;
  7338. skinVertexBArray[ offset_skin + 3 ] = 1; // pad for faster vertex shader
  7339. skinVertexBArray[ offset_skin + 4 ] = sb2.x;
  7340. skinVertexBArray[ offset_skin + 5 ] = sb2.y;
  7341. skinVertexBArray[ offset_skin + 6 ] = sb2.z;
  7342. skinVertexBArray[ offset_skin + 7 ] = 1;
  7343. skinVertexBArray[ offset_skin + 8 ] = sb3.x;
  7344. skinVertexBArray[ offset_skin + 9 ] = sb3.y;
  7345. skinVertexBArray[ offset_skin + 10 ] = sb3.z;
  7346. skinVertexBArray[ offset_skin + 11 ] = 1;
  7347. skinVertexBArray[ offset_skin + 12 ] = sb4.x;
  7348. skinVertexBArray[ offset_skin + 13 ] = sb4.y;
  7349. skinVertexBArray[ offset_skin + 14 ] = sb4.z;
  7350. skinVertexBArray[ offset_skin + 15 ] = 1;
  7351. offset_skin += 16;
  7352. }
  7353. if ( offset_skin > 0 ) {
  7354. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  7355. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexAArray, hint );
  7356. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  7357. _gl.bufferData( _gl.ARRAY_BUFFER, skinVertexBArray, hint );
  7358. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  7359. _gl.bufferData( _gl.ARRAY_BUFFER, skinIndexArray, hint );
  7360. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  7361. _gl.bufferData( _gl.ARRAY_BUFFER, skinWeightArray, hint );
  7362. }
  7363. }
  7364. if ( dirtyColors && vertexColorType ) {
  7365. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7366. face = obj_faces[ chunk_faces3[ f ] ];
  7367. vertexColors = face.vertexColors;
  7368. faceColor = face.color;
  7369. if ( vertexColors.length === 3 && vertexColorType === THREE.VertexColors ) {
  7370. c1 = vertexColors[ 0 ];
  7371. c2 = vertexColors[ 1 ];
  7372. c3 = vertexColors[ 2 ];
  7373. } else {
  7374. c1 = faceColor;
  7375. c2 = faceColor;
  7376. c3 = faceColor;
  7377. }
  7378. colorArray[ offset_color ] = c1.r;
  7379. colorArray[ offset_color + 1 ] = c1.g;
  7380. colorArray[ offset_color + 2 ] = c1.b;
  7381. colorArray[ offset_color + 3 ] = c2.r;
  7382. colorArray[ offset_color + 4 ] = c2.g;
  7383. colorArray[ offset_color + 5 ] = c2.b;
  7384. colorArray[ offset_color + 6 ] = c3.r;
  7385. colorArray[ offset_color + 7 ] = c3.g;
  7386. colorArray[ offset_color + 8 ] = c3.b;
  7387. offset_color += 9;
  7388. }
  7389. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7390. face = obj_faces[ chunk_faces4[ f ] ];
  7391. vertexColors = face.vertexColors;
  7392. faceColor = face.color;
  7393. if ( vertexColors.length === 4 && vertexColorType === THREE.VertexColors ) {
  7394. c1 = vertexColors[ 0 ];
  7395. c2 = vertexColors[ 1 ];
  7396. c3 = vertexColors[ 2 ];
  7397. c4 = vertexColors[ 3 ];
  7398. } else {
  7399. c1 = faceColor;
  7400. c2 = faceColor;
  7401. c3 = faceColor;
  7402. c4 = faceColor;
  7403. }
  7404. colorArray[ offset_color ] = c1.r;
  7405. colorArray[ offset_color + 1 ] = c1.g;
  7406. colorArray[ offset_color + 2 ] = c1.b;
  7407. colorArray[ offset_color + 3 ] = c2.r;
  7408. colorArray[ offset_color + 4 ] = c2.g;
  7409. colorArray[ offset_color + 5 ] = c2.b;
  7410. colorArray[ offset_color + 6 ] = c3.r;
  7411. colorArray[ offset_color + 7 ] = c3.g;
  7412. colorArray[ offset_color + 8 ] = c3.b;
  7413. colorArray[ offset_color + 9 ] = c4.r;
  7414. colorArray[ offset_color + 10 ] = c4.g;
  7415. colorArray[ offset_color + 11 ] = c4.b;
  7416. offset_color += 12;
  7417. }
  7418. if ( offset_color > 0 ) {
  7419. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  7420. _gl.bufferData( _gl.ARRAY_BUFFER, colorArray, hint );
  7421. }
  7422. }
  7423. if ( dirtyTangents && geometry.hasTangents ) {
  7424. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7425. face = obj_faces[ chunk_faces3[ f ] ];
  7426. vertexTangents = face.vertexTangents;
  7427. t1 = vertexTangents[ 0 ];
  7428. t2 = vertexTangents[ 1 ];
  7429. t3 = vertexTangents[ 2 ];
  7430. tangentArray[ offset_tangent ] = t1.x;
  7431. tangentArray[ offset_tangent + 1 ] = t1.y;
  7432. tangentArray[ offset_tangent + 2 ] = t1.z;
  7433. tangentArray[ offset_tangent + 3 ] = t1.w;
  7434. tangentArray[ offset_tangent + 4 ] = t2.x;
  7435. tangentArray[ offset_tangent + 5 ] = t2.y;
  7436. tangentArray[ offset_tangent + 6 ] = t2.z;
  7437. tangentArray[ offset_tangent + 7 ] = t2.w;
  7438. tangentArray[ offset_tangent + 8 ] = t3.x;
  7439. tangentArray[ offset_tangent + 9 ] = t3.y;
  7440. tangentArray[ offset_tangent + 10 ] = t3.z;
  7441. tangentArray[ offset_tangent + 11 ] = t3.w;
  7442. offset_tangent += 12;
  7443. }
  7444. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7445. face = obj_faces[ chunk_faces4[ f ] ];
  7446. vertexTangents = face.vertexTangents;
  7447. t1 = vertexTangents[ 0 ];
  7448. t2 = vertexTangents[ 1 ];
  7449. t3 = vertexTangents[ 2 ];
  7450. t4 = vertexTangents[ 3 ];
  7451. tangentArray[ offset_tangent ] = t1.x;
  7452. tangentArray[ offset_tangent + 1 ] = t1.y;
  7453. tangentArray[ offset_tangent + 2 ] = t1.z;
  7454. tangentArray[ offset_tangent + 3 ] = t1.w;
  7455. tangentArray[ offset_tangent + 4 ] = t2.x;
  7456. tangentArray[ offset_tangent + 5 ] = t2.y;
  7457. tangentArray[ offset_tangent + 6 ] = t2.z;
  7458. tangentArray[ offset_tangent + 7 ] = t2.w;
  7459. tangentArray[ offset_tangent + 8 ] = t3.x;
  7460. tangentArray[ offset_tangent + 9 ] = t3.y;
  7461. tangentArray[ offset_tangent + 10 ] = t3.z;
  7462. tangentArray[ offset_tangent + 11 ] = t3.w;
  7463. tangentArray[ offset_tangent + 12 ] = t4.x;
  7464. tangentArray[ offset_tangent + 13 ] = t4.y;
  7465. tangentArray[ offset_tangent + 14 ] = t4.z;
  7466. tangentArray[ offset_tangent + 15 ] = t4.w;
  7467. offset_tangent += 16;
  7468. }
  7469. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  7470. _gl.bufferData( _gl.ARRAY_BUFFER, tangentArray, hint );
  7471. }
  7472. if ( dirtyNormals && normalType ) {
  7473. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7474. face = obj_faces[ chunk_faces3[ f ] ];
  7475. vertexNormals = face.vertexNormals;
  7476. faceNormal = face.normal;
  7477. if ( vertexNormals.length === 3 && needsSmoothNormals ) {
  7478. for ( i = 0; i < 3; i ++ ) {
  7479. vn = vertexNormals[ i ];
  7480. normalArray[ offset_normal ] = vn.x;
  7481. normalArray[ offset_normal + 1 ] = vn.y;
  7482. normalArray[ offset_normal + 2 ] = vn.z;
  7483. offset_normal += 3;
  7484. }
  7485. } else {
  7486. for ( i = 0; i < 3; i ++ ) {
  7487. normalArray[ offset_normal ] = faceNormal.x;
  7488. normalArray[ offset_normal + 1 ] = faceNormal.y;
  7489. normalArray[ offset_normal + 2 ] = faceNormal.z;
  7490. offset_normal += 3;
  7491. }
  7492. }
  7493. }
  7494. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7495. face = obj_faces[ chunk_faces4[ f ] ];
  7496. vertexNormals = face.vertexNormals;
  7497. faceNormal = face.normal;
  7498. if ( vertexNormals.length === 4 && needsSmoothNormals ) {
  7499. for ( i = 0; i < 4; i ++ ) {
  7500. vn = vertexNormals[ i ];
  7501. normalArray[ offset_normal ] = vn.x;
  7502. normalArray[ offset_normal + 1 ] = vn.y;
  7503. normalArray[ offset_normal + 2 ] = vn.z;
  7504. offset_normal += 3;
  7505. }
  7506. } else {
  7507. for ( i = 0; i < 4; i ++ ) {
  7508. normalArray[ offset_normal ] = faceNormal.x;
  7509. normalArray[ offset_normal + 1 ] = faceNormal.y;
  7510. normalArray[ offset_normal + 2 ] = faceNormal.z;
  7511. offset_normal += 3;
  7512. }
  7513. }
  7514. }
  7515. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  7516. _gl.bufferData( _gl.ARRAY_BUFFER, normalArray, hint );
  7517. }
  7518. if ( dirtyUvs && obj_uvs && uvType ) {
  7519. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7520. fi = chunk_faces3[ f ];
  7521. face = obj_faces[ fi ];
  7522. uv = obj_uvs[ fi ];
  7523. if ( uv === undefined ) continue;
  7524. for ( i = 0; i < 3; i ++ ) {
  7525. uvi = uv[ i ];
  7526. uvArray[ offset_uv ] = uvi.u;
  7527. uvArray[ offset_uv + 1 ] = uvi.v;
  7528. offset_uv += 2;
  7529. }
  7530. }
  7531. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7532. fi = chunk_faces4[ f ];
  7533. face = obj_faces[ fi ];
  7534. uv = obj_uvs[ fi ];
  7535. if ( uv === undefined ) continue;
  7536. for ( i = 0; i < 4; i ++ ) {
  7537. uvi = uv[ i ];
  7538. uvArray[ offset_uv ] = uvi.u;
  7539. uvArray[ offset_uv + 1 ] = uvi.v;
  7540. offset_uv += 2;
  7541. }
  7542. }
  7543. if ( offset_uv > 0 ) {
  7544. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  7545. _gl.bufferData( _gl.ARRAY_BUFFER, uvArray, hint );
  7546. }
  7547. }
  7548. if ( dirtyUvs && obj_uvs2 && uvType ) {
  7549. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7550. fi = chunk_faces3[ f ];
  7551. face = obj_faces[ fi ];
  7552. uv2 = obj_uvs2[ fi ];
  7553. if ( uv2 === undefined ) continue;
  7554. for ( i = 0; i < 3; i ++ ) {
  7555. uv2i = uv2[ i ];
  7556. uv2Array[ offset_uv2 ] = uv2i.u;
  7557. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  7558. offset_uv2 += 2;
  7559. }
  7560. }
  7561. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7562. fi = chunk_faces4[ f ];
  7563. face = obj_faces[ fi ];
  7564. uv2 = obj_uvs2[ fi ];
  7565. if ( uv2 === undefined ) continue;
  7566. for ( i = 0; i < 4; i ++ ) {
  7567. uv2i = uv2[ i ];
  7568. uv2Array[ offset_uv2 ] = uv2i.u;
  7569. uv2Array[ offset_uv2 + 1 ] = uv2i.v;
  7570. offset_uv2 += 2;
  7571. }
  7572. }
  7573. if ( offset_uv2 > 0 ) {
  7574. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  7575. _gl.bufferData( _gl.ARRAY_BUFFER, uv2Array, hint );
  7576. }
  7577. }
  7578. if ( dirtyElements ) {
  7579. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7580. face = obj_faces[ chunk_faces3[ f ] ];
  7581. faceArray[ offset_face ] = vertexIndex;
  7582. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  7583. faceArray[ offset_face + 2 ] = vertexIndex + 2;
  7584. offset_face += 3;
  7585. lineArray[ offset_line ] = vertexIndex;
  7586. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  7587. lineArray[ offset_line + 2 ] = vertexIndex;
  7588. lineArray[ offset_line + 3 ] = vertexIndex + 2;
  7589. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  7590. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  7591. offset_line += 6;
  7592. vertexIndex += 3;
  7593. }
  7594. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7595. face = obj_faces[ chunk_faces4[ f ] ];
  7596. faceArray[ offset_face ] = vertexIndex;
  7597. faceArray[ offset_face + 1 ] = vertexIndex + 1;
  7598. faceArray[ offset_face + 2 ] = vertexIndex + 3;
  7599. faceArray[ offset_face + 3 ] = vertexIndex + 1;
  7600. faceArray[ offset_face + 4 ] = vertexIndex + 2;
  7601. faceArray[ offset_face + 5 ] = vertexIndex + 3;
  7602. offset_face += 6;
  7603. lineArray[ offset_line ] = vertexIndex;
  7604. lineArray[ offset_line + 1 ] = vertexIndex + 1;
  7605. lineArray[ offset_line + 2 ] = vertexIndex;
  7606. lineArray[ offset_line + 3 ] = vertexIndex + 3;
  7607. lineArray[ offset_line + 4 ] = vertexIndex + 1;
  7608. lineArray[ offset_line + 5 ] = vertexIndex + 2;
  7609. lineArray[ offset_line + 6 ] = vertexIndex + 2;
  7610. lineArray[ offset_line + 7 ] = vertexIndex + 3;
  7611. offset_line += 8;
  7612. vertexIndex += 4;
  7613. }
  7614. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  7615. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, faceArray, hint );
  7616. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  7617. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, lineArray, hint );
  7618. }
  7619. if ( customAttributes ) {
  7620. for ( i = 0, il = customAttributes.length; i < il; i ++ ) {
  7621. customAttribute = customAttributes[ i ];
  7622. if ( ! customAttribute.__original.needsUpdate ) continue;
  7623. offset_custom = 0;
  7624. offset_customSrc = 0;
  7625. if ( customAttribute.size === 1 ) {
  7626. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7627. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7628. face = obj_faces[ chunk_faces3[ f ] ];
  7629. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  7630. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  7631. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  7632. offset_custom += 3;
  7633. }
  7634. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7635. face = obj_faces[ chunk_faces4[ f ] ];
  7636. customAttribute.array[ offset_custom ] = customAttribute.value[ face.a ];
  7637. customAttribute.array[ offset_custom + 1 ] = customAttribute.value[ face.b ];
  7638. customAttribute.array[ offset_custom + 2 ] = customAttribute.value[ face.c ];
  7639. customAttribute.array[ offset_custom + 3 ] = customAttribute.value[ face.d ];
  7640. offset_custom += 4;
  7641. }
  7642. } else if ( customAttribute.boundTo === "faces" ) {
  7643. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7644. value = customAttribute.value[ chunk_faces3[ f ] ];
  7645. customAttribute.array[ offset_custom ] = value;
  7646. customAttribute.array[ offset_custom + 1 ] = value;
  7647. customAttribute.array[ offset_custom + 2 ] = value;
  7648. offset_custom += 3;
  7649. }
  7650. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7651. value = customAttribute.value[ chunk_faces4[ f ] ];
  7652. customAttribute.array[ offset_custom ] = value;
  7653. customAttribute.array[ offset_custom + 1 ] = value;
  7654. customAttribute.array[ offset_custom + 2 ] = value;
  7655. customAttribute.array[ offset_custom + 3 ] = value;
  7656. offset_custom += 4;
  7657. }
  7658. }
  7659. } else if ( customAttribute.size === 2 ) {
  7660. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7661. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7662. face = obj_faces[ chunk_faces3[ f ] ];
  7663. v1 = customAttribute.value[ face.a ];
  7664. v2 = customAttribute.value[ face.b ];
  7665. v3 = customAttribute.value[ face.c ];
  7666. customAttribute.array[ offset_custom ] = v1.x;
  7667. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7668. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7669. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7670. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7671. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7672. offset_custom += 6;
  7673. }
  7674. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7675. face = obj_faces[ chunk_faces4[ f ] ];
  7676. v1 = customAttribute.value[ face.a ];
  7677. v2 = customAttribute.value[ face.b ];
  7678. v3 = customAttribute.value[ face.c ];
  7679. v4 = customAttribute.value[ face.d ];
  7680. customAttribute.array[ offset_custom ] = v1.x;
  7681. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7682. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7683. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7684. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7685. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7686. customAttribute.array[ offset_custom + 6 ] = v4.x;
  7687. customAttribute.array[ offset_custom + 7 ] = v4.y;
  7688. offset_custom += 8;
  7689. }
  7690. } else if ( customAttribute.boundTo === "faces" ) {
  7691. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7692. value = customAttribute.value[ chunk_faces3[ f ] ];
  7693. v1 = value;
  7694. v2 = value;
  7695. v3 = value;
  7696. customAttribute.array[ offset_custom ] = v1.x;
  7697. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7698. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7699. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7700. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7701. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7702. offset_custom += 6;
  7703. }
  7704. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7705. value = customAttribute.value[ chunk_faces4[ f ] ];
  7706. v1 = value;
  7707. v2 = value;
  7708. v3 = value;
  7709. v4 = value;
  7710. customAttribute.array[ offset_custom ] = v1.x;
  7711. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7712. customAttribute.array[ offset_custom + 2 ] = v2.x;
  7713. customAttribute.array[ offset_custom + 3 ] = v2.y;
  7714. customAttribute.array[ offset_custom + 4 ] = v3.x;
  7715. customAttribute.array[ offset_custom + 5 ] = v3.y;
  7716. customAttribute.array[ offset_custom + 6 ] = v4.x;
  7717. customAttribute.array[ offset_custom + 7 ] = v4.y;
  7718. offset_custom += 8;
  7719. }
  7720. }
  7721. } else if ( customAttribute.size === 3 ) {
  7722. var pp;
  7723. if ( customAttribute.type === "c" ) {
  7724. pp = [ "r", "g", "b" ];
  7725. } else {
  7726. pp = [ "x", "y", "z" ];
  7727. }
  7728. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7729. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7730. face = obj_faces[ chunk_faces3[ f ] ];
  7731. v1 = customAttribute.value[ face.a ];
  7732. v2 = customAttribute.value[ face.b ];
  7733. v3 = customAttribute.value[ face.c ];
  7734. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7735. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7736. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7737. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7738. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7739. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7740. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7741. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7742. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7743. offset_custom += 9;
  7744. }
  7745. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7746. face = obj_faces[ chunk_faces4[ f ] ];
  7747. v1 = customAttribute.value[ face.a ];
  7748. v2 = customAttribute.value[ face.b ];
  7749. v3 = customAttribute.value[ face.c ];
  7750. v4 = customAttribute.value[ face.d ];
  7751. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7752. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7753. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7754. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7755. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7756. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7757. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7758. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7759. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7760. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  7761. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  7762. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  7763. offset_custom += 12;
  7764. }
  7765. } else if ( customAttribute.boundTo === "faces" ) {
  7766. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7767. value = customAttribute.value[ chunk_faces3[ f ] ];
  7768. v1 = value;
  7769. v2 = value;
  7770. v3 = value;
  7771. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7772. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7773. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7774. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7775. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7776. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7777. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7778. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7779. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7780. offset_custom += 9;
  7781. }
  7782. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7783. value = customAttribute.value[ chunk_faces4[ f ] ];
  7784. v1 = value;
  7785. v2 = value;
  7786. v3 = value;
  7787. v4 = value;
  7788. customAttribute.array[ offset_custom ] = v1[ pp[ 0 ] ];
  7789. customAttribute.array[ offset_custom + 1 ] = v1[ pp[ 1 ] ];
  7790. customAttribute.array[ offset_custom + 2 ] = v1[ pp[ 2 ] ];
  7791. customAttribute.array[ offset_custom + 3 ] = v2[ pp[ 0 ] ];
  7792. customAttribute.array[ offset_custom + 4 ] = v2[ pp[ 1 ] ];
  7793. customAttribute.array[ offset_custom + 5 ] = v2[ pp[ 2 ] ];
  7794. customAttribute.array[ offset_custom + 6 ] = v3[ pp[ 0 ] ];
  7795. customAttribute.array[ offset_custom + 7 ] = v3[ pp[ 1 ] ];
  7796. customAttribute.array[ offset_custom + 8 ] = v3[ pp[ 2 ] ];
  7797. customAttribute.array[ offset_custom + 9 ] = v4[ pp[ 0 ] ];
  7798. customAttribute.array[ offset_custom + 10 ] = v4[ pp[ 1 ] ];
  7799. customAttribute.array[ offset_custom + 11 ] = v4[ pp[ 2 ] ];
  7800. offset_custom += 12;
  7801. }
  7802. }
  7803. } else if ( customAttribute.size === 4 ) {
  7804. if ( customAttribute.boundTo === undefined || customAttribute.boundTo === "vertices" ) {
  7805. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7806. face = obj_faces[ chunk_faces3[ f ] ];
  7807. v1 = customAttribute.value[ face.a ];
  7808. v2 = customAttribute.value[ face.b ];
  7809. v3 = customAttribute.value[ face.c ];
  7810. customAttribute.array[ offset_custom ] = v1.x;
  7811. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7812. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7813. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7814. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7815. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7816. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7817. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7818. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7819. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7820. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7821. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7822. offset_custom += 12;
  7823. }
  7824. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7825. face = obj_faces[ chunk_faces4[ f ] ];
  7826. v1 = customAttribute.value[ face.a ];
  7827. v2 = customAttribute.value[ face.b ];
  7828. v3 = customAttribute.value[ face.c ];
  7829. v4 = customAttribute.value[ face.d ];
  7830. customAttribute.array[ offset_custom ] = v1.x;
  7831. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7832. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7833. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7834. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7835. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7836. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7837. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7838. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7839. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7840. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7841. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7842. customAttribute.array[ offset_custom + 12 ] = v4.x;
  7843. customAttribute.array[ offset_custom + 13 ] = v4.y;
  7844. customAttribute.array[ offset_custom + 14 ] = v4.z;
  7845. customAttribute.array[ offset_custom + 15 ] = v4.w;
  7846. offset_custom += 16;
  7847. }
  7848. } else if ( customAttribute.boundTo === "faces" ) {
  7849. for ( f = 0, fl = chunk_faces3.length; f < fl; f ++ ) {
  7850. value = customAttribute.value[ chunk_faces3[ f ] ];
  7851. v1 = value;
  7852. v2 = value;
  7853. v3 = value;
  7854. customAttribute.array[ offset_custom ] = v1.x;
  7855. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7856. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7857. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7858. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7859. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7860. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7861. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7862. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7863. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7864. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7865. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7866. offset_custom += 12;
  7867. }
  7868. for ( f = 0, fl = chunk_faces4.length; f < fl; f ++ ) {
  7869. value = customAttribute.value[ chunk_faces4[ f ] ];
  7870. v1 = value;
  7871. v2 = value;
  7872. v3 = value;
  7873. v4 = value;
  7874. customAttribute.array[ offset_custom ] = v1.x;
  7875. customAttribute.array[ offset_custom + 1 ] = v1.y;
  7876. customAttribute.array[ offset_custom + 2 ] = v1.z;
  7877. customAttribute.array[ offset_custom + 3 ] = v1.w;
  7878. customAttribute.array[ offset_custom + 4 ] = v2.x;
  7879. customAttribute.array[ offset_custom + 5 ] = v2.y;
  7880. customAttribute.array[ offset_custom + 6 ] = v2.z;
  7881. customAttribute.array[ offset_custom + 7 ] = v2.w;
  7882. customAttribute.array[ offset_custom + 8 ] = v3.x;
  7883. customAttribute.array[ offset_custom + 9 ] = v3.y;
  7884. customAttribute.array[ offset_custom + 10 ] = v3.z;
  7885. customAttribute.array[ offset_custom + 11 ] = v3.w;
  7886. customAttribute.array[ offset_custom + 12 ] = v4.x;
  7887. customAttribute.array[ offset_custom + 13 ] = v4.y;
  7888. customAttribute.array[ offset_custom + 14 ] = v4.z;
  7889. customAttribute.array[ offset_custom + 15 ] = v4.w;
  7890. offset_custom += 16;
  7891. }
  7892. }
  7893. }
  7894. _gl.bindBuffer( _gl.ARRAY_BUFFER, customAttribute.buffer );
  7895. _gl.bufferData( _gl.ARRAY_BUFFER, customAttribute.array, hint );
  7896. }
  7897. }
  7898. if ( dispose ) {
  7899. delete geometryGroup.__inittedArrays;
  7900. delete geometryGroup.__colorArray;
  7901. delete geometryGroup.__normalArray;
  7902. delete geometryGroup.__tangentArray;
  7903. delete geometryGroup.__uvArray;
  7904. delete geometryGroup.__uv2Array;
  7905. delete geometryGroup.__faceArray;
  7906. delete geometryGroup.__vertexArray;
  7907. delete geometryGroup.__lineArray;
  7908. delete geometryGroup.__skinVertexAArray;
  7909. delete geometryGroup.__skinVertexBArray;
  7910. delete geometryGroup.__skinIndexArray;
  7911. delete geometryGroup.__skinWeightArray;
  7912. }
  7913. };
  7914. // Buffer rendering
  7915. this.renderBufferImmediate = function ( object, program, shading ) {
  7916. if ( ! object.__webglVertexBuffer ) object.__webglVertexBuffer = _gl.createBuffer();
  7917. if ( ! object.__webglNormalBuffer ) object.__webglNormalBuffer = _gl.createBuffer();
  7918. if ( object.hasPos ) {
  7919. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglVertexBuffer );
  7920. _gl.bufferData( _gl.ARRAY_BUFFER, object.positionArray, _gl.DYNAMIC_DRAW );
  7921. _gl.enableVertexAttribArray( program.attributes.position );
  7922. _gl.vertexAttribPointer( program.attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  7923. }
  7924. if ( object.hasNormal ) {
  7925. _gl.bindBuffer( _gl.ARRAY_BUFFER, object.__webglNormalBuffer );
  7926. if ( shading === THREE.FlatShading ) {
  7927. var nx, ny, nz,
  7928. nax, nbx, ncx, nay, nby, ncy, naz, nbz, ncz,
  7929. normalArray,
  7930. i, il = object.count * 3;
  7931. for( i = 0; i < il; i += 9 ) {
  7932. normalArray = object.normalArray;
  7933. nax = normalArray[ i ];
  7934. nay = normalArray[ i + 1 ];
  7935. naz = normalArray[ i + 2 ];
  7936. nbx = normalArray[ i + 3 ];
  7937. nby = normalArray[ i + 4 ];
  7938. nbz = normalArray[ i + 5 ];
  7939. ncx = normalArray[ i + 6 ];
  7940. ncy = normalArray[ i + 7 ];
  7941. ncz = normalArray[ i + 8 ];
  7942. nx = ( nax + nbx + ncx ) / 3;
  7943. ny = ( nay + nby + ncy ) / 3;
  7944. nz = ( naz + nbz + ncz ) / 3;
  7945. normalArray[ i ] = nx;
  7946. normalArray[ i + 1 ] = ny;
  7947. normalArray[ i + 2 ] = nz;
  7948. normalArray[ i + 3 ] = nx;
  7949. normalArray[ i + 4 ] = ny;
  7950. normalArray[ i + 5 ] = nz;
  7951. normalArray[ i + 6 ] = nx;
  7952. normalArray[ i + 7 ] = ny;
  7953. normalArray[ i + 8 ] = nz;
  7954. }
  7955. }
  7956. _gl.bufferData( _gl.ARRAY_BUFFER, object.normalArray, _gl.DYNAMIC_DRAW );
  7957. _gl.enableVertexAttribArray( program.attributes.normal );
  7958. _gl.vertexAttribPointer( program.attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  7959. }
  7960. _gl.drawArrays( _gl.TRIANGLES, 0, object.count );
  7961. object.count = 0;
  7962. };
  7963. this.renderBufferDirect = function ( camera, lights, fog, material, geometryGroup, object ) {
  7964. if ( material.opacity === 0 ) return;
  7965. var program, attributes, linewidth, primitives, a, attribute;
  7966. program = setProgram( camera, lights, fog, material, object );
  7967. attributes = program.attributes;
  7968. var updateBuffers = false,
  7969. wireframeBit = material.wireframe ? 1 : 0,
  7970. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  7971. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  7972. _currentGeometryGroupHash = geometryGroupHash;
  7973. updateBuffers = true;
  7974. }
  7975. // render mesh
  7976. if ( object instanceof THREE.Mesh ) {
  7977. var offsets = geometryGroup.offsets;
  7978. for ( var i = 0, il = offsets.length; i < il; ++ i ) {
  7979. if ( updateBuffers ) {
  7980. // vertices
  7981. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexPositionBuffer );
  7982. _gl.vertexAttribPointer( attributes.position, geometryGroup.vertexPositionBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 );
  7983. // normals
  7984. if ( attributes.normal >= 0 && geometryGroup.vertexNormalBuffer ) {
  7985. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexNormalBuffer );
  7986. _gl.vertexAttribPointer( attributes.normal, geometryGroup.vertexNormalBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 3 );
  7987. }
  7988. // uvs
  7989. if ( attributes.uv >= 0 && geometryGroup.vertexUvBuffer ) {
  7990. if ( geometryGroup.vertexUvBuffer ) {
  7991. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexUvBuffer );
  7992. _gl.vertexAttribPointer( attributes.uv, geometryGroup.vertexUvBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 2 );
  7993. _gl.enableVertexAttribArray( attributes.uv );
  7994. } else {
  7995. _gl.disableVertexAttribArray( attributes.uv );
  7996. }
  7997. }
  7998. // colors
  7999. if ( attributes.color >= 0 && geometryGroup.vertexColorBuffer ) {
  8000. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.vertexColorBuffer );
  8001. _gl.vertexAttribPointer( attributes.color, geometryGroup.vertexColorBuffer.itemSize, _gl.FLOAT, false, 0, offsets[ i ].index * 4 * 4 );
  8002. }
  8003. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.vertexIndexBuffer );
  8004. }
  8005. // render indexed triangles
  8006. _gl.drawElements( _gl.TRIANGLES, offsets[ i ].count, _gl.UNSIGNED_SHORT, offsets[ i ].start * 2 ); // 2 = Uint16
  8007. _this.info.render.calls ++;
  8008. _this.info.render.vertices += offsets[ i ].count; // not really true, here vertices can be shared
  8009. _this.info.render.faces += offsets[ i ].count / 3;
  8010. }
  8011. }
  8012. };
  8013. this.renderBuffer = function ( camera, lights, fog, material, geometryGroup, object ) {
  8014. if ( material.opacity === 0 ) return;
  8015. var program, attributes, linewidth, primitives, a, attribute, i, il;
  8016. program = setProgram( camera, lights, fog, material, object );
  8017. attributes = program.attributes;
  8018. var updateBuffers = false,
  8019. wireframeBit = material.wireframe ? 1 : 0,
  8020. geometryGroupHash = ( geometryGroup.id * 0xffffff ) + ( program.id * 2 ) + wireframeBit;
  8021. if ( geometryGroupHash !== _currentGeometryGroupHash ) {
  8022. _currentGeometryGroupHash = geometryGroupHash;
  8023. updateBuffers = true;
  8024. }
  8025. // vertices
  8026. if ( !material.morphTargets && attributes.position >= 0 ) {
  8027. if ( updateBuffers ) {
  8028. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  8029. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8030. }
  8031. } else {
  8032. if ( object.morphTargetBase ) {
  8033. setupMorphTargets( material, geometryGroup, object );
  8034. }
  8035. }
  8036. if ( updateBuffers ) {
  8037. // custom attributes
  8038. // Use the per-geometryGroup custom attribute arrays which are setup in initMeshBuffers
  8039. if ( geometryGroup.__webglCustomAttributesList ) {
  8040. for ( i = 0, il = geometryGroup.__webglCustomAttributesList.length; i < il; i ++ ) {
  8041. attribute = geometryGroup.__webglCustomAttributesList[ i ];
  8042. if( attributes[ attribute.buffer.belongsToAttribute ] >= 0 ) {
  8043. _gl.bindBuffer( _gl.ARRAY_BUFFER, attribute.buffer );
  8044. _gl.vertexAttribPointer( attributes[ attribute.buffer.belongsToAttribute ], attribute.size, _gl.FLOAT, false, 0, 0 );
  8045. }
  8046. }
  8047. }
  8048. // colors
  8049. if ( attributes.color >= 0 ) {
  8050. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglColorBuffer );
  8051. _gl.vertexAttribPointer( attributes.color, 3, _gl.FLOAT, false, 0, 0 );
  8052. }
  8053. // normals
  8054. if ( attributes.normal >= 0 ) {
  8055. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglNormalBuffer );
  8056. _gl.vertexAttribPointer( attributes.normal, 3, _gl.FLOAT, false, 0, 0 );
  8057. }
  8058. // tangents
  8059. if ( attributes.tangent >= 0 ) {
  8060. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglTangentBuffer );
  8061. _gl.vertexAttribPointer( attributes.tangent, 4, _gl.FLOAT, false, 0, 0 );
  8062. }
  8063. // uvs
  8064. if ( attributes.uv >= 0 ) {
  8065. if ( geometryGroup.__webglUVBuffer ) {
  8066. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUVBuffer );
  8067. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 0, 0 );
  8068. _gl.enableVertexAttribArray( attributes.uv );
  8069. } else {
  8070. _gl.disableVertexAttribArray( attributes.uv );
  8071. }
  8072. }
  8073. if ( attributes.uv2 >= 0 ) {
  8074. if ( geometryGroup.__webglUV2Buffer ) {
  8075. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglUV2Buffer );
  8076. _gl.vertexAttribPointer( attributes.uv2, 2, _gl.FLOAT, false, 0, 0 );
  8077. _gl.enableVertexAttribArray( attributes.uv2 );
  8078. } else {
  8079. _gl.disableVertexAttribArray( attributes.uv2 );
  8080. }
  8081. }
  8082. if ( material.skinning &&
  8083. attributes.skinVertexA >= 0 && attributes.skinVertexB >= 0 &&
  8084. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  8085. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexABuffer );
  8086. _gl.vertexAttribPointer( attributes.skinVertexA, 4, _gl.FLOAT, false, 0, 0 );
  8087. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinVertexBBuffer );
  8088. _gl.vertexAttribPointer( attributes.skinVertexB, 4, _gl.FLOAT, false, 0, 0 );
  8089. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinIndicesBuffer );
  8090. _gl.vertexAttribPointer( attributes.skinIndex, 4, _gl.FLOAT, false, 0, 0 );
  8091. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglSkinWeightsBuffer );
  8092. _gl.vertexAttribPointer( attributes.skinWeight, 4, _gl.FLOAT, false, 0, 0 );
  8093. }
  8094. }
  8095. // render mesh
  8096. if ( object instanceof THREE.Mesh ) {
  8097. // wireframe
  8098. if ( material.wireframe ) {
  8099. setLineWidth( material.wireframeLinewidth );
  8100. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglLineBuffer );
  8101. _gl.drawElements( _gl.LINES, geometryGroup.__webglLineCount, _gl.UNSIGNED_SHORT, 0 );
  8102. // triangles
  8103. } else {
  8104. if ( updateBuffers ) _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, geometryGroup.__webglFaceBuffer );
  8105. _gl.drawElements( _gl.TRIANGLES, geometryGroup.__webglFaceCount, _gl.UNSIGNED_SHORT, 0 );
  8106. }
  8107. _this.info.render.calls ++;
  8108. _this.info.render.vertices += geometryGroup.__webglFaceCount;
  8109. _this.info.render.faces += geometryGroup.__webglFaceCount / 3;
  8110. // render lines
  8111. } else if ( object instanceof THREE.Line ) {
  8112. primitives = ( object.type === THREE.LineStrip ) ? _gl.LINE_STRIP : _gl.LINES;
  8113. setLineWidth( material.linewidth );
  8114. _gl.drawArrays( primitives, 0, geometryGroup.__webglLineCount );
  8115. _this.info.render.calls ++;
  8116. // render particles
  8117. } else if ( object instanceof THREE.ParticleSystem ) {
  8118. _gl.drawArrays( _gl.POINTS, 0, geometryGroup.__webglParticleCount );
  8119. _this.info.render.calls ++;
  8120. _this.info.render.points += geometryGroup.__webglParticleCount;
  8121. // render ribbon
  8122. } else if ( object instanceof THREE.Ribbon ) {
  8123. _gl.drawArrays( _gl.TRIANGLE_STRIP, 0, geometryGroup.__webglVertexCount );
  8124. _this.info.render.calls ++;
  8125. }
  8126. };
  8127. function setupMorphTargets ( material, geometryGroup, object ) {
  8128. // set base
  8129. var attributes = material.program.attributes;
  8130. if ( object.morphTargetBase !== - 1 ) {
  8131. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ object.morphTargetBase ] );
  8132. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8133. } else if ( attributes.position >= 0 ) {
  8134. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglVertexBuffer );
  8135. _gl.vertexAttribPointer( attributes.position, 3, _gl.FLOAT, false, 0, 0 );
  8136. }
  8137. if ( object.morphTargetForcedOrder.length ) {
  8138. // set forced order
  8139. var m = 0;
  8140. var order = object.morphTargetForcedOrder;
  8141. var influences = object.morphTargetInfluences;
  8142. while ( m < material.numSupportedMorphTargets && m < order.length ) {
  8143. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ order[ m ] ] );
  8144. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8145. if ( material.morphNormals ) {
  8146. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ order[ m ] ] );
  8147. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8148. }
  8149. object.__webglMorphTargetInfluences[ m ] = influences[ order[ m ] ];
  8150. m ++;
  8151. }
  8152. } else {
  8153. // find most influencing
  8154. var used = [];
  8155. var candidateInfluence = - 1;
  8156. var candidate = 0;
  8157. var influences = object.morphTargetInfluences;
  8158. var i, il = influences.length;
  8159. var m = 0;
  8160. if ( object.morphTargetBase !== - 1 ) {
  8161. used[ object.morphTargetBase ] = true;
  8162. }
  8163. while ( m < material.numSupportedMorphTargets ) {
  8164. for ( i = 0; i < il; i ++ ) {
  8165. if ( !used[ i ] && influences[ i ] > candidateInfluence ) {
  8166. candidate = i;
  8167. candidateInfluence = influences[ candidate ];
  8168. }
  8169. }
  8170. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphTargetsBuffers[ candidate ] );
  8171. _gl.vertexAttribPointer( attributes[ "morphTarget" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8172. if ( material.morphNormals ) {
  8173. _gl.bindBuffer( _gl.ARRAY_BUFFER, geometryGroup.__webglMorphNormalsBuffers[ candidate ] );
  8174. _gl.vertexAttribPointer( attributes[ "morphNormal" + m ], 3, _gl.FLOAT, false, 0, 0 );
  8175. }
  8176. object.__webglMorphTargetInfluences[ m ] = candidateInfluence;
  8177. used[ candidate ] = 1;
  8178. candidateInfluence = -1;
  8179. m ++;
  8180. }
  8181. }
  8182. // load updated influences uniform
  8183. if( material.program.uniforms.morphTargetInfluences !== null ) {
  8184. _gl.uniform1fv( material.program.uniforms.morphTargetInfluences, object.__webglMorphTargetInfluences );
  8185. }
  8186. };
  8187. function painterSort ( a, b ) {
  8188. return b.z - a.z;
  8189. };
  8190. // Rendering
  8191. this.render = function ( scene, camera, renderTarget, forceClear ) {
  8192. var i, il,
  8193. webglObject, object,
  8194. renderList,
  8195. lights = scene.__lights,
  8196. fog = scene.fog;
  8197. _currentMaterialId = -1;
  8198. // update scene graph
  8199. if ( camera.parent === undefined ) {
  8200. console.warn( 'DEPRECATED: Camera hasn\'t been added to a Scene. Adding it...' );
  8201. scene.add( camera );
  8202. }
  8203. if ( this.autoUpdateScene ) scene.updateMatrixWorld();
  8204. // update camera matrices and frustum
  8205. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  8206. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  8207. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  8208. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  8209. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  8210. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  8211. _frustum.setFromMatrix( _projScreenMatrix );
  8212. // update WebGL objects
  8213. if ( this.autoUpdateObjects ) this.initWebGLObjects( scene );
  8214. // custom render plugins (pre pass)
  8215. renderPlugins( this.renderPluginsPre, scene, camera );
  8216. //
  8217. _this.info.render.calls = 0;
  8218. _this.info.render.vertices = 0;
  8219. _this.info.render.faces = 0;
  8220. _this.info.render.points = 0;
  8221. this.setRenderTarget( renderTarget );
  8222. if ( this.autoClear || forceClear ) {
  8223. this.clear( this.autoClearColor, this.autoClearDepth, this.autoClearStencil );
  8224. }
  8225. // set matrices for regular objects (frustum culled)
  8226. renderList = scene.__webglObjects;
  8227. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  8228. webglObject = renderList[ i ];
  8229. object = webglObject.object;
  8230. webglObject.render = false;
  8231. if ( object.visible ) {
  8232. if ( ! ( object instanceof THREE.Mesh || object instanceof THREE.ParticleSystem ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  8233. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8234. setupMatrices( object, camera );
  8235. unrollBufferMaterial( webglObject );
  8236. webglObject.render = true;
  8237. if ( this.sortObjects ) {
  8238. if ( object.renderDepth ) {
  8239. webglObject.z = object.renderDepth;
  8240. } else {
  8241. _vector3.copy( object.matrixWorld.getPosition() );
  8242. _projScreenMatrix.multiplyVector3( _vector3 );
  8243. webglObject.z = _vector3.z;
  8244. }
  8245. }
  8246. }
  8247. }
  8248. }
  8249. if ( this.sortObjects ) {
  8250. renderList.sort( painterSort );
  8251. }
  8252. // set matrices for immediate objects
  8253. renderList = scene.__webglObjectsImmediate;
  8254. for ( i = 0, il = renderList.length; i < il; i ++ ) {
  8255. webglObject = renderList[ i ];
  8256. object = webglObject.object;
  8257. if ( object.visible ) {
  8258. if( object.matrixAutoUpdate ) {
  8259. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8260. }
  8261. setupMatrices( object, camera );
  8262. unrollImmediateBufferMaterial( webglObject );
  8263. }
  8264. }
  8265. if ( scene.overrideMaterial ) {
  8266. var material = scene.overrideMaterial;
  8267. this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8268. this.setDepthTest( material.depthTest );
  8269. this.setDepthWrite( material.depthWrite );
  8270. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8271. renderObjects( scene.__webglObjects, false, "", camera, lights, fog, true, material );
  8272. renderObjectsImmediate( scene.__webglObjectsImmediate, "", camera, lights, fog, false, material );
  8273. } else {
  8274. // opaque pass (front-to-back order)
  8275. this.setBlending( THREE.NormalBlending );
  8276. renderObjects( scene.__webglObjects, true, "opaque", camera, lights, fog, false );
  8277. renderObjectsImmediate( scene.__webglObjectsImmediate, "opaque", camera, lights, fog, false );
  8278. // transparent pass (back-to-front order)
  8279. renderObjects( scene.__webglObjects, false, "transparent", camera, lights, fog, true );
  8280. renderObjectsImmediate( scene.__webglObjectsImmediate, "transparent", camera, lights, fog, true );
  8281. }
  8282. // custom render plugins (post pass)
  8283. renderPlugins( this.renderPluginsPost, scene, camera );
  8284. // Generate mipmap if we're using any kind of mipmap filtering
  8285. if ( renderTarget && renderTarget.generateMipmaps && renderTarget.minFilter !== THREE.NearestFilter && renderTarget.minFilter !== THREE.LinearFilter ) {
  8286. updateRenderTargetMipmap( renderTarget );
  8287. }
  8288. // Ensure depth buffer writing is enabled so it can be cleared on next render
  8289. this.setDepthTest( true );
  8290. this.setDepthWrite( true );
  8291. // _gl.finish();
  8292. };
  8293. function renderPlugins( plugins, scene, camera ) {
  8294. if ( ! plugins.length ) return;
  8295. for ( var i = 0, il = plugins.length; i < il; i ++ ) {
  8296. _currentProgram = null;
  8297. _currentCamera = null;
  8298. _oldBlending = -1;
  8299. _oldDepthTest = -1;
  8300. _oldDepthWrite = -1;
  8301. _currentGeometryGroupHash = -1;
  8302. _currentMaterialId = -1;
  8303. plugins[ i ].render( scene, camera, _currentWidth, _currentHeight );
  8304. _currentProgram = null;
  8305. _currentCamera = null;
  8306. _oldBlending = -1;
  8307. _oldDepthTest = -1;
  8308. _oldDepthWrite = -1;
  8309. _currentGeometryGroupHash = -1;
  8310. _currentMaterialId = -1;
  8311. }
  8312. };
  8313. function renderObjects ( renderList, reverse, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  8314. var webglObject, object, buffer, material, start, end, delta;
  8315. if ( reverse ) {
  8316. start = renderList.length - 1;
  8317. end = -1;
  8318. delta = -1;
  8319. } else {
  8320. start = 0;
  8321. end = renderList.length;
  8322. delta = 1;
  8323. }
  8324. for ( var i = start; i !== end; i += delta ) {
  8325. webglObject = renderList[ i ];
  8326. if ( webglObject.render ) {
  8327. object = webglObject.object;
  8328. buffer = webglObject.buffer;
  8329. if ( overrideMaterial ) {
  8330. material = overrideMaterial;
  8331. } else {
  8332. material = webglObject[ materialType ];
  8333. if ( ! material ) continue;
  8334. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8335. _this.setDepthTest( material.depthTest );
  8336. _this.setDepthWrite( material.depthWrite );
  8337. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8338. }
  8339. _this.setObjectFaces( object );
  8340. if ( buffer instanceof THREE.BufferGeometry ) {
  8341. _this.renderBufferDirect( camera, lights, fog, material, buffer, object );
  8342. } else {
  8343. _this.renderBuffer( camera, lights, fog, material, buffer, object );
  8344. }
  8345. }
  8346. }
  8347. };
  8348. function renderObjectsImmediate ( renderList, materialType, camera, lights, fog, useBlending, overrideMaterial ) {
  8349. var webglObject, object, material, program;
  8350. for ( var i = 0, il = renderList.length; i < il; i ++ ) {
  8351. webglObject = renderList[ i ];
  8352. object = webglObject.object;
  8353. if ( object.visible ) {
  8354. if ( overrideMaterial ) {
  8355. material = overrideMaterial;
  8356. } else {
  8357. material = webglObject[ materialType ];
  8358. if ( ! material ) continue;
  8359. if ( useBlending ) _this.setBlending( material.blending, material.blendEquation, material.blendSrc, material.blendDst );
  8360. _this.setDepthTest( material.depthTest );
  8361. _this.setDepthWrite( material.depthWrite );
  8362. setPolygonOffset( material.polygonOffset, material.polygonOffsetFactor, material.polygonOffsetUnits );
  8363. }
  8364. _this.renderImmediateObject( camera, lights, fog, material, object );
  8365. }
  8366. }
  8367. };
  8368. this.renderImmediateObject = function ( camera, lights, fog, material, object ) {
  8369. var program = setProgram( camera, lights, fog, material, object );
  8370. _currentGeometryGroupHash = -1;
  8371. _this.setObjectFaces( object );
  8372. if ( object.immediateRenderCallback ) {
  8373. object.immediateRenderCallback( program, _gl, _frustum );
  8374. } else {
  8375. object.render( function( object ) { _this.renderBufferImmediate( object, program, material.shading ); } );
  8376. }
  8377. };
  8378. function unrollImmediateBufferMaterial ( globject ) {
  8379. var object = globject.object,
  8380. material = object.material;
  8381. if ( material.transparent ) {
  8382. globject.transparent = material;
  8383. globject.opaque = null;
  8384. } else {
  8385. globject.opaque = material;
  8386. globject.transparent = null;
  8387. }
  8388. };
  8389. function unrollBufferMaterial ( globject ) {
  8390. var object = globject.object,
  8391. buffer = globject.buffer,
  8392. material, materialIndex, meshMaterial;
  8393. meshMaterial = object.material;
  8394. if ( meshMaterial instanceof THREE.MeshFaceMaterial ) {
  8395. materialIndex = buffer.materialIndex;
  8396. if ( materialIndex >= 0 ) {
  8397. material = object.geometry.materials[ materialIndex ];
  8398. if ( material.transparent ) {
  8399. globject.transparent = material;
  8400. globject.opaque = null;
  8401. } else {
  8402. globject.opaque = material;
  8403. globject.transparent = null;
  8404. }
  8405. }
  8406. } else {
  8407. material = meshMaterial;
  8408. if ( material ) {
  8409. if ( material.transparent ) {
  8410. globject.transparent = material;
  8411. globject.opaque = null;
  8412. } else {
  8413. globject.opaque = material;
  8414. globject.transparent = null;
  8415. }
  8416. }
  8417. }
  8418. };
  8419. // Geometry splitting
  8420. function sortFacesByMaterial ( geometry ) {
  8421. var f, fl, face, materialIndex, vertices,
  8422. materialHash, groupHash,
  8423. hash_map = {};
  8424. var numMorphTargets = geometry.morphTargets.length;
  8425. var numMorphNormals = geometry.morphNormals.length;
  8426. geometry.geometryGroups = {};
  8427. for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
  8428. face = geometry.faces[ f ];
  8429. materialIndex = face.materialIndex;
  8430. materialHash = ( materialIndex !== undefined ) ? materialIndex : -1;
  8431. if ( hash_map[ materialHash ] === undefined ) {
  8432. hash_map[ materialHash ] = { 'hash': materialHash, 'counter': 0 };
  8433. }
  8434. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  8435. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  8436. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  8437. }
  8438. vertices = face instanceof THREE.Face3 ? 3 : 4;
  8439. if ( geometry.geometryGroups[ groupHash ].vertices + vertices > 65535 ) {
  8440. hash_map[ materialHash ].counter += 1;
  8441. groupHash = hash_map[ materialHash ].hash + '_' + hash_map[ materialHash ].counter;
  8442. if ( geometry.geometryGroups[ groupHash ] === undefined ) {
  8443. geometry.geometryGroups[ groupHash ] = { 'faces3': [], 'faces4': [], 'materialIndex': materialIndex, 'vertices': 0, 'numMorphTargets': numMorphTargets, 'numMorphNormals': numMorphNormals };
  8444. }
  8445. }
  8446. if ( face instanceof THREE.Face3 ) {
  8447. geometry.geometryGroups[ groupHash ].faces3.push( f );
  8448. } else {
  8449. geometry.geometryGroups[ groupHash ].faces4.push( f );
  8450. }
  8451. geometry.geometryGroups[ groupHash ].vertices += vertices;
  8452. }
  8453. geometry.geometryGroupsList = [];
  8454. for ( var g in geometry.geometryGroups ) {
  8455. geometry.geometryGroups[ g ].id = _geometryGroupCounter ++;
  8456. geometry.geometryGroupsList.push( geometry.geometryGroups[ g ] );
  8457. }
  8458. };
  8459. // Objects refresh
  8460. this.initWebGLObjects = function ( scene ) {
  8461. if ( !scene.__webglObjects ) {
  8462. scene.__webglObjects = [];
  8463. scene.__webglObjectsImmediate = [];
  8464. scene.__webglSprites = [];
  8465. scene.__webglFlares = [];
  8466. }
  8467. while ( scene.__objectsAdded.length ) {
  8468. addObject( scene.__objectsAdded[ 0 ], scene );
  8469. scene.__objectsAdded.splice( 0, 1 );
  8470. }
  8471. while ( scene.__objectsRemoved.length ) {
  8472. removeObject( scene.__objectsRemoved[ 0 ], scene );
  8473. scene.__objectsRemoved.splice( 0, 1 );
  8474. }
  8475. // update must be called after objects adding / removal
  8476. for ( var o = 0, ol = scene.__webglObjects.length; o < ol; o ++ ) {
  8477. updateObject( scene.__webglObjects[ o ].object );
  8478. }
  8479. };
  8480. // Objects adding
  8481. function addObject ( object, scene ) {
  8482. var g, geometry, geometryGroup;
  8483. if ( ! object.__webglInit ) {
  8484. object.__webglInit = true;
  8485. object._modelViewMatrix = new THREE.Matrix4();
  8486. object._normalMatrix = new THREE.Matrix3();
  8487. object._normalMatrixArray = new Float32Array( 9 );
  8488. object._modelViewMatrixArray = new Float32Array( 16 );
  8489. object._objectMatrixArray = new Float32Array( 16 );
  8490. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  8491. if ( object instanceof THREE.Mesh ) {
  8492. geometry = object.geometry;
  8493. if ( geometry instanceof THREE.Geometry ) {
  8494. if ( geometry.geometryGroups === undefined ) {
  8495. sortFacesByMaterial( geometry );
  8496. }
  8497. // create separate VBOs per geometry chunk
  8498. for ( g in geometry.geometryGroups ) {
  8499. geometryGroup = geometry.geometryGroups[ g ];
  8500. // initialise VBO on the first access
  8501. if ( ! geometryGroup.__webglVertexBuffer ) {
  8502. createMeshBuffers( geometryGroup );
  8503. initMeshBuffers( geometryGroup, object );
  8504. geometry.__dirtyVertices = true;
  8505. geometry.__dirtyMorphTargets = true;
  8506. geometry.__dirtyElements = true;
  8507. geometry.__dirtyUvs = true;
  8508. geometry.__dirtyNormals = true;
  8509. geometry.__dirtyTangents = true;
  8510. geometry.__dirtyColors = true;
  8511. }
  8512. }
  8513. }
  8514. } else if ( object instanceof THREE.Ribbon ) {
  8515. geometry = object.geometry;
  8516. if( ! geometry.__webglVertexBuffer ) {
  8517. createRibbonBuffers( geometry );
  8518. initRibbonBuffers( geometry );
  8519. geometry.__dirtyVertices = true;
  8520. geometry.__dirtyColors = true;
  8521. }
  8522. } else if ( object instanceof THREE.Line ) {
  8523. geometry = object.geometry;
  8524. if( ! geometry.__webglVertexBuffer ) {
  8525. createLineBuffers( geometry );
  8526. initLineBuffers( geometry, object );
  8527. geometry.__dirtyVertices = true;
  8528. geometry.__dirtyColors = true;
  8529. }
  8530. } else if ( object instanceof THREE.ParticleSystem ) {
  8531. geometry = object.geometry;
  8532. if ( ! geometry.__webglVertexBuffer ) {
  8533. createParticleBuffers( geometry );
  8534. initParticleBuffers( geometry, object );
  8535. geometry.__dirtyVertices = true;
  8536. geometry.__dirtyColors = true;
  8537. }
  8538. }
  8539. }
  8540. if ( ! object.__webglActive ) {
  8541. if ( object instanceof THREE.Mesh ) {
  8542. geometry = object.geometry;
  8543. if ( geometry instanceof THREE.BufferGeometry ) {
  8544. addBuffer( scene.__webglObjects, geometry, object );
  8545. } else {
  8546. for ( g in geometry.geometryGroups ) {
  8547. geometryGroup = geometry.geometryGroups[ g ];
  8548. addBuffer( scene.__webglObjects, geometryGroup, object );
  8549. }
  8550. }
  8551. } else if ( object instanceof THREE.Ribbon ||
  8552. object instanceof THREE.Line ||
  8553. object instanceof THREE.ParticleSystem ) {
  8554. geometry = object.geometry;
  8555. addBuffer( scene.__webglObjects, geometry, object );
  8556. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  8557. addBufferImmediate( scene.__webglObjectsImmediate, object );
  8558. } else if ( object instanceof THREE.Sprite ) {
  8559. scene.__webglSprites.push( object );
  8560. } else if ( object instanceof THREE.LensFlare ) {
  8561. scene.__webglFlares.push( object );
  8562. }
  8563. object.__webglActive = true;
  8564. }
  8565. };
  8566. function addBuffer ( objlist, buffer, object ) {
  8567. objlist.push(
  8568. {
  8569. buffer: buffer,
  8570. object: object,
  8571. opaque: null,
  8572. transparent: null
  8573. }
  8574. );
  8575. };
  8576. function addBufferImmediate ( objlist, object ) {
  8577. objlist.push(
  8578. {
  8579. object: object,
  8580. opaque: null,
  8581. transparent: null
  8582. }
  8583. );
  8584. };
  8585. // Objects updates
  8586. function updateObject ( object ) {
  8587. var geometry = object.geometry,
  8588. geometryGroup, customAttributesDirty, material;
  8589. if ( object instanceof THREE.Mesh ) {
  8590. if ( geometry instanceof THREE.BufferGeometry ) {
  8591. /*
  8592. if ( geometry.__dirtyVertices || geometry.__dirtyElements ||
  8593. geometry.__dirtyUvs || geometry.__dirtyNormals ||
  8594. geometry.__dirtyColors ) {
  8595. // TODO
  8596. // set buffers from typed arrays
  8597. }
  8598. */
  8599. geometry.__dirtyVertices = false;
  8600. geometry.__dirtyElements = false;
  8601. geometry.__dirtyUvs = false;
  8602. geometry.__dirtyNormals = false;
  8603. geometry.__dirtyColors = false;
  8604. } else {
  8605. // check all geometry groups
  8606. for( var i = 0, il = geometry.geometryGroupsList.length; i < il; i ++ ) {
  8607. geometryGroup = geometry.geometryGroupsList[ i ];
  8608. material = getBufferMaterial( object, geometryGroup );
  8609. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8610. if ( geometry.__dirtyVertices || geometry.__dirtyMorphTargets || geometry.__dirtyElements ||
  8611. geometry.__dirtyUvs || geometry.__dirtyNormals ||
  8612. geometry.__dirtyColors || geometry.__dirtyTangents || customAttributesDirty ) {
  8613. setMeshBuffers( geometryGroup, object, _gl.DYNAMIC_DRAW, !geometry.dynamic, material );
  8614. }
  8615. }
  8616. geometry.__dirtyVertices = false;
  8617. geometry.__dirtyMorphTargets = false;
  8618. geometry.__dirtyElements = false;
  8619. geometry.__dirtyUvs = false;
  8620. geometry.__dirtyNormals = false;
  8621. geometry.__dirtyColors = false;
  8622. geometry.__dirtyTangents = false;
  8623. material.attributes && clearCustomAttributes( material );
  8624. }
  8625. } else if ( object instanceof THREE.Ribbon ) {
  8626. if ( geometry.__dirtyVertices || geometry.__dirtyColors ) {
  8627. setRibbonBuffers( geometry, _gl.DYNAMIC_DRAW );
  8628. }
  8629. geometry.__dirtyVertices = false;
  8630. geometry.__dirtyColors = false;
  8631. } else if ( object instanceof THREE.Line ) {
  8632. material = getBufferMaterial( object, geometryGroup );
  8633. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8634. if ( geometry.__dirtyVertices || geometry.__dirtyColors || customAttributesDirty ) {
  8635. setLineBuffers( geometry, _gl.DYNAMIC_DRAW );
  8636. }
  8637. geometry.__dirtyVertices = false;
  8638. geometry.__dirtyColors = false;
  8639. material.attributes && clearCustomAttributes( material );
  8640. } else if ( object instanceof THREE.ParticleSystem ) {
  8641. material = getBufferMaterial( object, geometryGroup );
  8642. customAttributesDirty = material.attributes && areCustomAttributesDirty( material );
  8643. if ( geometry.__dirtyVertices || geometry.__dirtyColors || object.sortParticles || customAttributesDirty ) {
  8644. setParticleBuffers( geometry, _gl.DYNAMIC_DRAW, object );
  8645. }
  8646. geometry.__dirtyVertices = false;
  8647. geometry.__dirtyColors = false;
  8648. material.attributes && clearCustomAttributes( material );
  8649. }
  8650. };
  8651. // Objects updates - custom attributes check
  8652. function areCustomAttributesDirty ( material ) {
  8653. for ( var a in material.attributes ) {
  8654. if ( material.attributes[ a ].needsUpdate ) return true;
  8655. }
  8656. return false;
  8657. };
  8658. function clearCustomAttributes ( material ) {
  8659. for ( var a in material.attributes ) {
  8660. material.attributes[ a ].needsUpdate = false;
  8661. }
  8662. };
  8663. // Objects removal
  8664. function removeObject ( object, scene ) {
  8665. if ( object instanceof THREE.Mesh ||
  8666. object instanceof THREE.ParticleSystem ||
  8667. object instanceof THREE.Ribbon ||
  8668. object instanceof THREE.Line ) {
  8669. removeInstances( scene.__webglObjects, object );
  8670. } else if ( object instanceof THREE.Sprite ) {
  8671. removeInstancesDirect( scene.__webglSprites, object );
  8672. } else if ( object instanceof THREE.LensFlare ) {
  8673. removeInstancesDirect( scene.__webglFlares, object );
  8674. } else if ( object instanceof THREE.ImmediateRenderObject || object.immediateRenderCallback ) {
  8675. removeInstances( scene.__webglObjectsImmediate, object );
  8676. }
  8677. object.__webglActive = false;
  8678. };
  8679. function removeInstances ( objlist, object ) {
  8680. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  8681. if ( objlist[ o ].object === object ) {
  8682. objlist.splice( o, 1 );
  8683. }
  8684. }
  8685. };
  8686. function removeInstancesDirect ( objlist, object ) {
  8687. for ( var o = objlist.length - 1; o >= 0; o -- ) {
  8688. if ( objlist[ o ] === object ) {
  8689. objlist.splice( o, 1 );
  8690. }
  8691. }
  8692. };
  8693. // Materials
  8694. this.initMaterial = function ( material, lights, fog, object ) {
  8695. var u, a, identifiers, i, parameters, maxLightCount, maxBones, maxShadows, shaderID;
  8696. if ( material instanceof THREE.MeshDepthMaterial ) {
  8697. shaderID = 'depth';
  8698. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8699. shaderID = 'normal';
  8700. } else if ( material instanceof THREE.MeshBasicMaterial ) {
  8701. shaderID = 'basic';
  8702. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  8703. shaderID = 'lambert';
  8704. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  8705. shaderID = 'phong';
  8706. } else if ( material instanceof THREE.LineBasicMaterial ) {
  8707. shaderID = 'basic';
  8708. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  8709. shaderID = 'particle_basic';
  8710. }
  8711. if ( shaderID ) {
  8712. setMaterialShaders( material, THREE.ShaderLib[ shaderID ] );
  8713. }
  8714. // heuristics to create shader parameters according to lights in the scene
  8715. // (not to blow over maxLights budget)
  8716. maxLightCount = allocateLights( lights );
  8717. maxShadows = allocateShadows( lights );
  8718. maxBones = allocateBones( object );
  8719. parameters = {
  8720. map: !!material.map, envMap: !!material.envMap, lightMap: !!material.lightMap,
  8721. vertexColors: material.vertexColors,
  8722. fog: fog, useFog: material.fog,
  8723. sizeAttenuation: material.sizeAttenuation,
  8724. skinning: material.skinning,
  8725. morphTargets: material.morphTargets,
  8726. morphNormals: material.morphNormals,
  8727. maxMorphTargets: this.maxMorphTargets,
  8728. maxMorphNormals: this.maxMorphNormals,
  8729. maxDirLights: maxLightCount.directional, maxPointLights: maxLightCount.point,
  8730. maxBones: maxBones,
  8731. shadowMapEnabled: this.shadowMapEnabled && object.receiveShadow,
  8732. shadowMapSoft: this.shadowMapSoft,
  8733. shadowMapDebug: this.shadowMapDebug,
  8734. shadowMapCascade: this.shadowMapCascade,
  8735. maxShadows: maxShadows,
  8736. alphaTest: material.alphaTest,
  8737. metal: material.metal,
  8738. perPixel: material.perPixel,
  8739. wrapAround: material.wrapAround,
  8740. doubleSided: object && object.doubleSided
  8741. };
  8742. material.program = buildProgram( shaderID, material.fragmentShader, material.vertexShader, material.uniforms, material.attributes, parameters );
  8743. var attributes = material.program.attributes;
  8744. if ( attributes.position >= 0 ) _gl.enableVertexAttribArray( attributes.position );
  8745. if ( attributes.color >= 0 ) _gl.enableVertexAttribArray( attributes.color );
  8746. if ( attributes.normal >= 0 ) _gl.enableVertexAttribArray( attributes.normal );
  8747. if ( attributes.tangent >= 0 ) _gl.enableVertexAttribArray( attributes.tangent );
  8748. if ( material.skinning &&
  8749. attributes.skinVertexA >=0 && attributes.skinVertexB >= 0 &&
  8750. attributes.skinIndex >= 0 && attributes.skinWeight >= 0 ) {
  8751. _gl.enableVertexAttribArray( attributes.skinVertexA );
  8752. _gl.enableVertexAttribArray( attributes.skinVertexB );
  8753. _gl.enableVertexAttribArray( attributes.skinIndex );
  8754. _gl.enableVertexAttribArray( attributes.skinWeight );
  8755. }
  8756. if ( material.attributes ) {
  8757. for ( a in material.attributes ) {
  8758. if( attributes[ a ] !== undefined && attributes[ a ] >= 0 ) _gl.enableVertexAttribArray( attributes[ a ] );
  8759. }
  8760. }
  8761. if ( material.morphTargets ) {
  8762. material.numSupportedMorphTargets = 0;
  8763. var id, base = "morphTarget";
  8764. for ( i = 0; i < this.maxMorphTargets; i ++ ) {
  8765. id = base + i;
  8766. if ( attributes[ id ] >= 0 ) {
  8767. _gl.enableVertexAttribArray( attributes[ id ] );
  8768. material.numSupportedMorphTargets ++;
  8769. }
  8770. }
  8771. }
  8772. if ( material.morphNormals ) {
  8773. material.numSupportedMorphNormals = 0;
  8774. var id, base = "morphNormal";
  8775. for ( i = 0; i < this.maxMorphNormals; i ++ ) {
  8776. id = base + i;
  8777. if ( attributes[ id ] >= 0 ) {
  8778. _gl.enableVertexAttribArray( attributes[ id ] );
  8779. material.numSupportedMorphNormals ++;
  8780. }
  8781. }
  8782. }
  8783. material.uniformsList = [];
  8784. for ( u in material.uniforms ) {
  8785. material.uniformsList.push( [ material.uniforms[ u ], u ] );
  8786. }
  8787. };
  8788. function setMaterialShaders( material, shaders ) {
  8789. material.uniforms = THREE.UniformsUtils.clone( shaders.uniforms );
  8790. material.vertexShader = shaders.vertexShader;
  8791. material.fragmentShader = shaders.fragmentShader;
  8792. };
  8793. function setProgram( camera, lights, fog, material, object ) {
  8794. if ( ! material.program || material.needsUpdate ) {
  8795. _this.initMaterial( material, lights, fog, object );
  8796. material.needsUpdate = false;
  8797. }
  8798. if ( material.morphTargets ) {
  8799. if ( ! object.__webglMorphTargetInfluences ) {
  8800. object.__webglMorphTargetInfluences = new Float32Array( _this.maxMorphTargets );
  8801. for ( var i = 0, il = _this.maxMorphTargets; i < il; i ++ ) {
  8802. object.__webglMorphTargetInfluences[ i ] = 0;
  8803. }
  8804. }
  8805. }
  8806. var refreshMaterial = false;
  8807. var program = material.program,
  8808. p_uniforms = program.uniforms,
  8809. m_uniforms = material.uniforms;
  8810. if ( program !== _currentProgram ) {
  8811. _gl.useProgram( program );
  8812. _currentProgram = program;
  8813. refreshMaterial = true;
  8814. }
  8815. if ( material.id !== _currentMaterialId ) {
  8816. _currentMaterialId = material.id;
  8817. refreshMaterial = true;
  8818. }
  8819. if ( refreshMaterial || camera !== _currentCamera ) {
  8820. _gl.uniformMatrix4fv( p_uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  8821. if ( camera !== _currentCamera ) _currentCamera = camera;
  8822. }
  8823. if ( refreshMaterial ) {
  8824. // refresh uniforms common to several materials
  8825. if ( fog && material.fog ) {
  8826. refreshUniformsFog( m_uniforms, fog );
  8827. }
  8828. if ( material instanceof THREE.MeshPhongMaterial ||
  8829. material instanceof THREE.MeshLambertMaterial ||
  8830. material.lights ) {
  8831. setupLights( program, lights );
  8832. refreshUniformsLights( m_uniforms, _lights );
  8833. }
  8834. if ( material instanceof THREE.MeshBasicMaterial ||
  8835. material instanceof THREE.MeshLambertMaterial ||
  8836. material instanceof THREE.MeshPhongMaterial ) {
  8837. refreshUniformsCommon( m_uniforms, material );
  8838. }
  8839. // refresh single material specific uniforms
  8840. if ( material instanceof THREE.LineBasicMaterial ) {
  8841. refreshUniformsLine( m_uniforms, material );
  8842. } else if ( material instanceof THREE.ParticleBasicMaterial ) {
  8843. refreshUniformsParticle( m_uniforms, material );
  8844. } else if ( material instanceof THREE.MeshPhongMaterial ) {
  8845. refreshUniformsPhong( m_uniforms, material );
  8846. } else if ( material instanceof THREE.MeshLambertMaterial ) {
  8847. refreshUniformsLambert( m_uniforms, material );
  8848. } else if ( material instanceof THREE.MeshDepthMaterial ) {
  8849. m_uniforms.mNear.value = camera.near;
  8850. m_uniforms.mFar.value = camera.far;
  8851. m_uniforms.opacity.value = material.opacity;
  8852. } else if ( material instanceof THREE.MeshNormalMaterial ) {
  8853. m_uniforms.opacity.value = material.opacity;
  8854. }
  8855. if ( object.receiveShadow && ! material._shadowPass ) {
  8856. refreshUniformsShadow( m_uniforms, lights );
  8857. }
  8858. // load common uniforms
  8859. loadUniformsGeneric( program, material.uniformsList );
  8860. // load material specific uniforms
  8861. // (shader material also gets them for the sake of genericity)
  8862. if ( material instanceof THREE.ShaderMaterial ||
  8863. material instanceof THREE.MeshPhongMaterial ||
  8864. material.envMap ) {
  8865. if ( p_uniforms.cameraPosition !== null ) {
  8866. var position = camera.matrixWorld.getPosition();
  8867. _gl.uniform3f( p_uniforms.cameraPosition, position.x, position.y, position.z );
  8868. }
  8869. }
  8870. if ( material instanceof THREE.MeshPhongMaterial ||
  8871. material instanceof THREE.MeshLambertMaterial ||
  8872. material instanceof THREE.ShaderMaterial ||
  8873. material.skinning ) {
  8874. if ( p_uniforms.viewMatrix !== null ) {
  8875. _gl.uniformMatrix4fv( p_uniforms.viewMatrix, false, camera._viewMatrixArray );
  8876. }
  8877. }
  8878. if ( material.skinning ) {
  8879. _gl.uniformMatrix4fv( p_uniforms.boneGlobalMatrices, false, object.boneMatrices );
  8880. }
  8881. }
  8882. loadUniformsMatrices( p_uniforms, object );
  8883. if ( material instanceof THREE.ShaderMaterial ||
  8884. material.envMap ||
  8885. material.skinning ||
  8886. object.receiveShadow ) {
  8887. if ( p_uniforms.objectMatrix !== null ) {
  8888. _gl.uniformMatrix4fv( p_uniforms.objectMatrix, false, object.matrixWorld.elements );
  8889. }
  8890. }
  8891. return program;
  8892. };
  8893. // Uniforms (refresh uniforms objects)
  8894. function refreshUniformsCommon ( uniforms, material ) {
  8895. uniforms.opacity.value = material.opacity;
  8896. if ( _this.gammaInput ) {
  8897. uniforms.diffuse.value.copyGammaToLinear( material.color );
  8898. } else {
  8899. uniforms.diffuse.value = material.color;
  8900. }
  8901. uniforms.map.texture = material.map;
  8902. if ( material.map ) {
  8903. uniforms.offsetRepeat.value.set( material.map.offset.x, material.map.offset.y, material.map.repeat.x, material.map.repeat.y );
  8904. }
  8905. uniforms.lightMap.texture = material.lightMap;
  8906. uniforms.envMap.texture = material.envMap;
  8907. uniforms.flipEnvMap.value = ( material.envMap instanceof THREE.WebGLRenderTargetCube ) ? 1 : -1;
  8908. if ( _this.gammaInput ) {
  8909. //uniforms.reflectivity.value = material.reflectivity * material.reflectivity;
  8910. uniforms.reflectivity.value = material.reflectivity;
  8911. } else {
  8912. uniforms.reflectivity.value = material.reflectivity;
  8913. }
  8914. uniforms.refractionRatio.value = material.refractionRatio;
  8915. uniforms.combine.value = material.combine;
  8916. uniforms.useRefract.value = material.envMap && material.envMap.mapping instanceof THREE.CubeRefractionMapping;
  8917. };
  8918. function refreshUniformsLine ( uniforms, material ) {
  8919. uniforms.diffuse.value = material.color;
  8920. uniforms.opacity.value = material.opacity;
  8921. };
  8922. function refreshUniformsParticle ( uniforms, material ) {
  8923. uniforms.psColor.value = material.color;
  8924. uniforms.opacity.value = material.opacity;
  8925. uniforms.size.value = material.size;
  8926. uniforms.scale.value = _canvas.height / 2.0; // TODO: Cache this.
  8927. uniforms.map.texture = material.map;
  8928. };
  8929. function refreshUniformsFog ( uniforms, fog ) {
  8930. uniforms.fogColor.value = fog.color;
  8931. if ( fog instanceof THREE.Fog ) {
  8932. uniforms.fogNear.value = fog.near;
  8933. uniforms.fogFar.value = fog.far;
  8934. } else if ( fog instanceof THREE.FogExp2 ) {
  8935. uniforms.fogDensity.value = fog.density;
  8936. }
  8937. };
  8938. function refreshUniformsPhong ( uniforms, material ) {
  8939. uniforms.shininess.value = material.shininess;
  8940. if ( _this.gammaInput ) {
  8941. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  8942. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  8943. uniforms.specular.value.copyGammaToLinear( material.specular );
  8944. } else {
  8945. uniforms.ambient.value = material.ambient;
  8946. uniforms.emissive.value = material.emissive;
  8947. uniforms.specular.value = material.specular;
  8948. }
  8949. if ( material.wrapAround ) {
  8950. uniforms.wrapRGB.value.copy( material.wrapRGB );
  8951. }
  8952. };
  8953. function refreshUniformsLambert ( uniforms, material ) {
  8954. if ( _this.gammaInput ) {
  8955. uniforms.ambient.value.copyGammaToLinear( material.ambient );
  8956. uniforms.emissive.value.copyGammaToLinear( material.emissive );
  8957. } else {
  8958. uniforms.ambient.value = material.ambient;
  8959. uniforms.emissive.value = material.emissive;
  8960. }
  8961. if ( material.wrapAround ) {
  8962. uniforms.wrapRGB.value.copy( material.wrapRGB );
  8963. }
  8964. };
  8965. function refreshUniformsLights ( uniforms, lights ) {
  8966. uniforms.ambientLightColor.value = lights.ambient;
  8967. uniforms.directionalLightColor.value = lights.directional.colors;
  8968. uniforms.directionalLightDirection.value = lights.directional.positions;
  8969. uniforms.pointLightColor.value = lights.point.colors;
  8970. uniforms.pointLightPosition.value = lights.point.positions;
  8971. uniforms.pointLightDistance.value = lights.point.distances;
  8972. };
  8973. function refreshUniformsShadow ( uniforms, lights ) {
  8974. if ( uniforms.shadowMatrix ) {
  8975. var j = 0;
  8976. for ( var i = 0, il = lights.length; i < il; i ++ ) {
  8977. var light = lights[ i ];
  8978. if ( ! light.castShadow ) continue;
  8979. if ( light instanceof THREE.SpotLight || ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) ) {
  8980. uniforms.shadowMap.texture[ j ] = light.shadowMap;
  8981. uniforms.shadowMapSize.value[ j ] = light.shadowMapSize;
  8982. uniforms.shadowMatrix.value[ j ] = light.shadowMatrix;
  8983. uniforms.shadowDarkness.value[ j ] = light.shadowDarkness;
  8984. uniforms.shadowBias.value[ j ] = light.shadowBias;
  8985. j ++;
  8986. }
  8987. }
  8988. }
  8989. };
  8990. // Uniforms (load to GPU)
  8991. function loadUniformsMatrices ( uniforms, object ) {
  8992. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, object._modelViewMatrix.elements );
  8993. if ( uniforms.normalMatrix ) {
  8994. _gl.uniformMatrix3fv( uniforms.normalMatrix, false, object._normalMatrixArray );
  8995. }
  8996. };
  8997. function loadUniformsGeneric ( program, uniforms ) {
  8998. var uniform, value, type, location, texture, i, il, j, jl, offset;
  8999. for( j = 0, jl = uniforms.length; j < jl; j ++ ) {
  9000. location = program.uniforms[ uniforms[ j ][ 1 ] ];
  9001. if ( !location ) continue;
  9002. uniform = uniforms[ j ][ 0 ];
  9003. type = uniform.type;
  9004. value = uniform.value;
  9005. // single integer
  9006. if( type === "i" ) {
  9007. _gl.uniform1i( location, value );
  9008. // single float
  9009. } else if( type === "f" ) {
  9010. _gl.uniform1f( location, value );
  9011. // single THREE.Vector2
  9012. } else if( type === "v2" ) {
  9013. _gl.uniform2f( location, value.x, value.y );
  9014. // single THREE.Vector3
  9015. } else if( type === "v3" ) {
  9016. _gl.uniform3f( location, value.x, value.y, value.z );
  9017. // single THREE.Vector4
  9018. } else if( type === "v4" ) {
  9019. _gl.uniform4f( location, value.x, value.y, value.z, value.w );
  9020. // single THREE.Color
  9021. } else if( type === "c" ) {
  9022. _gl.uniform3f( location, value.r, value.g, value.b );
  9023. // flat array of floats (JS or typed array)
  9024. } else if( type === "fv1" ) {
  9025. _gl.uniform1fv( location, value );
  9026. // flat array of floats with 3 x N size (JS or typed array)
  9027. } else if( type === "fv" ) {
  9028. _gl.uniform3fv( location, value );
  9029. // array of THREE.Vector2
  9030. } else if( type === "v2v" ) {
  9031. if ( ! uniform._array ) {
  9032. uniform._array = new Float32Array( 2 * value.length );
  9033. }
  9034. for ( i = 0, il = value.length; i < il; i ++ ) {
  9035. offset = i * 2;
  9036. uniform._array[ offset ] = value[ i ].x;
  9037. uniform._array[ offset + 1 ] = value[ i ].y;
  9038. }
  9039. _gl.uniform2fv( location, uniform._array );
  9040. // array of THREE.Vector3
  9041. } else if( type === "v3v" ) {
  9042. if ( ! uniform._array ) {
  9043. uniform._array = new Float32Array( 3 * value.length );
  9044. }
  9045. for ( i = 0, il = value.length; i < il; i ++ ) {
  9046. offset = i * 3;
  9047. uniform._array[ offset ] = value[ i ].x;
  9048. uniform._array[ offset + 1 ] = value[ i ].y;
  9049. uniform._array[ offset + 2 ] = value[ i ].z;
  9050. }
  9051. _gl.uniform3fv( location, uniform._array );
  9052. // array of THREE.Vector4
  9053. } else if( type == "v4v" ) {
  9054. if ( ! uniform._array ) {
  9055. uniform._array = new Float32Array( 4 * value.length );
  9056. }
  9057. for ( i = 0, il = value.length; i < il; i ++ ) {
  9058. offset = i * 4;
  9059. uniform._array[ offset ] = value[ i ].x;
  9060. uniform._array[ offset + 1 ] = value[ i ].y;
  9061. uniform._array[ offset + 2 ] = value[ i ].z;
  9062. uniform._array[ offset + 3 ] = value[ i ].w;
  9063. }
  9064. _gl.uniform4fv( location, uniform._array );
  9065. // single THREE.Matrix4
  9066. } else if( type === "m4" ) {
  9067. if ( ! uniform._array ) {
  9068. uniform._array = new Float32Array( 16 );
  9069. }
  9070. value.flattenToArray( uniform._array );
  9071. _gl.uniformMatrix4fv( location, false, uniform._array );
  9072. // array of THREE.Matrix4
  9073. } else if( type === "m4v" ) {
  9074. if ( ! uniform._array ) {
  9075. uniform._array = new Float32Array( 16 * value.length );
  9076. }
  9077. for ( i = 0, il = value.length; i < il; i ++ ) {
  9078. value[ i ].flattenToArrayOffset( uniform._array, i * 16 );
  9079. }
  9080. _gl.uniformMatrix4fv( location, false, uniform._array );
  9081. // single THREE.Texture (2d or cube)
  9082. } else if( type === "t" ) {
  9083. _gl.uniform1i( location, value );
  9084. texture = uniform.texture;
  9085. if ( !texture ) continue;
  9086. if ( texture.image instanceof Array && texture.image.length === 6 ) {
  9087. setCubeTexture( texture, value );
  9088. } else if ( texture instanceof THREE.WebGLRenderTargetCube ) {
  9089. setCubeTextureDynamic( texture, value );
  9090. } else {
  9091. _this.setTexture( texture, value );
  9092. }
  9093. // array of THREE.Texture (2d)
  9094. } else if( type === "tv" ) {
  9095. if ( ! uniform._array ) {
  9096. uniform._array = [];
  9097. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  9098. uniform._array[ i ] = value + i;
  9099. }
  9100. }
  9101. _gl.uniform1iv( location, uniform._array );
  9102. for( i = 0, il = uniform.texture.length; i < il; i ++ ) {
  9103. texture = uniform.texture[ i ];
  9104. if ( !texture ) continue;
  9105. _this.setTexture( texture, uniform._array[ i ] );
  9106. }
  9107. }
  9108. }
  9109. };
  9110. function setupMatrices ( object, camera ) {
  9111. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  9112. object._normalMatrix.getInverse( object._modelViewMatrix );
  9113. object._normalMatrix.transposeIntoArray( object._normalMatrixArray );
  9114. };
  9115. function setupLights ( program, lights ) {
  9116. var l, ll, light, n,
  9117. r = 0, g = 0, b = 0,
  9118. color, position, intensity, distance,
  9119. zlights = _lights,
  9120. dcolors = zlights.directional.colors,
  9121. dpositions = zlights.directional.positions,
  9122. pcolors = zlights.point.colors,
  9123. ppositions = zlights.point.positions,
  9124. pdistances = zlights.point.distances,
  9125. dlength = 0,
  9126. plength = 0,
  9127. doffset = 0,
  9128. poffset = 0;
  9129. for ( l = 0, ll = lights.length; l < ll; l ++ ) {
  9130. light = lights[ l ];
  9131. if ( light.onlyShadow ) continue;
  9132. color = light.color;
  9133. intensity = light.intensity;
  9134. distance = light.distance;
  9135. if ( light instanceof THREE.AmbientLight ) {
  9136. if ( _this.gammaInput ) {
  9137. r += color.r * color.r;
  9138. g += color.g * color.g;
  9139. b += color.b * color.b;
  9140. } else {
  9141. r += color.r;
  9142. g += color.g;
  9143. b += color.b;
  9144. }
  9145. } else if ( light instanceof THREE.DirectionalLight ) {
  9146. doffset = dlength * 3;
  9147. if ( _this.gammaInput ) {
  9148. dcolors[ doffset ] = color.r * color.r * intensity * intensity;
  9149. dcolors[ doffset + 1 ] = color.g * color.g * intensity * intensity;
  9150. dcolors[ doffset + 2 ] = color.b * color.b * intensity * intensity;
  9151. } else {
  9152. dcolors[ doffset ] = color.r * intensity;
  9153. dcolors[ doffset + 1 ] = color.g * intensity;
  9154. dcolors[ doffset + 2 ] = color.b * intensity;
  9155. }
  9156. _direction.copy( light.matrixWorld.getPosition() );
  9157. _direction.subSelf( light.target.matrixWorld.getPosition() );
  9158. _direction.normalize();
  9159. dpositions[ doffset ] = _direction.x;
  9160. dpositions[ doffset + 1 ] = _direction.y;
  9161. dpositions[ doffset + 2 ] = _direction.z;
  9162. dlength += 1;
  9163. } else if( light instanceof THREE.PointLight || light instanceof THREE.SpotLight ) {
  9164. poffset = plength * 3;
  9165. if ( _this.gammaInput ) {
  9166. pcolors[ poffset ] = color.r * color.r * intensity * intensity;
  9167. pcolors[ poffset + 1 ] = color.g * color.g * intensity * intensity;
  9168. pcolors[ poffset + 2 ] = color.b * color.b * intensity * intensity;
  9169. } else {
  9170. pcolors[ poffset ] = color.r * intensity;
  9171. pcolors[ poffset + 1 ] = color.g * intensity;
  9172. pcolors[ poffset + 2 ] = color.b * intensity;
  9173. }
  9174. position = light.matrixWorld.getPosition();
  9175. ppositions[ poffset ] = position.x;
  9176. ppositions[ poffset + 1 ] = position.y;
  9177. ppositions[ poffset + 2 ] = position.z;
  9178. pdistances[ plength ] = distance;
  9179. plength += 1;
  9180. }
  9181. }
  9182. // null eventual remains from removed lights
  9183. // (this is to avoid if in shader)
  9184. for ( l = dlength * 3, ll = dcolors.length; l < ll; l ++ ) dcolors[ l ] = 0.0;
  9185. for ( l = plength * 3, ll = pcolors.length; l < ll; l ++ ) pcolors[ l ] = 0.0;
  9186. zlights.point.length = plength;
  9187. zlights.directional.length = dlength;
  9188. zlights.ambient[ 0 ] = r;
  9189. zlights.ambient[ 1 ] = g;
  9190. zlights.ambient[ 2 ] = b;
  9191. };
  9192. // GL state setting
  9193. this.setFaceCulling = function ( cullFace, frontFace ) {
  9194. if ( cullFace ) {
  9195. if ( !frontFace || frontFace === "ccw" ) {
  9196. _gl.frontFace( _gl.CCW );
  9197. } else {
  9198. _gl.frontFace( _gl.CW );
  9199. }
  9200. if( cullFace === "back" ) {
  9201. _gl.cullFace( _gl.BACK );
  9202. } else if( cullFace === "front" ) {
  9203. _gl.cullFace( _gl.FRONT );
  9204. } else {
  9205. _gl.cullFace( _gl.FRONT_AND_BACK );
  9206. }
  9207. _gl.enable( _gl.CULL_FACE );
  9208. } else {
  9209. _gl.disable( _gl.CULL_FACE );
  9210. }
  9211. };
  9212. this.setObjectFaces = function ( object ) {
  9213. if ( _oldDoubleSided !== object.doubleSided ) {
  9214. if( object.doubleSided ) {
  9215. _gl.disable( _gl.CULL_FACE );
  9216. } else {
  9217. _gl.enable( _gl.CULL_FACE );
  9218. }
  9219. _oldDoubleSided = object.doubleSided;
  9220. }
  9221. if ( _oldFlipSided !== object.flipSided ) {
  9222. if( object.flipSided ) {
  9223. _gl.frontFace( _gl.CW );
  9224. } else {
  9225. _gl.frontFace( _gl.CCW );
  9226. }
  9227. _oldFlipSided = object.flipSided;
  9228. }
  9229. };
  9230. this.setDepthTest = function ( depthTest ) {
  9231. if ( _oldDepthTest !== depthTest ) {
  9232. if ( depthTest ) {
  9233. _gl.enable( _gl.DEPTH_TEST );
  9234. } else {
  9235. _gl.disable( _gl.DEPTH_TEST );
  9236. }
  9237. _oldDepthTest = depthTest;
  9238. }
  9239. };
  9240. this.setDepthWrite = function ( depthWrite ) {
  9241. if ( _oldDepthWrite !== depthWrite ) {
  9242. _gl.depthMask( depthWrite );
  9243. _oldDepthWrite = depthWrite;
  9244. }
  9245. };
  9246. function setLineWidth ( width ) {
  9247. if ( width !== _oldLineWidth ) {
  9248. _gl.lineWidth( width );
  9249. _oldLineWidth = width;
  9250. }
  9251. };
  9252. function setPolygonOffset ( polygonoffset, factor, units ) {
  9253. if ( _oldPolygonOffset !== polygonoffset ) {
  9254. if ( polygonoffset ) {
  9255. _gl.enable( _gl.POLYGON_OFFSET_FILL );
  9256. } else {
  9257. _gl.disable( _gl.POLYGON_OFFSET_FILL );
  9258. }
  9259. _oldPolygonOffset = polygonoffset;
  9260. }
  9261. if ( polygonoffset && ( _oldPolygonOffsetFactor !== factor || _oldPolygonOffsetUnits !== units ) ) {
  9262. _gl.polygonOffset( factor, units );
  9263. _oldPolygonOffsetFactor = factor;
  9264. _oldPolygonOffsetUnits = units;
  9265. }
  9266. };
  9267. this.setBlending = function ( blending, blendEquation, blendSrc, blendDst ) {
  9268. if ( blending !== _oldBlending ) {
  9269. switch ( blending ) {
  9270. case THREE.NoBlending:
  9271. _gl.disable( _gl.BLEND );
  9272. break;
  9273. case THREE.AdditiveBlending:
  9274. _gl.enable( _gl.BLEND );
  9275. _gl.blendEquation( _gl.FUNC_ADD );
  9276. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE );
  9277. break;
  9278. case THREE.SubtractiveBlending:
  9279. // TODO: Find blendFuncSeparate() combination
  9280. _gl.enable( _gl.BLEND );
  9281. _gl.blendEquation( _gl.FUNC_ADD );
  9282. _gl.blendFunc( _gl.ZERO, _gl.ONE_MINUS_SRC_COLOR );
  9283. break;
  9284. case THREE.MultiplyBlending:
  9285. // TODO: Find blendFuncSeparate() combination
  9286. _gl.enable( _gl.BLEND );
  9287. _gl.blendEquation( _gl.FUNC_ADD );
  9288. _gl.blendFunc( _gl.ZERO, _gl.SRC_COLOR );
  9289. break;
  9290. case THREE.CustomBlending:
  9291. _gl.enable( _gl.BLEND );
  9292. break;
  9293. default:
  9294. _gl.enable( _gl.BLEND );
  9295. _gl.blendEquationSeparate( _gl.FUNC_ADD, _gl.FUNC_ADD );
  9296. _gl.blendFuncSeparate( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA, _gl.ONE, _gl.ONE_MINUS_SRC_ALPHA );
  9297. break;
  9298. }
  9299. _oldBlending = blending;
  9300. }
  9301. if ( blending === THREE.CustomBlending ) {
  9302. if ( blendEquation !== _oldBlendEquation ) {
  9303. _gl.blendEquation( paramThreeToGL( blendEquation ) );
  9304. _oldBlendEquation = blendEquation;
  9305. }
  9306. if ( blendSrc !== _oldBlendSrc || blendDst !== _oldBlendDst ) {
  9307. _gl.blendFunc( paramThreeToGL( blendSrc ), paramThreeToGL( blendDst ) );
  9308. _oldBlendSrc = blendSrc;
  9309. _oldBlendDst = blendDst;
  9310. }
  9311. } else {
  9312. _oldBlendEquation = null;
  9313. _oldBlendSrc = null;
  9314. _oldBlendDst = null;
  9315. }
  9316. };
  9317. // Shaders
  9318. function buildProgram ( shaderID, fragmentShader, vertexShader, uniforms, attributes, parameters ) {
  9319. var p, pl, program, code;
  9320. var chunks = [];
  9321. // Generate code
  9322. if ( shaderID ) {
  9323. chunks.push( shaderID );
  9324. } else {
  9325. chunks.push( fragmentShader );
  9326. chunks.push( vertexShader );
  9327. }
  9328. for ( p in parameters ) {
  9329. chunks.push( p );
  9330. chunks.push( parameters[ p ] );
  9331. }
  9332. code = chunks.join();
  9333. // Check if code has been already compiled
  9334. for ( p = 0, pl = _programs.length; p < pl; p ++ ) {
  9335. if ( _programs[ p ].code === code ) {
  9336. // console.log( "Code already compiled." /*: \n\n" + code*/ );
  9337. return _programs[ p ].program;
  9338. }
  9339. }
  9340. //console.log( "building new program " );
  9341. //
  9342. program = _gl.createProgram();
  9343. var prefix_vertex = [
  9344. "precision " + _precision + " float;",
  9345. ( _maxVertexTextures > 0 ) ? "#define VERTEX_TEXTURES" : "",
  9346. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  9347. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  9348. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  9349. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  9350. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  9351. "#define MAX_SHADOWS " + parameters.maxShadows,
  9352. "#define MAX_BONES " + parameters.maxBones,
  9353. parameters.map ? "#define USE_MAP" : "",
  9354. parameters.envMap ? "#define USE_ENVMAP" : "",
  9355. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  9356. parameters.vertexColors ? "#define USE_COLOR" : "",
  9357. parameters.skinning ? "#define USE_SKINNING" : "",
  9358. parameters.morphTargets ? "#define USE_MORPHTARGETS" : "",
  9359. parameters.morphNormals ? "#define USE_MORPHNORMALS" : "",
  9360. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  9361. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  9362. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  9363. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  9364. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  9365. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  9366. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  9367. parameters.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "",
  9368. "uniform mat4 objectMatrix;",
  9369. "uniform mat4 modelViewMatrix;",
  9370. "uniform mat4 projectionMatrix;",
  9371. "uniform mat4 viewMatrix;",
  9372. "uniform mat3 normalMatrix;",
  9373. "uniform vec3 cameraPosition;",
  9374. "attribute vec3 position;",
  9375. "attribute vec3 normal;",
  9376. "attribute vec2 uv;",
  9377. "attribute vec2 uv2;",
  9378. "#ifdef USE_COLOR",
  9379. "attribute vec3 color;",
  9380. "#endif",
  9381. "#ifdef USE_MORPHTARGETS",
  9382. "attribute vec3 morphTarget0;",
  9383. "attribute vec3 morphTarget1;",
  9384. "attribute vec3 morphTarget2;",
  9385. "attribute vec3 morphTarget3;",
  9386. "#ifdef USE_MORPHNORMALS",
  9387. "attribute vec3 morphNormal0;",
  9388. "attribute vec3 morphNormal1;",
  9389. "attribute vec3 morphNormal2;",
  9390. "attribute vec3 morphNormal3;",
  9391. "#else",
  9392. "attribute vec3 morphTarget4;",
  9393. "attribute vec3 morphTarget5;",
  9394. "attribute vec3 morphTarget6;",
  9395. "attribute vec3 morphTarget7;",
  9396. "#endif",
  9397. "#endif",
  9398. "#ifdef USE_SKINNING",
  9399. "attribute vec4 skinVertexA;",
  9400. "attribute vec4 skinVertexB;",
  9401. "attribute vec4 skinIndex;",
  9402. "attribute vec4 skinWeight;",
  9403. "#endif",
  9404. ""
  9405. ].join("\n");
  9406. var prefix_fragment = [
  9407. "precision " + _precision + " float;",
  9408. "#define MAX_DIR_LIGHTS " + parameters.maxDirLights,
  9409. "#define MAX_POINT_LIGHTS " + parameters.maxPointLights,
  9410. "#define MAX_SHADOWS " + parameters.maxShadows,
  9411. parameters.alphaTest ? "#define ALPHATEST " + parameters.alphaTest: "",
  9412. _this.gammaInput ? "#define GAMMA_INPUT" : "",
  9413. _this.gammaOutput ? "#define GAMMA_OUTPUT" : "",
  9414. _this.physicallyBasedShading ? "#define PHYSICALLY_BASED_SHADING" : "",
  9415. ( parameters.useFog && parameters.fog ) ? "#define USE_FOG" : "",
  9416. ( parameters.useFog && parameters.fog instanceof THREE.FogExp2 ) ? "#define FOG_EXP2" : "",
  9417. parameters.map ? "#define USE_MAP" : "",
  9418. parameters.envMap ? "#define USE_ENVMAP" : "",
  9419. parameters.lightMap ? "#define USE_LIGHTMAP" : "",
  9420. parameters.vertexColors ? "#define USE_COLOR" : "",
  9421. parameters.metal ? "#define METAL" : "",
  9422. parameters.perPixel ? "#define PHONG_PER_PIXEL" : "",
  9423. parameters.wrapAround ? "#define WRAP_AROUND" : "",
  9424. parameters.doubleSided ? "#define DOUBLE_SIDED" : "",
  9425. parameters.shadowMapEnabled ? "#define USE_SHADOWMAP" : "",
  9426. parameters.shadowMapSoft ? "#define SHADOWMAP_SOFT" : "",
  9427. parameters.shadowMapDebug ? "#define SHADOWMAP_DEBUG" : "",
  9428. parameters.shadowMapCascade ? "#define SHADOWMAP_CASCADE" : "",
  9429. "uniform mat4 viewMatrix;",
  9430. "uniform vec3 cameraPosition;",
  9431. ""
  9432. ].join("\n");
  9433. _gl.attachShader( program, getShader( "fragment", prefix_fragment + fragmentShader ) );
  9434. _gl.attachShader( program, getShader( "vertex", prefix_vertex + vertexShader ) );
  9435. _gl.linkProgram( program );
  9436. if ( !_gl.getProgramParameter( program, _gl.LINK_STATUS ) ) {
  9437. console.error( "Could not initialise shader\n" + "VALIDATE_STATUS: " + _gl.getProgramParameter( program, _gl.VALIDATE_STATUS ) + ", gl error [" + _gl.getError() + "]" );
  9438. }
  9439. //console.log( prefix_fragment + fragmentShader );
  9440. //console.log( prefix_vertex + vertexShader );
  9441. program.uniforms = {};
  9442. program.attributes = {};
  9443. var identifiers, u, a, i;
  9444. // cache uniform locations
  9445. identifiers = [
  9446. 'viewMatrix', 'modelViewMatrix', 'projectionMatrix', 'normalMatrix', 'objectMatrix', 'cameraPosition',
  9447. 'boneGlobalMatrices', 'morphTargetInfluences'
  9448. ];
  9449. for ( u in uniforms ) {
  9450. identifiers.push( u );
  9451. }
  9452. cacheUniformLocations( program, identifiers );
  9453. // cache attributes locations
  9454. identifiers = [
  9455. "position", "normal", "uv", "uv2", "tangent", "color",
  9456. "skinVertexA", "skinVertexB", "skinIndex", "skinWeight"
  9457. ];
  9458. for ( i = 0; i < parameters.maxMorphTargets; i ++ ) {
  9459. identifiers.push( "morphTarget" + i );
  9460. }
  9461. for ( i = 0; i < parameters.maxMorphNormals; i ++ ) {
  9462. identifiers.push( "morphNormal" + i );
  9463. }
  9464. for ( a in attributes ) {
  9465. identifiers.push( a );
  9466. }
  9467. cacheAttributeLocations( program, identifiers );
  9468. program.id = _programs.length;
  9469. _programs.push( { program: program, code: code } );
  9470. _this.info.memory.programs = _programs.length;
  9471. return program;
  9472. };
  9473. // Shader parameters cache
  9474. function cacheUniformLocations ( program, identifiers ) {
  9475. var i, l, id;
  9476. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  9477. id = identifiers[ i ];
  9478. program.uniforms[ id ] = _gl.getUniformLocation( program, id );
  9479. }
  9480. };
  9481. function cacheAttributeLocations ( program, identifiers ) {
  9482. var i, l, id;
  9483. for( i = 0, l = identifiers.length; i < l; i ++ ) {
  9484. id = identifiers[ i ];
  9485. program.attributes[ id ] = _gl.getAttribLocation( program, id );
  9486. }
  9487. };
  9488. function getShader ( type, string ) {
  9489. var shader;
  9490. if ( type === "fragment" ) {
  9491. shader = _gl.createShader( _gl.FRAGMENT_SHADER );
  9492. } else if ( type === "vertex" ) {
  9493. shader = _gl.createShader( _gl.VERTEX_SHADER );
  9494. }
  9495. _gl.shaderSource( shader, string );
  9496. _gl.compileShader( shader );
  9497. if ( !_gl.getShaderParameter( shader, _gl.COMPILE_STATUS ) ) {
  9498. console.error( _gl.getShaderInfoLog( shader ) );
  9499. console.error( string );
  9500. return null;
  9501. }
  9502. return shader;
  9503. };
  9504. // Textures
  9505. function isPowerOfTwo ( value ) {
  9506. return ( value & ( value - 1 ) ) === 0;
  9507. };
  9508. function setTextureParameters ( textureType, texture, isImagePowerOfTwo ) {
  9509. if ( isImagePowerOfTwo ) {
  9510. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, paramThreeToGL( texture.wrapS ) );
  9511. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, paramThreeToGL( texture.wrapT ) );
  9512. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, paramThreeToGL( texture.magFilter ) );
  9513. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, paramThreeToGL( texture.minFilter ) );
  9514. } else {
  9515. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  9516. _gl.texParameteri( textureType, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  9517. _gl.texParameteri( textureType, _gl.TEXTURE_MAG_FILTER, filterFallback( texture.magFilter ) );
  9518. _gl.texParameteri( textureType, _gl.TEXTURE_MIN_FILTER, filterFallback( texture.minFilter ) );
  9519. }
  9520. };
  9521. this.setTexture = function ( texture, slot ) {
  9522. if ( texture.needsUpdate ) {
  9523. if ( ! texture.__webglInit ) {
  9524. texture.__webglInit = true;
  9525. texture.__webglTexture = _gl.createTexture();
  9526. _this.info.memory.textures ++;
  9527. }
  9528. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9529. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  9530. _gl.pixelStorei( _gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultiplyAlpha );
  9531. var image = texture.image,
  9532. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  9533. glFormat = paramThreeToGL( texture.format ),
  9534. glType = paramThreeToGL( texture.type );
  9535. setTextureParameters( _gl.TEXTURE_2D, texture, isImagePowerOfTwo );
  9536. if ( texture instanceof THREE.DataTexture ) {
  9537. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, image.width, image.height, 0, glFormat, glType, image.data );
  9538. } else {
  9539. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, glFormat, glType, texture.image );
  9540. }
  9541. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  9542. texture.needsUpdate = false;
  9543. if ( texture.onUpdate ) texture.onUpdate();
  9544. } else {
  9545. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9546. _gl.bindTexture( _gl.TEXTURE_2D, texture.__webglTexture );
  9547. }
  9548. };
  9549. function clampToMaxSize ( image, maxSize ) {
  9550. if ( image.width <= maxSize && image.height <= maxSize ) {
  9551. return image;
  9552. }
  9553. // Warning: Scaling through the canvas will only work with images that use
  9554. // premultiplied alpha.
  9555. var maxDimension = Math.max( image.width, image.height );
  9556. var newWidth = Math.floor( image.width * maxSize / maxDimension );
  9557. var newHeight = Math.floor( image.height * maxSize / maxDimension );
  9558. var canvas = document.createElement( 'canvas' );
  9559. canvas.width = newWidth;
  9560. canvas.height = newHeight;
  9561. var ctx = canvas.getContext( "2d" );
  9562. ctx.drawImage( image, 0, 0, image.width, image.height, 0, 0, newWidth, newHeight );
  9563. return canvas;
  9564. }
  9565. function setCubeTexture ( texture, slot ) {
  9566. if ( texture.image.length === 6 ) {
  9567. if ( texture.needsUpdate ) {
  9568. if ( ! texture.image.__webglTextureCube ) {
  9569. texture.image.__webglTextureCube = _gl.createTexture();
  9570. }
  9571. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9572. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  9573. var cubeImage = [];
  9574. for ( var i = 0; i < 6; i ++ ) {
  9575. if ( _this.autoScaleCubemaps ) {
  9576. cubeImage[ i ] = clampToMaxSize( texture.image[ i ], _maxCubemapSize );
  9577. } else {
  9578. cubeImage[ i ] = texture.image[ i ];
  9579. }
  9580. }
  9581. var image = cubeImage[ 0 ],
  9582. isImagePowerOfTwo = isPowerOfTwo( image.width ) && isPowerOfTwo( image.height ),
  9583. glFormat = paramThreeToGL( texture.format ),
  9584. glType = paramThreeToGL( texture.type );
  9585. setTextureParameters( _gl.TEXTURE_CUBE_MAP, texture, isImagePowerOfTwo );
  9586. for ( var i = 0; i < 6; i ++ ) {
  9587. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, glFormat, glType, cubeImage[ i ] );
  9588. }
  9589. if ( texture.generateMipmaps && isImagePowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9590. texture.needsUpdate = false;
  9591. if ( texture.onUpdate ) texture.onUpdate();
  9592. } else {
  9593. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9594. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.image.__webglTextureCube );
  9595. }
  9596. }
  9597. };
  9598. function setCubeTextureDynamic ( texture, slot ) {
  9599. _gl.activeTexture( _gl.TEXTURE0 + slot );
  9600. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, texture.__webglTexture );
  9601. };
  9602. // Render targets
  9603. function setupFrameBuffer ( framebuffer, renderTarget, textureTarget ) {
  9604. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  9605. _gl.framebufferTexture2D( _gl.FRAMEBUFFER, _gl.COLOR_ATTACHMENT0, textureTarget, renderTarget.__webglTexture, 0 );
  9606. };
  9607. function setupRenderBuffer ( renderbuffer, renderTarget ) {
  9608. _gl.bindRenderbuffer( _gl.RENDERBUFFER, renderbuffer );
  9609. if ( renderTarget.depthBuffer && ! renderTarget.stencilBuffer ) {
  9610. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_COMPONENT16, renderTarget.width, renderTarget.height );
  9611. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9612. /* For some reason this is not working. Defaulting to RGBA4.
  9613. } else if( ! renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  9614. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.STENCIL_INDEX8, renderTarget.width, renderTarget.height );
  9615. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9616. */
  9617. } else if( renderTarget.depthBuffer && renderTarget.stencilBuffer ) {
  9618. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.DEPTH_STENCIL, renderTarget.width, renderTarget.height );
  9619. _gl.framebufferRenderbuffer( _gl.FRAMEBUFFER, _gl.DEPTH_STENCIL_ATTACHMENT, _gl.RENDERBUFFER, renderbuffer );
  9620. } else {
  9621. _gl.renderbufferStorage( _gl.RENDERBUFFER, _gl.RGBA4, renderTarget.width, renderTarget.height );
  9622. }
  9623. };
  9624. this.setRenderTarget = function ( renderTarget ) {
  9625. var isCube = ( renderTarget instanceof THREE.WebGLRenderTargetCube );
  9626. if ( renderTarget && ! renderTarget.__webglFramebuffer ) {
  9627. if( renderTarget.depthBuffer === undefined ) renderTarget.depthBuffer = true;
  9628. if( renderTarget.stencilBuffer === undefined ) renderTarget.stencilBuffer = true;
  9629. renderTarget.__webglTexture = _gl.createTexture();
  9630. // Setup texture, create render and frame buffers
  9631. var isTargetPowerOfTwo = isPowerOfTwo( renderTarget.width ) && isPowerOfTwo( renderTarget.height ),
  9632. glFormat = paramThreeToGL( renderTarget.format ),
  9633. glType = paramThreeToGL( renderTarget.type );
  9634. if ( isCube ) {
  9635. renderTarget.__webglFramebuffer = [];
  9636. renderTarget.__webglRenderbuffer = [];
  9637. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  9638. setTextureParameters( _gl.TEXTURE_CUBE_MAP, renderTarget, isTargetPowerOfTwo );
  9639. for ( var i = 0; i < 6; i ++ ) {
  9640. renderTarget.__webglFramebuffer[ i ] = _gl.createFramebuffer();
  9641. renderTarget.__webglRenderbuffer[ i ] = _gl.createRenderbuffer();
  9642. _gl.texImage2D( _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  9643. setupFrameBuffer( renderTarget.__webglFramebuffer[ i ], renderTarget, _gl.TEXTURE_CUBE_MAP_POSITIVE_X + i );
  9644. setupRenderBuffer( renderTarget.__webglRenderbuffer[ i ], renderTarget );
  9645. }
  9646. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9647. } else {
  9648. renderTarget.__webglFramebuffer = _gl.createFramebuffer();
  9649. renderTarget.__webglRenderbuffer = _gl.createRenderbuffer();
  9650. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  9651. setTextureParameters( _gl.TEXTURE_2D, renderTarget, isTargetPowerOfTwo );
  9652. _gl.texImage2D( _gl.TEXTURE_2D, 0, glFormat, renderTarget.width, renderTarget.height, 0, glFormat, glType, null );
  9653. setupFrameBuffer( renderTarget.__webglFramebuffer, renderTarget, _gl.TEXTURE_2D );
  9654. setupRenderBuffer( renderTarget.__webglRenderbuffer, renderTarget );
  9655. if ( isTargetPowerOfTwo ) _gl.generateMipmap( _gl.TEXTURE_2D );
  9656. }
  9657. // Release everything
  9658. if ( isCube ) {
  9659. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  9660. } else {
  9661. _gl.bindTexture( _gl.TEXTURE_2D, null );
  9662. }
  9663. _gl.bindRenderbuffer( _gl.RENDERBUFFER, null );
  9664. _gl.bindFramebuffer( _gl.FRAMEBUFFER, null);
  9665. }
  9666. var framebuffer, width, height, vx, vy;
  9667. if ( renderTarget ) {
  9668. if ( isCube ) {
  9669. framebuffer = renderTarget.__webglFramebuffer[ renderTarget.activeCubeFace ];
  9670. } else {
  9671. framebuffer = renderTarget.__webglFramebuffer;
  9672. }
  9673. width = renderTarget.width;
  9674. height = renderTarget.height;
  9675. vx = 0;
  9676. vy = 0;
  9677. } else {
  9678. framebuffer = null;
  9679. width = _viewportWidth;
  9680. height = _viewportHeight;
  9681. vx = _viewportX;
  9682. vy = _viewportY;
  9683. }
  9684. if ( framebuffer !== _currentFramebuffer ) {
  9685. _gl.bindFramebuffer( _gl.FRAMEBUFFER, framebuffer );
  9686. _gl.viewport( vx, vy, width, height );
  9687. _currentFramebuffer = framebuffer;
  9688. }
  9689. _currentWidth = width;
  9690. _currentHeight = height;
  9691. };
  9692. function updateRenderTargetMipmap ( renderTarget ) {
  9693. if ( renderTarget instanceof THREE.WebGLRenderTargetCube ) {
  9694. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, renderTarget.__webglTexture );
  9695. _gl.generateMipmap( _gl.TEXTURE_CUBE_MAP );
  9696. _gl.bindTexture( _gl.TEXTURE_CUBE_MAP, null );
  9697. } else {
  9698. _gl.bindTexture( _gl.TEXTURE_2D, renderTarget.__webglTexture );
  9699. _gl.generateMipmap( _gl.TEXTURE_2D );
  9700. _gl.bindTexture( _gl.TEXTURE_2D, null );
  9701. }
  9702. };
  9703. // Fallback filters for non-power-of-2 textures
  9704. function filterFallback ( f ) {
  9705. switch ( f ) {
  9706. case THREE.NearestFilter:
  9707. case THREE.NearestMipMapNearestFilter:
  9708. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST; break;
  9709. case THREE.LinearFilter:
  9710. case THREE.LinearMipMapNearestFilter:
  9711. case THREE.LinearMipMapLinearFilter:
  9712. default:
  9713. return _gl.LINEAR; break;
  9714. }
  9715. };
  9716. // Map three.js constants to WebGL constants
  9717. function paramThreeToGL ( p ) {
  9718. switch ( p ) {
  9719. case THREE.RepeatWrapping: return _gl.REPEAT; break;
  9720. case THREE.ClampToEdgeWrapping: return _gl.CLAMP_TO_EDGE; break;
  9721. case THREE.MirroredRepeatWrapping: return _gl.MIRRORED_REPEAT; break;
  9722. case THREE.NearestFilter: return _gl.NEAREST; break;
  9723. case THREE.NearestMipMapNearestFilter: return _gl.NEAREST_MIPMAP_NEAREST; break;
  9724. case THREE.NearestMipMapLinearFilter: return _gl.NEAREST_MIPMAP_LINEAR; break;
  9725. case THREE.LinearFilter: return _gl.LINEAR; break;
  9726. case THREE.LinearMipMapNearestFilter: return _gl.LINEAR_MIPMAP_NEAREST; break;
  9727. case THREE.LinearMipMapLinearFilter: return _gl.LINEAR_MIPMAP_LINEAR; break;
  9728. case THREE.ByteType: return _gl.BYTE; break;
  9729. case THREE.UnsignedByteType: return _gl.UNSIGNED_BYTE; break;
  9730. case THREE.ShortType: return _gl.SHORT; break;
  9731. case THREE.UnsignedShortType: return _gl.UNSIGNED_SHORT; break;
  9732. case THREE.IntType: return _gl.INT; break;
  9733. case THREE.UnsignedIntType: return _gl.UNSIGNED_INT; break;
  9734. case THREE.FloatType: return _gl.FLOAT; break;
  9735. case THREE.AlphaFormat: return _gl.ALPHA; break;
  9736. case THREE.RGBFormat: return _gl.RGB; break;
  9737. case THREE.RGBAFormat: return _gl.RGBA; break;
  9738. case THREE.LuminanceFormat: return _gl.LUMINANCE; break;
  9739. case THREE.LuminanceAlphaFormat: return _gl.LUMINANCE_ALPHA; break;
  9740. case THREE.AddEquation: return _gl.FUNC_ADD; break;
  9741. case THREE.SubtractEquation: return _gl.FUNC_SUBTRACT; break;
  9742. case THREE.ReverseSubtractEquation: return _gl.FUNC_REVERSE_SUBTRACT; break;
  9743. case THREE.ZeroFactor: return _gl.ZERO; break;
  9744. case THREE.OneFactor: return _gl.ONE; break;
  9745. case THREE.SrcColorFactor: return _gl.SRC_COLOR; break;
  9746. case THREE.OneMinusSrcColorFactor: return _gl.ONE_MINUS_SRC_COLOR; break;
  9747. case THREE.SrcAlphaFactor: return _gl.SRC_ALPHA; break;
  9748. case THREE.OneMinusSrcAlphaFactor: return _gl.ONE_MINUS_SRC_ALPHA; break;
  9749. case THREE.DstAlphaFactor: return _gl.DST_ALPHA; break;
  9750. case THREE.OneMinusDstAlphaFactor: return _gl.ONE_MINUS_DST_ALPHA; break;
  9751. case THREE.DstColorFactor: return _gl.DST_COLOR; break;
  9752. case THREE.OneMinusDstColorFactor: return _gl.ONE_MINUS_DST_COLOR; break;
  9753. case THREE.SrcAlphaSaturateFactor: return _gl.SRC_ALPHA_SATURATE; break;
  9754. }
  9755. return 0;
  9756. };
  9757. // Allocations
  9758. function allocateBones ( object ) {
  9759. // default for when object is not specified
  9760. // ( for example when prebuilding shader
  9761. // to be used with multiple objects )
  9762. //
  9763. // - leave some extra space for other uniforms
  9764. // - limit here is ANGLE's 254 max uniform vectors
  9765. // (up to 54 should be safe)
  9766. var maxBones = 50;
  9767. if ( object !== undefined && object instanceof THREE.SkinnedMesh ) {
  9768. maxBones = object.bones.length;
  9769. }
  9770. return maxBones;
  9771. };
  9772. function allocateLights ( lights ) {
  9773. var l, ll, light, dirLights, pointLights, maxDirLights, maxPointLights;
  9774. dirLights = pointLights = maxDirLights = maxPointLights = 0;
  9775. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  9776. light = lights[ l ];
  9777. if ( light.onlyShadow ) continue;
  9778. if ( light instanceof THREE.DirectionalLight ) dirLights ++;
  9779. if ( light instanceof THREE.PointLight ) pointLights ++;
  9780. if ( light instanceof THREE.SpotLight ) pointLights ++;
  9781. }
  9782. if ( ( pointLights + dirLights ) <= _maxLights ) {
  9783. maxDirLights = dirLights;
  9784. maxPointLights = pointLights;
  9785. } else {
  9786. maxDirLights = Math.ceil( _maxLights * dirLights / ( pointLights + dirLights ) );
  9787. maxPointLights = _maxLights - maxDirLights;
  9788. }
  9789. return { 'directional' : maxDirLights, 'point' : maxPointLights };
  9790. };
  9791. function allocateShadows ( lights ) {
  9792. var l, ll, light, maxShadows = 0;
  9793. for ( l = 0, ll = lights.length; l < ll; l++ ) {
  9794. light = lights[ l ];
  9795. if ( ! light.castShadow ) continue;
  9796. if ( light instanceof THREE.SpotLight ) maxShadows ++;
  9797. if ( light instanceof THREE.DirectionalLight && ! light.shadowCascade ) maxShadows ++;
  9798. }
  9799. return maxShadows;
  9800. };
  9801. // Initialization
  9802. function initGL () {
  9803. var gl;
  9804. try {
  9805. if ( ! ( gl = _canvas.getContext( 'experimental-webgl', { alpha: _alpha, premultipliedAlpha: _premultipliedAlpha, antialias: _antialias, stencil: _stencil, preserveDrawingBuffer: _preserveDrawingBuffer } ) ) ) {
  9806. throw 'Error creating WebGL context.';
  9807. }
  9808. console.log(
  9809. navigator.userAgent + " | " +
  9810. gl.getParameter( gl.VERSION ) + " | " +
  9811. gl.getParameter( gl.VENDOR ) + " | " +
  9812. gl.getParameter( gl.RENDERER ) + " | " +
  9813. gl.getParameter( gl.SHADING_LANGUAGE_VERSION )
  9814. );
  9815. } catch ( error ) {
  9816. console.error( error );
  9817. }
  9818. return gl;
  9819. };
  9820. function setDefaultGLState () {
  9821. _gl.clearColor( 0, 0, 0, 1 );
  9822. _gl.clearDepth( 1 );
  9823. _gl.clearStencil( 0 );
  9824. _gl.enable( _gl.DEPTH_TEST );
  9825. _gl.depthFunc( _gl.LEQUAL );
  9826. _gl.frontFace( _gl.CCW );
  9827. _gl.cullFace( _gl.BACK );
  9828. _gl.enable( _gl.CULL_FACE );
  9829. _gl.enable( _gl.BLEND );
  9830. _gl.blendEquation( _gl.FUNC_ADD );
  9831. _gl.blendFunc( _gl.SRC_ALPHA, _gl.ONE_MINUS_SRC_ALPHA );
  9832. _gl.clearColor( _clearColor.r, _clearColor.g, _clearColor.b, _clearAlpha );
  9833. };
  9834. // default plugins (order is important)
  9835. this.shadowMapPlugin = new THREE.ShadowMapPlugin();
  9836. this.addPrePlugin( this.shadowMapPlugin );
  9837. this.addPostPlugin( new THREE.SpritePlugin() );
  9838. this.addPostPlugin( new THREE.LensFlarePlugin() );
  9839. };
  9840. /**
  9841. * @author szimek / https://github.com/szimek/
  9842. */
  9843. THREE.WebGLRenderTarget = function ( width, height, options ) {
  9844. this.width = width;
  9845. this.height = height;
  9846. options = options || {};
  9847. this.wrapS = options.wrapS !== undefined ? options.wrapS : THREE.ClampToEdgeWrapping;
  9848. this.wrapT = options.wrapT !== undefined ? options.wrapT : THREE.ClampToEdgeWrapping;
  9849. this.magFilter = options.magFilter !== undefined ? options.magFilter : THREE.LinearFilter;
  9850. this.minFilter = options.minFilter !== undefined ? options.minFilter : THREE.LinearMipMapLinearFilter;
  9851. this.offset = new THREE.Vector2( 0, 0 );
  9852. this.repeat = new THREE.Vector2( 1, 1 );
  9853. this.format = options.format !== undefined ? options.format : THREE.RGBAFormat;
  9854. this.type = options.type !== undefined ? options.type : THREE.UnsignedByteType;
  9855. this.depthBuffer = options.depthBuffer !== undefined ? options.depthBuffer : true;
  9856. this.stencilBuffer = options.stencilBuffer !== undefined ? options.stencilBuffer : true;
  9857. this.generateMipmaps = true;
  9858. };
  9859. THREE.WebGLRenderTarget.prototype.clone = function() {
  9860. var tmp = new THREE.WebGLRenderTarget( this.width, this.height );
  9861. tmp.wrapS = this.wrapS;
  9862. tmp.wrapT = this.wrapT;
  9863. tmp.magFilter = this.magFilter;
  9864. tmp.minFilter = this.minFilter;
  9865. tmp.offset.copy( this.offset );
  9866. tmp.repeat.copy( this.repeat );
  9867. tmp.format = this.format;
  9868. tmp.type = this.type;
  9869. tmp.depthBuffer = this.depthBuffer;
  9870. tmp.stencilBuffer = this.stencilBuffer;
  9871. return tmp;
  9872. };
  9873. /**
  9874. * @author alteredq / http://alteredqualia.com
  9875. */
  9876. THREE.WebGLRenderTargetCube = function ( width, height, options ) {
  9877. THREE.WebGLRenderTarget.call( this, width, height, options );
  9878. this.activeCubeFace = 0; // PX 0, NX 1, PY 2, NY 3, PZ 4, NZ 5
  9879. };
  9880. THREE.WebGLRenderTargetCube.prototype = new THREE.WebGLRenderTarget();
  9881. THREE.WebGLRenderTargetCube.prototype.constructor = THREE.WebGLRenderTargetCube;
  9882. /**
  9883. * @author mr.doob / http://mrdoob.com/
  9884. */
  9885. THREE.RenderableVertex = function () {
  9886. this.positionWorld = new THREE.Vector3();
  9887. this.positionScreen = new THREE.Vector4();
  9888. this.visible = true;
  9889. };
  9890. THREE.RenderableVertex.prototype.copy = function ( vertex ) {
  9891. this.positionWorld.copy( vertex.positionWorld );
  9892. this.positionScreen.copy( vertex.positionScreen );
  9893. }
  9894. /**
  9895. * @author mr.doob / http://mrdoob.com/
  9896. */
  9897. THREE.RenderableFace3 = function () {
  9898. this.v1 = new THREE.RenderableVertex();
  9899. this.v2 = new THREE.RenderableVertex();
  9900. this.v3 = new THREE.RenderableVertex();
  9901. this.centroidWorld = new THREE.Vector3();
  9902. this.centroidScreen = new THREE.Vector3();
  9903. this.normalWorld = new THREE.Vector3();
  9904. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  9905. this.material = null;
  9906. this.faceMaterial = null;
  9907. this.uvs = [[]];
  9908. this.z = null;
  9909. };
  9910. /**
  9911. * @author mr.doob / http://mrdoob.com/
  9912. */
  9913. THREE.RenderableFace4 = function () {
  9914. this.v1 = new THREE.RenderableVertex();
  9915. this.v2 = new THREE.RenderableVertex();
  9916. this.v3 = new THREE.RenderableVertex();
  9917. this.v4 = new THREE.RenderableVertex();
  9918. this.centroidWorld = new THREE.Vector3();
  9919. this.centroidScreen = new THREE.Vector3();
  9920. this.normalWorld = new THREE.Vector3();
  9921. this.vertexNormalsWorld = [ new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3() ];
  9922. this.material = null;
  9923. this.faceMaterial = null;
  9924. this.uvs = [[]];
  9925. this.z = null;
  9926. };
  9927. /**
  9928. * @author mr.doob / http://mrdoob.com/
  9929. */
  9930. THREE.RenderableObject = function () {
  9931. this.object = null;
  9932. this.z = null;
  9933. };
  9934. /**
  9935. * @author mr.doob / http://mrdoob.com/
  9936. */
  9937. THREE.RenderableParticle = function () {
  9938. this.x = null;
  9939. this.y = null;
  9940. this.z = null;
  9941. this.rotation = null;
  9942. this.scale = new THREE.Vector2();
  9943. this.material = null;
  9944. };
  9945. /**
  9946. * @author mr.doob / http://mrdoob.com/
  9947. */
  9948. THREE.RenderableLine = function () {
  9949. this.z = null;
  9950. this.v1 = new THREE.RenderableVertex();
  9951. this.v2 = new THREE.RenderableVertex();
  9952. this.material = null;
  9953. };
  9954. /**
  9955. * @author alteredq / http://alteredqualia.com/
  9956. */
  9957. THREE.ColorUtils = {
  9958. adjustHSV : function ( color, h, s, v ) {
  9959. var hsv = THREE.ColorUtils.__hsv;
  9960. THREE.ColorUtils.rgbToHsv( color, hsv );
  9961. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  9962. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  9963. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  9964. color.setHSV( hsv.h, hsv.s, hsv.v );
  9965. },
  9966. // based on MochiKit implementation by Bob Ippolito
  9967. rgbToHsv : function ( color, hsv ) {
  9968. var r = color.r;
  9969. var g = color.g;
  9970. var b = color.b;
  9971. var max = Math.max( Math.max( r, g ), b );
  9972. var min = Math.min( Math.min( r, g ), b );
  9973. var hue;
  9974. var saturation;
  9975. var value = max;
  9976. if ( min === max ) {
  9977. hue = 0;
  9978. saturation = 0;
  9979. } else {
  9980. var delta = ( max - min );
  9981. saturation = delta / max;
  9982. if ( r === max ) {
  9983. hue = ( g - b ) / delta;
  9984. } else if ( g === max ) {
  9985. hue = 2 + ( ( b - r ) / delta );
  9986. } else {
  9987. hue = 4 + ( ( r - g ) / delta );
  9988. }
  9989. hue /= 6;
  9990. if ( hue < 0 ) {
  9991. hue += 1;
  9992. }
  9993. if ( hue > 1 ) {
  9994. hue -= 1;
  9995. }
  9996. }
  9997. if ( hsv === undefined ) {
  9998. hsv = { h: 0, s: 0, v: 0 };
  9999. }
  10000. hsv.h = hue;
  10001. hsv.s = saturation;
  10002. hsv.v = value;
  10003. return hsv;
  10004. }
  10005. };
  10006. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  10007. * @author mrdoob / http://mrdoob.com/
  10008. * @author alteredq / http://alteredqualia.com/
  10009. */
  10010. THREE.GeometryUtils = {
  10011. // Merge two geometries or geometry and geometry from object (using object's transform)
  10012. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  10013. var matrix, matrixRotation,
  10014. vertexOffset = geometry1.vertices.length,
  10015. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  10016. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  10017. vertices1 = geometry1.vertices,
  10018. vertices2 = geometry2.vertices,
  10019. faces1 = geometry1.faces,
  10020. faces2 = geometry2.faces,
  10021. uvs1 = geometry1.faceVertexUvs[ 0 ],
  10022. uvs2 = geometry2.faceVertexUvs[ 0 ];
  10023. var geo1MaterialsMap = {};
  10024. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  10025. var id = geometry1.materials[ i ].id;
  10026. geo1MaterialsMap[ id ] = i;
  10027. }
  10028. if ( object2 instanceof THREE.Mesh ) {
  10029. object2.matrixAutoUpdate && object2.updateMatrix();
  10030. matrix = object2.matrix;
  10031. matrixRotation = new THREE.Matrix4();
  10032. matrixRotation.extractRotation( matrix, object2.scale );
  10033. }
  10034. // vertices
  10035. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  10036. var vertex = vertices2[ i ];
  10037. var vertexCopy = vertex.clone();
  10038. if ( matrix ) matrix.multiplyVector3( vertexCopy.position );
  10039. vertices1.push( vertexCopy );
  10040. }
  10041. // faces
  10042. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  10043. var face = faces2[ i ], faceCopy, normal, color,
  10044. faceVertexNormals = face.vertexNormals,
  10045. faceVertexColors = face.vertexColors;
  10046. if ( face instanceof THREE.Face3 ) {
  10047. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  10048. } else if ( face instanceof THREE.Face4 ) {
  10049. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  10050. }
  10051. faceCopy.normal.copy( face.normal );
  10052. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  10053. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  10054. normal = faceVertexNormals[ j ].clone();
  10055. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  10056. faceCopy.vertexNormals.push( normal );
  10057. }
  10058. faceCopy.color.copy( face.color );
  10059. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  10060. color = faceVertexColors[ j ];
  10061. faceCopy.vertexColors.push( color.clone() );
  10062. }
  10063. if ( face.materialIndex !== undefined ) {
  10064. var material2 = geometry2.materials[ face.materialIndex ];
  10065. var materialId2 = material2.id;
  10066. var materialIndex = geo1MaterialsMap[ materialId2 ];
  10067. if ( materialIndex === undefined ) {
  10068. materialIndex = geometry1.materials.length;
  10069. geo1MaterialsMap[ materialId2 ] = materialIndex;
  10070. geometry1.materials.push( material2 );
  10071. }
  10072. faceCopy.materialIndex = materialIndex;
  10073. }
  10074. faceCopy.centroid.copy( face.centroid );
  10075. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  10076. faces1.push( faceCopy );
  10077. }
  10078. // uvs
  10079. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  10080. var uv = uvs2[ i ], uvCopy = [];
  10081. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10082. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  10083. }
  10084. uvs1.push( uvCopy );
  10085. }
  10086. },
  10087. clone: function ( geometry ) {
  10088. var cloneGeo = new THREE.Geometry();
  10089. var i, il;
  10090. var vertices = geometry.vertices,
  10091. faces = geometry.faces,
  10092. uvs = geometry.faceVertexUvs[ 0 ];
  10093. // materials
  10094. if ( geometry.materials ) {
  10095. cloneGeo.materials = geometry.materials.slice();
  10096. }
  10097. // vertices
  10098. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  10099. var vertex = vertices[ i ];
  10100. cloneGeo.vertices.push( vertex.clone() );
  10101. }
  10102. // faces
  10103. for ( i = 0, il = faces.length; i < il; i ++ ) {
  10104. var face = faces[ i ];
  10105. cloneGeo.faces.push( face.clone() );
  10106. }
  10107. // uvs
  10108. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  10109. var uv = uvs[ i ], uvCopy = [];
  10110. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  10111. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  10112. }
  10113. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  10114. }
  10115. return cloneGeo;
  10116. },
  10117. // Get random point in triangle (via barycentric coordinates)
  10118. // (uniform distribution)
  10119. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  10120. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  10121. var a, b, c,
  10122. point = new THREE.Vector3(),
  10123. tmp = THREE.GeometryUtils.__v1;
  10124. a = THREE.GeometryUtils.random();
  10125. b = THREE.GeometryUtils.random();
  10126. if ( ( a + b ) > 1 ) {
  10127. a = 1 - a;
  10128. b = 1 - b;
  10129. }
  10130. c = 1 - a - b;
  10131. point.copy( vectorA );
  10132. point.multiplyScalar( a );
  10133. tmp.copy( vectorB );
  10134. tmp.multiplyScalar( b );
  10135. point.addSelf( tmp );
  10136. tmp.copy( vectorC );
  10137. tmp.multiplyScalar( c );
  10138. point.addSelf( tmp );
  10139. return point;
  10140. },
  10141. // Get random point in face (triangle / quad)
  10142. // (uniform distribution)
  10143. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  10144. var vA, vB, vC, vD;
  10145. if ( face instanceof THREE.Face3 ) {
  10146. vA = geometry.vertices[ face.a ].position;
  10147. vB = geometry.vertices[ face.b ].position;
  10148. vC = geometry.vertices[ face.c ].position;
  10149. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  10150. } else if ( face instanceof THREE.Face4 ) {
  10151. vA = geometry.vertices[ face.a ].position;
  10152. vB = geometry.vertices[ face.b ].position;
  10153. vC = geometry.vertices[ face.c ].position;
  10154. vD = geometry.vertices[ face.d ].position;
  10155. var area1, area2;
  10156. if ( useCachedAreas ) {
  10157. if ( face._area1 && face._area2 ) {
  10158. area1 = face._area1;
  10159. area2 = face._area2;
  10160. } else {
  10161. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  10162. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10163. face._area1 = area1;
  10164. face._area2 = area2;
  10165. }
  10166. } else {
  10167. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  10168. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10169. }
  10170. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  10171. if ( r < area1 ) {
  10172. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  10173. } else {
  10174. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  10175. }
  10176. }
  10177. },
  10178. // Get uniformly distributed random points in mesh
  10179. // - create array with cumulative sums of face areas
  10180. // - pick random number from 0 to total area
  10181. // - find corresponding place in area array by binary search
  10182. // - get random point in face
  10183. randomPointsInGeometry: function ( geometry, n ) {
  10184. var face, i,
  10185. faces = geometry.faces,
  10186. vertices = geometry.vertices,
  10187. il = faces.length,
  10188. totalArea = 0,
  10189. cumulativeAreas = [],
  10190. vA, vB, vC, vD;
  10191. // precompute face areas
  10192. for ( i = 0; i < il; i ++ ) {
  10193. face = faces[ i ];
  10194. if ( face instanceof THREE.Face3 ) {
  10195. vA = vertices[ face.a ].position;
  10196. vB = vertices[ face.b ].position;
  10197. vC = vertices[ face.c ].position;
  10198. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  10199. } else if ( face instanceof THREE.Face4 ) {
  10200. vA = vertices[ face.a ].position;
  10201. vB = vertices[ face.b ].position;
  10202. vC = vertices[ face.c ].position;
  10203. vD = vertices[ face.d ].position;
  10204. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  10205. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  10206. face._area = face._area1 + face._area2;
  10207. }
  10208. totalArea += face._area;
  10209. cumulativeAreas[ i ] = totalArea;
  10210. }
  10211. // binary search cumulative areas array
  10212. function binarySearchIndices( value ) {
  10213. function binarySearch( start, end ) {
  10214. // return closest larger index
  10215. // if exact number is not found
  10216. if ( end < start )
  10217. return start;
  10218. var mid = start + Math.floor( ( end - start ) / 2 );
  10219. if ( cumulativeAreas[ mid ] > value ) {
  10220. return binarySearch( start, mid - 1 );
  10221. } else if ( cumulativeAreas[ mid ] < value ) {
  10222. return binarySearch( mid + 1, end );
  10223. } else {
  10224. return mid;
  10225. }
  10226. }
  10227. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  10228. return result;
  10229. }
  10230. // pick random face weighted by face area
  10231. var r, index,
  10232. result = [];
  10233. var stats = {};
  10234. for ( i = 0; i < n; i ++ ) {
  10235. r = THREE.GeometryUtils.random() * totalArea;
  10236. index = binarySearchIndices( r );
  10237. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  10238. if ( ! stats[ index ] ) {
  10239. stats[ index ] = 1;
  10240. } else {
  10241. stats[ index ] += 1;
  10242. }
  10243. }
  10244. return result;
  10245. },
  10246. // Get triangle area (by Heron's formula)
  10247. // http://en.wikipedia.org/wiki/Heron%27s_formula
  10248. triangleArea: function ( vectorA, vectorB, vectorC ) {
  10249. var s, a, b, c,
  10250. tmp = THREE.GeometryUtils.__v1;
  10251. tmp.sub( vectorA, vectorB );
  10252. a = tmp.length();
  10253. tmp.sub( vectorA, vectorC );
  10254. b = tmp.length();
  10255. tmp.sub( vectorB, vectorC );
  10256. c = tmp.length();
  10257. s = 0.5 * ( a + b + c );
  10258. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  10259. },
  10260. // Center geometry so that 0,0,0 is in center of bounding box
  10261. center: function ( geometry ) {
  10262. geometry.computeBoundingBox();
  10263. var bb = geometry.boundingBox;
  10264. var offset = new THREE.Vector3();
  10265. offset.add( bb.min, bb.max );
  10266. offset.multiplyScalar( -0.5 );
  10267. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  10268. geometry.computeBoundingBox();
  10269. return offset;
  10270. },
  10271. // Normalize UVs to be from <0,1>
  10272. // (for now just the first set of UVs)
  10273. normalizeUVs: function ( geometry ) {
  10274. var uvSet = geometry.faceVertexUvs[ 0 ];
  10275. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  10276. var uvs = uvSet[ i ];
  10277. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  10278. // texture repeat
  10279. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  10280. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  10281. }
  10282. }
  10283. },
  10284. triangulateQuads: function ( geometry ) {
  10285. var i, il, j, jl;
  10286. var faces = [];
  10287. var faceUvs = [];
  10288. var faceVertexUvs = [];
  10289. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  10290. faceUvs[ i ] = [];
  10291. }
  10292. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  10293. faceVertexUvs[ i ] = [];
  10294. }
  10295. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10296. var face = geometry.faces[ i ];
  10297. if ( face instanceof THREE.Face4 ) {
  10298. var a = face.a;
  10299. var b = face.b;
  10300. var c = face.c;
  10301. var d = face.d;
  10302. var triA = new THREE.Face3();
  10303. var triB = new THREE.Face3();
  10304. triA.color.copy( face.color );
  10305. triB.color.copy( face.color );
  10306. triA.materialIndex = face.materialIndex;
  10307. triB.materialIndex = face.materialIndex;
  10308. triA.a = a;
  10309. triA.b = b;
  10310. triA.c = d;
  10311. triB.a = b;
  10312. triB.b = c;
  10313. triB.c = d;
  10314. if ( face.vertexColors.length === 4 ) {
  10315. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  10316. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  10317. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  10318. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  10319. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  10320. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  10321. }
  10322. faces.push( triA, triB );
  10323. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10324. if ( geometry.faceVertexUvs[ j ].length ) {
  10325. var uvs = geometry.faceVertexUvs[ j ][ i ];
  10326. var uvA = uvs[ 0 ];
  10327. var uvB = uvs[ 1 ];
  10328. var uvC = uvs[ 2 ];
  10329. var uvD = uvs[ 3 ];
  10330. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  10331. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  10332. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  10333. }
  10334. }
  10335. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  10336. if ( geometry.faceUvs[ j ].length ) {
  10337. var faceUv = geometry.faceUvs[ j ][ i ];
  10338. faceUvs[ j ].push( faceUv, faceUv );
  10339. }
  10340. }
  10341. } else {
  10342. faces.push( face );
  10343. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  10344. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  10345. }
  10346. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10347. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10348. }
  10349. }
  10350. }
  10351. geometry.faces = faces;
  10352. geometry.faceUvs = faceUvs;
  10353. geometry.faceVertexUvs = faceVertexUvs;
  10354. geometry.computeCentroids();
  10355. geometry.computeFaceNormals();
  10356. geometry.computeVertexNormals();
  10357. if ( geometry.hasTangents ) geometry.computeTangents();
  10358. },
  10359. // Make all faces use unique vertices
  10360. // so that each face can be separated from others
  10361. explode: function( geometry ) {
  10362. var vertices = [];
  10363. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10364. var n = vertices.length;
  10365. var face = geometry.faces[ i ];
  10366. if ( face instanceof THREE.Face4 ) {
  10367. var a = face.a;
  10368. var b = face.b;
  10369. var c = face.c;
  10370. var d = face.d;
  10371. var va = geometry.vertices[ a ];
  10372. var vb = geometry.vertices[ b ];
  10373. var vc = geometry.vertices[ c ];
  10374. var vd = geometry.vertices[ d ];
  10375. vertices.push( va.clone() );
  10376. vertices.push( vb.clone() );
  10377. vertices.push( vc.clone() );
  10378. vertices.push( vd.clone() );
  10379. face.a = n;
  10380. face.b = n + 1;
  10381. face.c = n + 2;
  10382. face.d = n + 3;
  10383. } else {
  10384. var a = face.a;
  10385. var b = face.b;
  10386. var c = face.c;
  10387. var va = geometry.vertices[ a ];
  10388. var vb = geometry.vertices[ b ];
  10389. var vc = geometry.vertices[ c ];
  10390. vertices.push( va.clone() );
  10391. vertices.push( vb.clone() );
  10392. vertices.push( vc.clone() );
  10393. face.a = n;
  10394. face.b = n + 1;
  10395. face.c = n + 2;
  10396. }
  10397. }
  10398. geometry.vertices = vertices;
  10399. delete geometry.__tmpVertices;
  10400. },
  10401. // Break faces with edges longer than maxEdgeLength
  10402. // - not recursive
  10403. tessellate: function ( geometry, maxEdgeLength ) {
  10404. var i, il, face,
  10405. a, b, c, d,
  10406. va, vb, vc, vd,
  10407. dab, dbc, dac, dcd, dad,
  10408. m, m1, m2,
  10409. vm, vm1, vm2,
  10410. vnm, vnm1, vnm2,
  10411. vcm, vcm1, vcm2,
  10412. triA, triB,
  10413. quadA, quadB,
  10414. edge;
  10415. var faces = [];
  10416. var faceVertexUvs = [];
  10417. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  10418. faceVertexUvs[ i ] = [];
  10419. }
  10420. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  10421. face = geometry.faces[ i ];
  10422. if ( face instanceof THREE.Face3 ) {
  10423. a = face.a;
  10424. b = face.b;
  10425. c = face.c;
  10426. va = geometry.vertices[ a ];
  10427. vb = geometry.vertices[ b ];
  10428. vc = geometry.vertices[ c ];
  10429. dab = va.position.distanceTo( vb.position );
  10430. dbc = vb.position.distanceTo( vc.position );
  10431. dac = va.position.distanceTo( vc.position );
  10432. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  10433. m = geometry.vertices.length;
  10434. triA = face.clone();
  10435. triB = face.clone();
  10436. if ( dab >= dbc && dab >= dac ) {
  10437. vm = va.clone();
  10438. vm.position.lerpSelf( vb.position, 0.5 );
  10439. triA.a = a;
  10440. triA.b = m;
  10441. triA.c = c;
  10442. triB.a = m;
  10443. triB.b = b;
  10444. triB.c = c;
  10445. if ( face.vertexNormals.length === 3 ) {
  10446. vnm = face.vertexNormals[ 0 ].clone();
  10447. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  10448. triA.vertexNormals[ 1 ].copy( vnm );
  10449. triB.vertexNormals[ 0 ].copy( vnm );
  10450. }
  10451. if ( face.vertexColors.length === 3 ) {
  10452. vcm = face.vertexColors[ 0 ].clone();
  10453. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  10454. triA.vertexColors[ 1 ].copy( vcm );
  10455. triB.vertexColors[ 0 ].copy( vcm );
  10456. }
  10457. edge = 0;
  10458. } else if ( dbc >= dab && dbc >= dac ) {
  10459. vm = vb.clone();
  10460. vm.position.lerpSelf( vc.position, 0.5 );
  10461. triA.a = a;
  10462. triA.b = b;
  10463. triA.c = m;
  10464. triB.a = m;
  10465. triB.b = c;
  10466. triB.c = a;
  10467. if ( face.vertexNormals.length === 3 ) {
  10468. vnm = face.vertexNormals[ 1 ].clone();
  10469. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10470. triA.vertexNormals[ 2 ].copy( vnm );
  10471. triB.vertexNormals[ 0 ].copy( vnm );
  10472. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  10473. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  10474. }
  10475. if ( face.vertexColors.length === 3 ) {
  10476. vcm = face.vertexColors[ 1 ].clone();
  10477. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10478. triA.vertexColors[ 2 ].copy( vcm );
  10479. triB.vertexColors[ 0 ].copy( vcm );
  10480. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  10481. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  10482. }
  10483. edge = 1;
  10484. } else {
  10485. vm = va.clone();
  10486. vm.position.lerpSelf( vc.position, 0.5 );
  10487. triA.a = a;
  10488. triA.b = b;
  10489. triA.c = m;
  10490. triB.a = m;
  10491. triB.b = b;
  10492. triB.c = c;
  10493. if ( face.vertexNormals.length === 3 ) {
  10494. vnm = face.vertexNormals[ 0 ].clone();
  10495. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10496. triA.vertexNormals[ 2 ].copy( vnm );
  10497. triB.vertexNormals[ 0 ].copy( vnm );
  10498. }
  10499. if ( face.vertexColors.length === 3 ) {
  10500. vcm = face.vertexColors[ 0 ].clone();
  10501. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10502. triA.vertexColors[ 2 ].copy( vcm );
  10503. triB.vertexColors[ 0 ].copy( vcm );
  10504. }
  10505. edge = 2;
  10506. }
  10507. faces.push( triA, triB );
  10508. geometry.vertices.push( vm );
  10509. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  10510. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10511. if ( geometry.faceVertexUvs[ j ].length ) {
  10512. uvs = geometry.faceVertexUvs[ j ][ i ];
  10513. uvA = uvs[ 0 ];
  10514. uvB = uvs[ 1 ];
  10515. uvC = uvs[ 2 ];
  10516. // AB
  10517. if ( edge === 0 ) {
  10518. uvM = uvA.clone();
  10519. uvM.lerpSelf( uvB, 0.5 );
  10520. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  10521. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  10522. // BC
  10523. } else if ( edge === 1 ) {
  10524. uvM = uvB.clone();
  10525. uvM.lerpSelf( uvC, 0.5 );
  10526. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  10527. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  10528. // AC
  10529. } else {
  10530. uvM = uvA.clone();
  10531. uvM.lerpSelf( uvC, 0.5 );
  10532. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  10533. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  10534. }
  10535. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  10536. }
  10537. }
  10538. } else {
  10539. faces.push( face );
  10540. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10541. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10542. }
  10543. }
  10544. } else {
  10545. a = face.a;
  10546. b = face.b;
  10547. c = face.c;
  10548. d = face.d;
  10549. va = geometry.vertices[ a ];
  10550. vb = geometry.vertices[ b ];
  10551. vc = geometry.vertices[ c ];
  10552. vd = geometry.vertices[ d ];
  10553. dab = va.position.distanceTo( vb.position );
  10554. dbc = vb.position.distanceTo( vc.position );
  10555. dcd = vc.position.distanceTo( vd.position );
  10556. dad = va.position.distanceTo( vd.position );
  10557. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  10558. m1 = geometry.vertices.length;
  10559. m2 = geometry.vertices.length + 1;
  10560. quadA = face.clone();
  10561. quadB = face.clone();
  10562. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  10563. vm1 = va.clone();
  10564. vm1.position.lerpSelf( vb.position, 0.5 );
  10565. vm2 = vc.clone();
  10566. vm2.position.lerpSelf( vd.position, 0.5 );
  10567. quadA.a = a;
  10568. quadA.b = m1;
  10569. quadA.c = m2;
  10570. quadA.d = d;
  10571. quadB.a = m1;
  10572. quadB.b = b;
  10573. quadB.c = c;
  10574. quadB.d = m2;
  10575. if ( face.vertexNormals.length === 4 ) {
  10576. vnm1 = face.vertexNormals[ 0 ].clone();
  10577. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  10578. vnm2 = face.vertexNormals[ 2 ].clone();
  10579. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  10580. quadA.vertexNormals[ 1 ].copy( vnm1 );
  10581. quadA.vertexNormals[ 2 ].copy( vnm2 );
  10582. quadB.vertexNormals[ 0 ].copy( vnm1 );
  10583. quadB.vertexNormals[ 3 ].copy( vnm2 );
  10584. }
  10585. if ( face.vertexColors.length === 4 ) {
  10586. vcm1 = face.vertexColors[ 0 ].clone();
  10587. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  10588. vcm2 = face.vertexColors[ 2 ].clone();
  10589. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  10590. quadA.vertexColors[ 1 ].copy( vcm1 );
  10591. quadA.vertexColors[ 2 ].copy( vcm2 );
  10592. quadB.vertexColors[ 0 ].copy( vcm1 );
  10593. quadB.vertexColors[ 3 ].copy( vcm2 );
  10594. }
  10595. edge = 0;
  10596. } else {
  10597. vm1 = vb.clone();
  10598. vm1.position.lerpSelf( vc.position, 0.5 );
  10599. vm2 = vd.clone();
  10600. vm2.position.lerpSelf( va.position, 0.5 );
  10601. quadA.a = a;
  10602. quadA.b = b;
  10603. quadA.c = m1;
  10604. quadA.d = m2;
  10605. quadB.a = m2;
  10606. quadB.b = m1;
  10607. quadB.c = c;
  10608. quadB.d = d;
  10609. if ( face.vertexNormals.length === 4 ) {
  10610. vnm1 = face.vertexNormals[ 1 ].clone();
  10611. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  10612. vnm2 = face.vertexNormals[ 3 ].clone();
  10613. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  10614. quadA.vertexNormals[ 2 ].copy( vnm1 );
  10615. quadA.vertexNormals[ 3 ].copy( vnm2 );
  10616. quadB.vertexNormals[ 0 ].copy( vnm2 );
  10617. quadB.vertexNormals[ 1 ].copy( vnm1 );
  10618. }
  10619. if ( face.vertexColors.length === 4 ) {
  10620. vcm1 = face.vertexColors[ 1 ].clone();
  10621. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  10622. vcm2 = face.vertexColors[ 3 ].clone();
  10623. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  10624. quadA.vertexColors[ 2 ].copy( vcm1 );
  10625. quadA.vertexColors[ 3 ].copy( vcm2 );
  10626. quadB.vertexColors[ 0 ].copy( vcm2 );
  10627. quadB.vertexColors[ 1 ].copy( vcm1 );
  10628. }
  10629. edge = 1;
  10630. }
  10631. faces.push( quadA, quadB );
  10632. geometry.vertices.push( vm1, vm2 );
  10633. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  10634. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10635. if ( geometry.faceVertexUvs[ j ].length ) {
  10636. uvs = geometry.faceVertexUvs[ j ][ i ];
  10637. uvA = uvs[ 0 ];
  10638. uvB = uvs[ 1 ];
  10639. uvC = uvs[ 2 ];
  10640. uvD = uvs[ 3 ];
  10641. // AB + CD
  10642. if ( edge === 0 ) {
  10643. uvM1 = uvA.clone();
  10644. uvM1.lerpSelf( uvB, 0.5 );
  10645. uvM2 = uvC.clone();
  10646. uvM2.lerpSelf( uvD, 0.5 );
  10647. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  10648. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  10649. // BC + AD
  10650. } else {
  10651. uvM1 = uvB.clone();
  10652. uvM1.lerpSelf( uvC, 0.5 );
  10653. uvM2 = uvD.clone();
  10654. uvM2.lerpSelf( uvA, 0.5 );
  10655. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  10656. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  10657. }
  10658. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  10659. }
  10660. }
  10661. } else {
  10662. faces.push( face );
  10663. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  10664. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  10665. }
  10666. }
  10667. }
  10668. }
  10669. geometry.faces = faces;
  10670. geometry.faceVertexUvs = faceVertexUvs;
  10671. }
  10672. };
  10673. THREE.GeometryUtils.random = THREE.Math.random16;
  10674. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  10675. /**
  10676. * @author alteredq / http://alteredqualia.com/
  10677. * @author mrdoob / http://mrdoob.com/
  10678. */
  10679. THREE.ImageUtils = {
  10680. crossOrigin: 'anonymous',
  10681. loadTexture: function ( path, mapping, callback ) {
  10682. var image = new Image(), texture = new THREE.Texture( image, mapping );
  10683. image.onload = function () { texture.needsUpdate = true; if ( callback ) callback( this ); };
  10684. image.crossOrigin = this.crossOrigin;
  10685. image.src = path;
  10686. return texture;
  10687. },
  10688. loadTextureCube: function ( array, mapping, callback ) {
  10689. var i, l, images = [], texture = new THREE.Texture( images, mapping );
  10690. images.loadCount = 0;
  10691. for ( i = 0, l = array.length; i < l; ++ i ) {
  10692. images[ i ] = new Image();
  10693. images[ i ].onload = function () {
  10694. images.loadCount += 1;
  10695. if ( images.loadCount === 6 ) texture.needsUpdate = true;
  10696. if ( callback ) callback( this );
  10697. };
  10698. images[ i ].crossOrigin = this.crossOrigin;
  10699. images[ i ].src = array[ i ];
  10700. }
  10701. return texture;
  10702. },
  10703. getNormalMap: function ( image, depth ) {
  10704. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  10705. var cross = function ( a, b ) {
  10706. 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 ] ];
  10707. }
  10708. var subtract = function ( a, b ) {
  10709. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  10710. }
  10711. var normalize = function ( a ) {
  10712. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  10713. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  10714. }
  10715. depth = depth | 1;
  10716. var width = image.width;
  10717. var height = image.height;
  10718. var canvas = document.createElement( 'canvas' );
  10719. canvas.width = width;
  10720. canvas.height = height;
  10721. var context = canvas.getContext( '2d' );
  10722. context.drawImage( image, 0, 0 );
  10723. var data = context.getImageData( 0, 0, width, height ).data;
  10724. var imageData = context.createImageData( width, height );
  10725. var output = imageData.data;
  10726. for ( var x = 0; x < width; x ++ ) {
  10727. for ( var y = 1; y < height; y ++ ) {
  10728. var ly = y - 1 < 0 ? height - 1 : y - 1;
  10729. var uy = ( y + 1 ) % height;
  10730. var lx = x - 1 < 0 ? width - 1 : x - 1;
  10731. var ux = ( x + 1 ) % width;
  10732. var points = [];
  10733. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  10734. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  10735. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  10736. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  10737. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  10738. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  10739. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  10740. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  10741. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  10742. var normals = [];
  10743. var num_points = points.length;
  10744. for ( var i = 0; i < num_points; i ++ ) {
  10745. var v1 = points[ i ];
  10746. var v2 = points[ ( i + 1 ) % num_points ];
  10747. v1 = subtract( v1, origin );
  10748. v2 = subtract( v2, origin );
  10749. normals.push( normalize( cross( v1, v2 ) ) );
  10750. }
  10751. var normal = [ 0, 0, 0 ];
  10752. for ( var i = 0; i < normals.length; i ++ ) {
  10753. normal[ 0 ] += normals[ i ][ 0 ];
  10754. normal[ 1 ] += normals[ i ][ 1 ];
  10755. normal[ 2 ] += normals[ i ][ 2 ];
  10756. }
  10757. normal[ 0 ] /= normals.length;
  10758. normal[ 1 ] /= normals.length;
  10759. normal[ 2 ] /= normals.length;
  10760. var idx = ( y * width + x ) * 4;
  10761. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  10762. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 / 2.0 ) * 255 ) | 0;
  10763. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  10764. output[ idx + 3 ] = 255;
  10765. }
  10766. }
  10767. context.putImageData( imageData, 0, 0 );
  10768. return canvas;
  10769. },
  10770. generateDataTexture: function ( width, height, color ) {
  10771. var size = width * height;
  10772. var data = new Uint8Array( 3 * size );
  10773. var r = Math.floor( color.r * 255 );
  10774. var g = Math.floor( color.g * 255 );
  10775. var b = Math.floor( color.b * 255 );
  10776. for ( var i = 0; i < size; i ++ ) {
  10777. data[ i * 3 ] = r;
  10778. data[ i * 3 + 1 ] = g;
  10779. data[ i * 3 + 2 ] = b;
  10780. }
  10781. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  10782. texture.needsUpdate = true;
  10783. return texture;
  10784. }
  10785. };
  10786. /**
  10787. * @author alteredq / http://alteredqualia.com/
  10788. */
  10789. THREE.SceneUtils = {
  10790. showHierarchy : function ( root, visible ) {
  10791. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  10792. },
  10793. traverseHierarchy : function ( root, callback ) {
  10794. var n, i, l = root.children.length;
  10795. for ( i = 0; i < l; i ++ ) {
  10796. n = root.children[ i ];
  10797. callback( n );
  10798. THREE.SceneUtils.traverseHierarchy( n, callback );
  10799. }
  10800. },
  10801. createMultiMaterialObject : function ( geometry, materials ) {
  10802. var i, il = materials.length,
  10803. group = new THREE.Object3D();
  10804. for ( i = 0; i < il; i ++ ) {
  10805. var object = new THREE.Mesh( geometry, materials[ i ] );
  10806. group.add( object );
  10807. }
  10808. return group;
  10809. },
  10810. cloneObject: function ( source ) {
  10811. var object;
  10812. // subclass specific properties
  10813. // (must process in order from more specific subclasses to more abstract classes)
  10814. if ( source instanceof THREE.MorphAnimMesh ) {
  10815. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  10816. object.duration = source.duration;
  10817. object.mirroredLoop = source.mirroredLoop;
  10818. object.time = source.time;
  10819. object.lastKeyframe = source.lastKeyframe;
  10820. object.currentKeyframe = source.currentKeyframe;
  10821. object.direction = source.direction;
  10822. object.directionBackwards = source.directionBackwards;
  10823. } else if ( source instanceof THREE.SkinnedMesh ) {
  10824. object = new THREE.SkinnedMesh( source.geometry, source.material );
  10825. } else if ( source instanceof THREE.Mesh ) {
  10826. object = new THREE.Mesh( source.geometry, source.material );
  10827. } else if ( source instanceof THREE.Line ) {
  10828. object = new THREE.Line( source.geometry, source.material, source.type );
  10829. } else if ( source instanceof THREE.Ribbon ) {
  10830. object = new THREE.Ribbon( source.geometry, source.material );
  10831. } else if ( source instanceof THREE.ParticleSystem ) {
  10832. object = new THREE.ParticleSystem( source.geometry, source.material );
  10833. object.sortParticles = source.sortParticles;
  10834. } else if ( source instanceof THREE.Particle ) {
  10835. object = new THREE.Particle( source.material );
  10836. } else if ( source instanceof THREE.Sprite ) {
  10837. object = new THREE.Sprite( {} );
  10838. object.color.copy( source.color );
  10839. object.map = source.map;
  10840. object.blending = source.blending;
  10841. object.useScreenCoordinates = source.useScreenCoordinates;
  10842. object.mergeWith3D = source.mergeWith3D;
  10843. object.affectedByDistance = source.affectedByDistance;
  10844. object.scaleByViewport = source.scaleByViewport;
  10845. object.alignment = source.alignment;
  10846. object.rotation3d.copy( source.rotation3d );
  10847. object.rotation = source.rotation;
  10848. object.opacity = source.opacity;
  10849. object.uvOffset.copy( source.uvOffset );
  10850. object.uvScale.copy( source.uvScale);
  10851. } else if ( source instanceof THREE.LOD ) {
  10852. object = new THREE.LOD();
  10853. } else if ( source instanceof THREE.MarchingCubes ) {
  10854. object = new THREE.MarchingCubes( source.resolution, source.material );
  10855. object.field.set( source.field );
  10856. object.isolation = source.isolation;
  10857. } else if ( source instanceof THREE.Object3D ) {
  10858. object = new THREE.Object3D();
  10859. }
  10860. // base class properties
  10861. object.name = source.name;
  10862. object.parent = source.parent;
  10863. object.up.copy( source.up );
  10864. object.position.copy( source.position );
  10865. // because of Sprite madness
  10866. if ( object.rotation instanceof THREE.Vector3 )
  10867. object.rotation.copy( source.rotation );
  10868. object.eulerOrder = source.eulerOrder;
  10869. object.scale.copy( source.scale );
  10870. object.dynamic = source.dynamic;
  10871. object.doubleSided = source.doubleSided;
  10872. object.flipSided = source.flipSided;
  10873. object.renderDepth = source.renderDepth;
  10874. object.rotationAutoUpdate = source.rotationAutoUpdate;
  10875. object.matrix.copy( source.matrix );
  10876. object.matrixWorld.copy( source.matrixWorld );
  10877. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  10878. object.matrixAutoUpdate = source.matrixAutoUpdate;
  10879. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  10880. object.quaternion.copy( source.quaternion );
  10881. object.useQuaternion = source.useQuaternion;
  10882. object.boundRadius = source.boundRadius;
  10883. object.boundRadiusScale = source.boundRadiusScale;
  10884. object.visible = source.visible;
  10885. object.castShadow = source.castShadow;
  10886. object.receiveShadow = source.receiveShadow;
  10887. object.frustumCulled = source.frustumCulled;
  10888. // children
  10889. for ( var i = 0; i < source.children.length; i ++ ) {
  10890. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  10891. object.children[ i ] = child;
  10892. child.parent = object;
  10893. }
  10894. // LODs need to be patched separately to use cloned children
  10895. if ( source instanceof THREE.LOD ) {
  10896. for ( var i = 0; i < source.LODs.length; i ++ ) {
  10897. var lod = source.LODs[ i ];
  10898. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  10899. }
  10900. }
  10901. return object;
  10902. },
  10903. detach : function ( child, parent, scene ) {
  10904. child.applyMatrix( parent.matrixWorld );
  10905. parent.remove( child );
  10906. scene.add( child );
  10907. },
  10908. attach: function ( child, scene, parent ) {
  10909. var matrixWorldInverse = new THREE.Matrix4();
  10910. matrixWorldInverse.getInverse( parent.matrixWorld );
  10911. child.applyMatrix( matrixWorldInverse );
  10912. scene.remove( child );
  10913. parent.add( child );
  10914. }
  10915. };
  10916. /**
  10917. * @author alteredq / http://alteredqualia.com/
  10918. * @author mr.doob / http://mrdoob.com/
  10919. *
  10920. * ShaderUtils currently contains:
  10921. *
  10922. * fresnel
  10923. * normal
  10924. * cube
  10925. *
  10926. */
  10927. if ( THREE.WebGLRenderer ) {
  10928. THREE.ShaderUtils = {
  10929. lib: {
  10930. /* -------------------------------------------------------------------------
  10931. // Fresnel shader
  10932. // - based on Nvidia Cg tutorial
  10933. ------------------------------------------------------------------------- */
  10934. 'fresnel': {
  10935. uniforms: {
  10936. "mRefractionRatio": { type: "f", value: 1.02 },
  10937. "mFresnelBias": { type: "f", value: 0.1 },
  10938. "mFresnelPower": { type: "f", value: 2.0 },
  10939. "mFresnelScale": { type: "f", value: 1.0 },
  10940. "tCube": { type: "t", value: 1, texture: null }
  10941. },
  10942. fragmentShader: [
  10943. "uniform samplerCube tCube;",
  10944. "varying vec3 vReflect;",
  10945. "varying vec3 vRefract[3];",
  10946. "varying float vReflectionFactor;",
  10947. "void main() {",
  10948. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  10949. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  10950. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  10951. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  10952. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  10953. "refractedColor.a = 1.0;",
  10954. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  10955. "}"
  10956. ].join("\n"),
  10957. vertexShader: [
  10958. "uniform float mRefractionRatio;",
  10959. "uniform float mFresnelBias;",
  10960. "uniform float mFresnelScale;",
  10961. "uniform float mFresnelPower;",
  10962. "varying vec3 vReflect;",
  10963. "varying vec3 vRefract[3];",
  10964. "varying float vReflectionFactor;",
  10965. "void main() {",
  10966. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  10967. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  10968. "vec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );",
  10969. "vec3 I = mPosition.xyz - cameraPosition;",
  10970. "vReflect = reflect( I, nWorld );",
  10971. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  10972. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  10973. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  10974. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  10975. "gl_Position = projectionMatrix * mvPosition;",
  10976. "}"
  10977. ].join("\n")
  10978. },
  10979. /* -------------------------------------------------------------------------
  10980. // Normal map shader
  10981. // - Blinn-Phong
  10982. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  10983. // - point and directional lights (use with "lights: true" material option)
  10984. ------------------------------------------------------------------------- */
  10985. 'normal' : {
  10986. uniforms: THREE.UniformsUtils.merge( [
  10987. THREE.UniformsLib[ "fog" ],
  10988. THREE.UniformsLib[ "lights" ],
  10989. THREE.UniformsLib[ "shadowmap" ],
  10990. {
  10991. "enableAO" : { type: "i", value: 0 },
  10992. "enableDiffuse" : { type: "i", value: 0 },
  10993. "enableSpecular" : { type: "i", value: 0 },
  10994. "enableReflection": { type: "i", value: 0 },
  10995. "tDiffuse" : { type: "t", value: 0, texture: null },
  10996. "tCube" : { type: "t", value: 1, texture: null },
  10997. "tNormal" : { type: "t", value: 2, texture: null },
  10998. "tSpecular" : { type: "t", value: 3, texture: null },
  10999. "tAO" : { type: "t", value: 4, texture: null },
  11000. "tDisplacement": { type: "t", value: 5, texture: null },
  11001. "uNormalScale": { type: "f", value: 1.0 },
  11002. "uDisplacementBias": { type: "f", value: 0.0 },
  11003. "uDisplacementScale": { type: "f", value: 1.0 },
  11004. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11005. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  11006. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  11007. "uShininess": { type: "f", value: 30 },
  11008. "uOpacity": { type: "f", value: 1 },
  11009. "uReflectivity": { type: "f", value: 0.5 },
  11010. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  11011. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  11012. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  11013. }
  11014. ] ),
  11015. fragmentShader: [
  11016. "uniform vec3 uAmbientColor;",
  11017. "uniform vec3 uDiffuseColor;",
  11018. "uniform vec3 uSpecularColor;",
  11019. "uniform float uShininess;",
  11020. "uniform float uOpacity;",
  11021. "uniform bool enableDiffuse;",
  11022. "uniform bool enableSpecular;",
  11023. "uniform bool enableAO;",
  11024. "uniform bool enableReflection;",
  11025. "uniform sampler2D tDiffuse;",
  11026. "uniform sampler2D tNormal;",
  11027. "uniform sampler2D tSpecular;",
  11028. "uniform sampler2D tAO;",
  11029. "uniform samplerCube tCube;",
  11030. "uniform float uNormalScale;",
  11031. "uniform float uReflectivity;",
  11032. "varying vec3 vTangent;",
  11033. "varying vec3 vBinormal;",
  11034. "varying vec3 vNormal;",
  11035. "varying vec2 vUv;",
  11036. "uniform vec3 ambientLightColor;",
  11037. "#if MAX_DIR_LIGHTS > 0",
  11038. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  11039. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  11040. "#endif",
  11041. "#if MAX_POINT_LIGHTS > 0",
  11042. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  11043. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  11044. "#endif",
  11045. "#ifdef WRAP_AROUND",
  11046. "uniform vec3 wrapRGB;",
  11047. "#endif",
  11048. "varying vec3 vViewPosition;",
  11049. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  11050. THREE.ShaderChunk[ "fog_pars_fragment" ],
  11051. "void main() {",
  11052. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  11053. "vec3 specularTex = vec3( 1.0 );",
  11054. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  11055. "normalTex.xy *= uNormalScale;",
  11056. "normalTex = normalize( normalTex );",
  11057. "if( enableDiffuse ) {",
  11058. "#ifdef GAMMA_INPUT",
  11059. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  11060. "texelColor.xyz *= texelColor.xyz;",
  11061. "gl_FragColor = gl_FragColor * texelColor;",
  11062. "#else",
  11063. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  11064. "#endif",
  11065. "}",
  11066. "if( enableAO ) {",
  11067. "#ifdef GAMMA_INPUT",
  11068. "vec4 aoColor = texture2D( tAO, vUv );",
  11069. "aoColor.xyz *= aoColor.xyz;",
  11070. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  11071. "#else",
  11072. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  11073. "#endif",
  11074. "}",
  11075. "if( enableSpecular )",
  11076. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  11077. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  11078. "vec3 finalNormal = tsb * normalTex;",
  11079. "vec3 normal = normalize( finalNormal );",
  11080. "vec3 viewPosition = normalize( vViewPosition );",
  11081. // point lights
  11082. "#if MAX_POINT_LIGHTS > 0",
  11083. "vec3 pointDiffuse = vec3( 0.0 );",
  11084. "vec3 pointSpecular = vec3( 0.0 );",
  11085. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  11086. "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
  11087. "float pointDistance = vPointLight[ i ].w;",
  11088. // diffuse
  11089. "#ifdef WRAP_AROUND",
  11090. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  11091. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  11092. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  11093. "#else",
  11094. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  11095. "#endif",
  11096. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  11097. // specular
  11098. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  11099. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  11100. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  11101. "#ifdef PHYSICALLY_BASED_SHADING",
  11102. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11103. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11104. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  11105. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  11106. "#else",
  11107. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  11108. "#endif",
  11109. "}",
  11110. "#endif",
  11111. // directional lights
  11112. "#if MAX_DIR_LIGHTS > 0",
  11113. "vec3 dirDiffuse = vec3( 0.0 );",
  11114. "vec3 dirSpecular = vec3( 0.0 );",
  11115. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  11116. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  11117. "vec3 dirVector = normalize( lDirection.xyz );",
  11118. // diffuse
  11119. "#ifdef WRAP_AROUND",
  11120. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  11121. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  11122. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  11123. "#else",
  11124. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  11125. "#endif",
  11126. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  11127. // specular
  11128. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  11129. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  11130. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  11131. "#ifdef PHYSICALLY_BASED_SHADING",
  11132. // 2.0 => 2.0001 is hack to work around ANGLE bug
  11133. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  11134. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  11135. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  11136. "#else",
  11137. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  11138. "#endif",
  11139. "}",
  11140. "#endif",
  11141. // all lights contribution summation
  11142. "vec3 totalDiffuse = vec3( 0.0 );",
  11143. "vec3 totalSpecular = vec3( 0.0 );",
  11144. "#if MAX_DIR_LIGHTS > 0",
  11145. "totalDiffuse += dirDiffuse;",
  11146. "totalSpecular += dirSpecular;",
  11147. "#endif",
  11148. "#if MAX_POINT_LIGHTS > 0",
  11149. "totalDiffuse += pointDiffuse;",
  11150. "totalSpecular += pointSpecular;",
  11151. "#endif",
  11152. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor) + totalSpecular;",
  11153. "if ( enableReflection ) {",
  11154. "vec3 wPos = cameraPosition - vViewPosition;",
  11155. "vec3 vReflect = reflect( normalize( wPos ), normal );",
  11156. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  11157. "#ifdef GAMMA_INPUT",
  11158. "cubeColor.xyz *= cubeColor.xyz;",
  11159. "#endif",
  11160. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  11161. "}",
  11162. THREE.ShaderChunk[ "shadowmap_fragment" ],
  11163. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  11164. THREE.ShaderChunk[ "fog_fragment" ],
  11165. "}"
  11166. ].join("\n"),
  11167. vertexShader: [
  11168. "attribute vec4 tangent;",
  11169. "uniform vec2 uOffset;",
  11170. "uniform vec2 uRepeat;",
  11171. "#ifdef VERTEX_TEXTURES",
  11172. "uniform sampler2D tDisplacement;",
  11173. "uniform float uDisplacementScale;",
  11174. "uniform float uDisplacementBias;",
  11175. "#endif",
  11176. "varying vec3 vTangent;",
  11177. "varying vec3 vBinormal;",
  11178. "varying vec3 vNormal;",
  11179. "varying vec2 vUv;",
  11180. "#if MAX_POINT_LIGHTS > 0",
  11181. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  11182. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  11183. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  11184. "#endif",
  11185. "varying vec3 vViewPosition;",
  11186. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  11187. "void main() {",
  11188. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  11189. "vViewPosition = -mvPosition.xyz;",
  11190. // normal, tangent and binormal vectors
  11191. "vNormal = normalMatrix * normal;",
  11192. "vTangent = normalMatrix * tangent.xyz;",
  11193. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  11194. "vUv = uv * uRepeat + uOffset;",
  11195. // point lights
  11196. "#if MAX_POINT_LIGHTS > 0",
  11197. "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",
  11198. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  11199. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  11200. "float lDistance = 1.0;",
  11201. "if ( pointLightDistance[ i ] > 0.0 )",
  11202. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  11203. "lVector = normalize( lVector );",
  11204. "vPointLight[ i ] = vec4( lVector, lDistance );",
  11205. "}",
  11206. "#endif",
  11207. // displacement mapping
  11208. "#ifdef VERTEX_TEXTURES",
  11209. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  11210. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  11211. "vec4 displacedPosition = vec4( normalize( vNormal.xyz ) * df, 0.0 ) + mvPosition;",
  11212. "gl_Position = projectionMatrix * displacedPosition;",
  11213. "#else",
  11214. "gl_Position = projectionMatrix * mvPosition;",
  11215. "#endif",
  11216. THREE.ShaderChunk[ "shadowmap_vertex" ],
  11217. "}"
  11218. ].join("\n")
  11219. },
  11220. /* -------------------------------------------------------------------------
  11221. // Cube map shader
  11222. ------------------------------------------------------------------------- */
  11223. 'cube': {
  11224. uniforms: { "tCube": { type: "t", value: 1, texture: null },
  11225. "tFlip": { type: "f", value: -1 } },
  11226. vertexShader: [
  11227. "varying vec3 vViewPosition;",
  11228. "void main() {",
  11229. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  11230. "vViewPosition = cameraPosition - mPosition.xyz;",
  11231. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11232. "}"
  11233. ].join("\n"),
  11234. fragmentShader: [
  11235. "uniform samplerCube tCube;",
  11236. "uniform float tFlip;",
  11237. "varying vec3 vViewPosition;",
  11238. "void main() {",
  11239. "vec3 wPos = cameraPosition - vViewPosition;",
  11240. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  11241. "}"
  11242. ].join("\n")
  11243. }
  11244. }
  11245. };
  11246. };/**
  11247. * @author alteredq / http://alteredqualia.com/
  11248. */
  11249. THREE.BufferGeometry = function () {
  11250. this.id = THREE.GeometryCount ++;
  11251. // GL buffers
  11252. this.vertexIndexBuffer = null;
  11253. this.vertexPositionBuffer = null;
  11254. this.vertexNormalBuffer = null;
  11255. this.vertexUvBuffer = null;
  11256. this.vertexColorBuffer = null;
  11257. // typed arrays (kept only if dynamic flag is set)
  11258. this.vertexIndexArray = null;
  11259. this.vertexPositionArray = null;
  11260. this.vertexNormalArray = null;
  11261. this.vertexUvArray = null;
  11262. this.vertexColorArray = null;
  11263. this.dynamic = false;
  11264. // boundings
  11265. this.boundingBox = null;
  11266. this.boundingSphere = null;
  11267. // for compatibility
  11268. this.morphTargets = [];
  11269. };
  11270. THREE.BufferGeometry.prototype = {
  11271. constructor : THREE.BufferGeometry,
  11272. // for compatibility
  11273. computeBoundingBox: function () {
  11274. },
  11275. // for compatibility
  11276. computeBoundingSphere: function () {
  11277. }
  11278. };
  11279. /**
  11280. * @author zz85 / http://www.lab4games.net/zz85/blog
  11281. * Extensible curve object
  11282. *
  11283. * Some common of Curve methods
  11284. * .getPoint(t), getTangent(t)
  11285. * .getPointAt(u), getTagentAt(u)
  11286. * .getPoints(), .getSpacedPoints()
  11287. * .getLength()
  11288. *
  11289. * This file contains following classes:
  11290. *
  11291. * -- 2d classes --
  11292. * THREE.Curve
  11293. * THREE.LineCurve
  11294. * THREE.QuadraticBezierCurve
  11295. * THREE.CubicBezierCurve
  11296. * THREE.SplineCurve
  11297. * THREE.ArcCurve
  11298. *
  11299. * -- 3d classes --
  11300. * THREE.LineCurve3
  11301. * THREE.QuadraticBezierCurve3
  11302. * THREE.CubicBezierCurve3
  11303. * THREE.SplineCurve3
  11304. * THREE.ClosedSplineCurve3
  11305. *
  11306. **/
  11307. /**************************************************************
  11308. * Abstract Curve base class
  11309. **************************************************************/
  11310. THREE.Curve = function () {
  11311. };
  11312. // Virtual base class method to overwrite and implement in subclasses
  11313. // - t [0 .. 1]
  11314. THREE.Curve.prototype.getPoint = function ( t ) {
  11315. console.log( "Warning, getPoint() not implemented!" );
  11316. return null;
  11317. };
  11318. // Get point at relative position in curve according to arc length
  11319. // - u [0 .. 1]
  11320. THREE.Curve.prototype.getPointAt = function ( u ) {
  11321. var t = this.getUtoTmapping( u );
  11322. return this.getPoint( t );
  11323. };
  11324. // Get sequence of points using getPoint( t )
  11325. THREE.Curve.prototype.getPoints = function ( divisions ) {
  11326. if ( !divisions ) divisions = 5;
  11327. var d, pts = [];
  11328. for ( d = 0; d <= divisions; d ++ ) {
  11329. pts.push( this.getPoint( d / divisions ) );
  11330. };
  11331. return pts;
  11332. };
  11333. // Get sequence of points using getPointAt( u )
  11334. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  11335. if ( !divisions ) divisions = 5;
  11336. var d, pts = [];
  11337. for ( d = 0; d <= divisions; d ++ ) {
  11338. pts.push( this.getPointAt( d / divisions ) );
  11339. };
  11340. return pts;
  11341. };
  11342. // Get total curve length
  11343. THREE.Curve.prototype.getLength = function () {
  11344. var lengths = this.getLengths();
  11345. return lengths[ lengths.length - 1 ];
  11346. };
  11347. // Get list of cumulative segment lengths
  11348. THREE.Curve.prototype.getLengths = function ( divisions ) {
  11349. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  11350. if ( this.cacheArcLengths
  11351. && ( this.cacheArcLengths.length == divisions + 1 )
  11352. && !this.needsUpdate) {
  11353. //console.log( "cached", this.cacheArcLengths );
  11354. return this.cacheArcLengths;
  11355. }
  11356. this.needsUpdate = false;
  11357. var cache = [];
  11358. var current, last = this.getPoint( 0 );
  11359. var p, sum = 0;
  11360. cache.push( 0 );
  11361. for ( p = 1; p <= divisions; p ++ ) {
  11362. current = this.getPoint ( p / divisions );
  11363. sum += current.distanceTo( last );
  11364. cache.push( sum );
  11365. last = current;
  11366. }
  11367. this.cacheArcLengths = cache;
  11368. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  11369. };
  11370. THREE.Curve.prototype.updateArcLengths = function() {
  11371. this.needsUpdate = true;
  11372. this.getLengths();
  11373. };
  11374. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  11375. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  11376. var arcLengths = this.getLengths();
  11377. var i = 0, il = arcLengths.length;
  11378. var targetArcLength; // The targeted u distance value to get
  11379. if ( distance ) {
  11380. targetArcLength = distance;
  11381. } else {
  11382. targetArcLength = u * arcLengths[ il - 1 ];
  11383. }
  11384. //var time = Date.now();
  11385. // binary search for the index with largest value smaller than target u distance
  11386. var low = 0, high = il - 1, comparison;
  11387. while ( low <= high ) {
  11388. 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
  11389. comparison = arcLengths[ i ] - targetArcLength;
  11390. if ( comparison < 0 ) {
  11391. low = i + 1;
  11392. continue;
  11393. } else if ( comparison > 0 ) {
  11394. high = i - 1;
  11395. continue;
  11396. } else {
  11397. high = i;
  11398. break;
  11399. // DONE
  11400. }
  11401. }
  11402. i = high;
  11403. //console.log('b' , i, low, high, Date.now()- time);
  11404. if ( arcLengths[ i ] == targetArcLength ) {
  11405. var t = i / ( il - 1 );
  11406. return t;
  11407. }
  11408. // we could get finer grain at lengths, or use simple interpolatation between two points
  11409. var lengthBefore = arcLengths[ i ];
  11410. var lengthAfter = arcLengths[ i + 1 ];
  11411. var segmentLength = lengthAfter - lengthBefore;
  11412. // determine where we are between the 'before' and 'after' points
  11413. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  11414. // add that fractional amount to t
  11415. t = ( i + segmentFraction ) / ( il -1 );
  11416. return t;
  11417. };
  11418. // In case any sub curve does not implement its tangent / normal finding,
  11419. // we get 2 points with a small delta and find a gradient of the 2 points
  11420. // which seems to make a reasonable approximation
  11421. THREE.Curve.prototype.getNormalVector = function( t ) {
  11422. var vec = this.getTangent( t );
  11423. return new THREE.Vector2( -vec.y , vec.x );
  11424. };
  11425. // Returns a unit vector tangent at t
  11426. THREE.Curve.prototype.getTangent = function( t ) {
  11427. var delta = 0.0001;
  11428. var t1 = t - delta;
  11429. var t2 = t + delta;
  11430. // Capping in case of danger
  11431. if ( t1 < 0 ) t1 = 0;
  11432. if ( t2 > 1 ) t2 = 1;
  11433. var pt1 = this.getPoint( t1 );
  11434. var pt2 = this.getPoint( t2 );
  11435. var vec = pt2.clone().subSelf(pt1);
  11436. return vec.normalize();
  11437. };
  11438. THREE.Curve.prototype.getTangentAt = function ( u ) {
  11439. var t = this.getUtoTmapping( u );
  11440. return this.getTangent( t );
  11441. };
  11442. /**************************************************************
  11443. * Line
  11444. **************************************************************/
  11445. THREE.LineCurve = function ( v1, v2 ) {
  11446. if ( ! ( v1 instanceof THREE.Vector2 ) ) {
  11447. // Fall back for old constuctor signature - should be removed over time
  11448. THREE.LineCurve.oldConstructor.apply( this, arguments );
  11449. return;
  11450. }
  11451. this.v1 = v1;
  11452. this.v2 = v2;
  11453. };
  11454. THREE.LineCurve.oldConstructor = function ( x1, y1, x2, y2 ) {
  11455. this.constructor( new THREE.Vector2( x1, y1 ), new THREE.Vector2( x2, y2 ) );
  11456. };
  11457. THREE.LineCurve.prototype = new THREE.Curve();
  11458. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  11459. THREE.LineCurve.prototype.getPoint = function ( t ) {
  11460. var point = new THREE.Vector2();
  11461. point.sub( this.v2, this.v1 );
  11462. point.multiplyScalar( t ).addSelf( this.v1 );
  11463. return point;
  11464. };
  11465. // Line curve is linear, so we can overwrite default getPointAt
  11466. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  11467. return this.getPoint( u );
  11468. };
  11469. THREE.LineCurve.prototype.getTangent = function( t ) {
  11470. var tangent = new THREE.Vector2();
  11471. tangent.sub( this.v2, this.v1 );
  11472. tangent.normalize();
  11473. return tangent;
  11474. };
  11475. /**************************************************************
  11476. * Quadratic Bezier curve
  11477. **************************************************************/
  11478. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  11479. if ( !( v1 instanceof THREE.Vector2 ) ) {
  11480. var args = Array.prototype.slice.call( arguments );
  11481. v0 = new THREE.Vector2( args[ 0 ], args[ 1 ] );
  11482. v1 = new THREE.Vector2( args[ 2 ], args[ 3 ] );
  11483. v2 = new THREE.Vector2( args[ 4 ], args[ 5 ] );
  11484. }
  11485. this.v0 = v0;
  11486. this.v1 = v1;
  11487. this.v2 = v2;
  11488. };
  11489. THREE.QuadraticBezierCurve.prototype = new THREE.Curve();
  11490. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  11491. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  11492. var tx, ty;
  11493. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  11494. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  11495. return new THREE.Vector2( tx, ty );
  11496. };
  11497. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  11498. // iterate sub segments
  11499. // get lengths for sub segments
  11500. // if segment is bezier
  11501. // perform subdivisions
  11502. var tx, ty;
  11503. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  11504. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  11505. // returns unit vector
  11506. var tangent = new THREE.Vector2( tx, ty );
  11507. tangent.normalize();
  11508. return tangent;
  11509. };
  11510. /**************************************************************
  11511. * Cubic Bezier curve
  11512. **************************************************************/
  11513. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  11514. if ( ! ( v1 instanceof THREE.Vector2 ) ) {
  11515. var args = Array.prototype.slice.call( arguments );
  11516. v0 = new THREE.Vector2( args[ 0 ], args[ 1 ] );
  11517. v1 = new THREE.Vector2( args[ 2 ], args[ 3 ] );
  11518. v2 = new THREE.Vector2( args[ 4 ], args[ 5 ] );
  11519. v3 = new THREE.Vector2( args[ 6 ], args[ 7 ] );
  11520. }
  11521. this.v0 = v0;
  11522. this.v1 = v1;
  11523. this.v2 = v2;
  11524. this.v3 = v3;
  11525. };
  11526. THREE.CubicBezierCurve.prototype = new THREE.Curve();
  11527. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  11528. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  11529. var tx, ty;
  11530. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11531. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11532. return new THREE.Vector2( tx, ty );
  11533. };
  11534. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  11535. var tx, ty;
  11536. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11537. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11538. // return normal unit vector
  11539. var tangent = new THREE.Vector2( tx, ty );
  11540. tangent.normalize();
  11541. return tangent;
  11542. };
  11543. /**************************************************************
  11544. * Spline curve
  11545. **************************************************************/
  11546. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  11547. this.points = (points == undefined) ? [] : points;
  11548. };
  11549. THREE.SplineCurve.prototype = new THREE.Curve();
  11550. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  11551. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  11552. var v = new THREE.Vector2();
  11553. var c = [];
  11554. var points = this.points, point, intPoint, weight;
  11555. point = ( points.length - 1 ) * t;
  11556. intPoint = Math.floor( point );
  11557. weight = point - intPoint;
  11558. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11559. c[ 1 ] = intPoint;
  11560. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  11561. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  11562. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  11563. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  11564. return v;
  11565. };
  11566. /**************************************************************
  11567. * Arc curve
  11568. **************************************************************/
  11569. THREE.ArcCurve = function ( aX, aY, aRadius,
  11570. aStartAngle, aEndAngle,
  11571. aClockwise ) {
  11572. this.aX = aX;
  11573. this.aY = aY;
  11574. this.aRadius = aRadius;
  11575. this.aStartAngle = aStartAngle;
  11576. this.aEndAngle = aEndAngle;
  11577. this.aClockwise = aClockwise;
  11578. };
  11579. THREE.ArcCurve.prototype = new THREE.Curve();
  11580. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  11581. THREE.ArcCurve.prototype.getPoint = function ( t ) {
  11582. var deltaAngle = this.aEndAngle - this.aStartAngle;
  11583. if ( !this.aClockwise ) {
  11584. t = 1 - t;
  11585. }
  11586. var angle = this.aStartAngle + t * deltaAngle;
  11587. var tx = this.aX + this.aRadius * Math.cos( angle );
  11588. var ty = this.aY + this.aRadius * Math.sin( angle );
  11589. return new THREE.Vector2( tx, ty );
  11590. };
  11591. /**************************************************************
  11592. * Utils
  11593. **************************************************************/
  11594. THREE.Curve.Utils = {
  11595. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  11596. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  11597. },
  11598. // Puay Bing, thanks for helping with this derivative!
  11599. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  11600. return -3 * p0 * (1 - t) * (1 - t) +
  11601. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  11602. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  11603. 3 * t * t * p3;
  11604. },
  11605. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  11606. // To check if my formulas are correct
  11607. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  11608. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  11609. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  11610. var h11 = 3 * t * t - 2 * t; // t3 − t2
  11611. return h00 + h10 + h01 + h11;
  11612. },
  11613. // Catmull-Rom
  11614. interpolate: function( p0, p1, p2, p3, t ) {
  11615. var v0 = ( p2 - p0 ) * 0.5;
  11616. var v1 = ( p3 - p1 ) * 0.5;
  11617. var t2 = t * t;
  11618. var t3 = t * t2;
  11619. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  11620. }
  11621. };
  11622. /*
  11623. getPoint DONE
  11624. getLength DONE
  11625. getLengths DONE
  11626. curve.getPoints(); DONE
  11627. curve.getPointAtArcLength(t); DONE
  11628. curve.transform(params);
  11629. curve.getTangentAt(t); DONE
  11630. */
  11631. /**************************************************************
  11632. * 3D Curves
  11633. **************************************************************/
  11634. // A Factory method for creating new curve subclasses
  11635. THREE.Curve.create = function( constructor, getPointFunc ) {
  11636. var subClass = constructor;
  11637. subClass.prototype = new THREE.Curve();
  11638. subClass.prototype.constructor = constructor;
  11639. subClass.prototype.getPoint = getPointFunc;
  11640. return subClass;
  11641. };
  11642. /**************************************************************
  11643. * Line3D
  11644. **************************************************************/
  11645. THREE.LineCurve3 = THREE.Curve.create(
  11646. function ( v1, v2 ) {
  11647. this.v1 = v1;
  11648. this.v2 = v2;
  11649. },
  11650. function ( t ) {
  11651. var r = new THREE.Vector3();
  11652. r.sub( this.v2, this.v1 ); // diff
  11653. r.multiplyScalar( t );
  11654. r.addSelf( this.v1 );
  11655. return r;
  11656. }
  11657. );
  11658. /**************************************************************
  11659. * Quadratic Bezier 3D curve
  11660. **************************************************************/
  11661. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  11662. function ( v0, v1, v2 ) {
  11663. this.v0 = v0;
  11664. this.v1 = v1;
  11665. this.v2 = v2;
  11666. },
  11667. function ( t ) {
  11668. var tx, ty, tz;
  11669. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  11670. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  11671. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  11672. return new THREE.Vector3( tx, ty, tz );
  11673. }
  11674. );
  11675. /**************************************************************
  11676. * Cubic Bezier 3D curve
  11677. **************************************************************/
  11678. THREE.CubicBezierCurve3 = THREE.Curve.create(
  11679. function ( v0, v1, v2, v3 ) {
  11680. this.v0 = v0;
  11681. this.v1 = v1;
  11682. this.v2 = v2;
  11683. this.v3 = v3;
  11684. },
  11685. function ( t ) {
  11686. var tx, ty, tz;
  11687. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  11688. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  11689. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  11690. return new THREE.Vector3( tx, ty, tz );
  11691. }
  11692. );
  11693. /**************************************************************
  11694. * Spline 3D curve
  11695. **************************************************************/
  11696. THREE.SplineCurve3 = THREE.Curve.create(
  11697. function ( points /* array of Vector3 */) {
  11698. this.points = (points == undefined) ? [] : points;
  11699. },
  11700. function ( t ) {
  11701. var v = new THREE.Vector3();
  11702. var c = [];
  11703. var points = this.points, point, intPoint, weight;
  11704. point = ( points.length - 1 ) * t;
  11705. intPoint = Math.floor( point );
  11706. weight = point - intPoint;
  11707. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11708. c[ 1 ] = intPoint;
  11709. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  11710. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  11711. var pt0 = points[ c[0] ],
  11712. pt1 = points[ c[1] ],
  11713. pt2 = points[ c[2] ],
  11714. pt3 = points[ c[3] ];
  11715. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  11716. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  11717. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  11718. return v;
  11719. }
  11720. );
  11721. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  11722. // var v = new THREE.Vector3();
  11723. // var c = [];
  11724. // var points = this.points, point, intPoint, weight;
  11725. // point = ( points.length - 1 ) * t;
  11726. // intPoint = Math.floor( point );
  11727. // weight = point - intPoint;
  11728. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  11729. // c[ 1 ] = intPoint;
  11730. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  11731. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  11732. // var pt0 = points[ c[0] ],
  11733. // pt1 = points[ c[1] ],
  11734. // pt2 = points[ c[2] ],
  11735. // pt3 = points[ c[3] ];
  11736. // // t = weight;
  11737. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  11738. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  11739. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  11740. // return v;
  11741. // }
  11742. /**************************************************************
  11743. * Closed Spline 3D curve
  11744. **************************************************************/
  11745. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  11746. function ( points /* array of Vector3 */) {
  11747. this.points = (points == undefined) ? [] : points;
  11748. },
  11749. function ( t ) {
  11750. var v = new THREE.Vector3();
  11751. var c = [];
  11752. var points = this.points, point, intPoint, weight;
  11753. point = ( points.length - 0 ) * t;
  11754. // This needs to be from 0-length +1
  11755. intPoint = Math.floor( point );
  11756. weight = point - intPoint;
  11757. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  11758. c[ 0 ] = ( intPoint - 1 ) % points.length;
  11759. c[ 1 ] = ( intPoint ) % points.length;
  11760. c[ 2 ] = ( intPoint + 1 ) % points.length;
  11761. c[ 3 ] = ( intPoint + 2 ) % points.length;
  11762. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  11763. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  11764. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  11765. return v;
  11766. }
  11767. );/**
  11768. * @author zz85 / http://www.lab4games.net/zz85/blog
  11769. *
  11770. **/
  11771. /**************************************************************
  11772. * Curved Path - a curve path is simply a array of connected
  11773. * curves, but retains the api of a curve
  11774. **************************************************************/
  11775. THREE.CurvePath = function () {
  11776. this.curves = [];
  11777. this.bends = [];
  11778. this.autoClose = false; // Automatically closes the path
  11779. };
  11780. THREE.CurvePath.prototype = new THREE.Curve();
  11781. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  11782. THREE.CurvePath.prototype.add = function ( curve ) {
  11783. this.curves.push( curve );
  11784. };
  11785. THREE.CurvePath.prototype.checkConnection = function() {
  11786. // TODO
  11787. // If the ending of curve is not connected to the starting
  11788. // or the next curve, then, this is not a real path
  11789. };
  11790. THREE.CurvePath.prototype.closePath = function() {
  11791. // TODO Test
  11792. // and verify for vector3 (needs to implement equals)
  11793. // Add a line curve if start and end of lines are not connected
  11794. var startPoint = this.curves[0].getPoint(0);
  11795. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  11796. if (!startPoint.equals(endPoint)) {
  11797. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  11798. }
  11799. };
  11800. // To get accurate point with reference to
  11801. // entire path distance at time t,
  11802. // following has to be done:
  11803. // 1. Length of each sub path have to be known
  11804. // 2. Locate and identify type of curve
  11805. // 3. Get t for the curve
  11806. // 4. Return curve.getPointAt(t')
  11807. THREE.CurvePath.prototype.getPoint = function( t ) {
  11808. var d = t * this.getLength();
  11809. var curveLengths = this.getCurveLengths();
  11810. var i = 0, diff, curve;
  11811. // To think about boundaries points.
  11812. while ( i < curveLengths.length ) {
  11813. if ( curveLengths[ i ] >= d ) {
  11814. diff = curveLengths[ i ] - d;
  11815. curve = this.curves[ i ];
  11816. var u = 1 - diff / curve.getLength();
  11817. return curve.getPointAt( u );
  11818. break;
  11819. }
  11820. i ++;
  11821. }
  11822. return null;
  11823. // loop where sum != 0, sum > d , sum+1 <d
  11824. };
  11825. /*
  11826. THREE.CurvePath.prototype.getTangent = function( t ) {
  11827. };*/
  11828. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  11829. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  11830. // getPoint() depends on getLength
  11831. THREE.CurvePath.prototype.getLength = function() {
  11832. var lens = this.getCurveLengths();
  11833. return lens[ lens.length - 1 ];
  11834. };
  11835. // Compute lengths and cache them
  11836. // We cannot overwrite getLengths() because UtoT mapping uses it.
  11837. THREE.CurvePath.prototype.getCurveLengths = function() {
  11838. // We use cache values if curves and cache array are same length
  11839. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  11840. return this.cacheLengths;
  11841. };
  11842. // Get length of subsurve
  11843. // Push sums into cached array
  11844. var lengths = [], sums = 0;
  11845. var i, il = this.curves.length;
  11846. for ( i = 0; i < il; i ++ ) {
  11847. sums += this.curves[ i ].getLength();
  11848. lengths.push( sums );
  11849. }
  11850. this.cacheLengths = lengths;
  11851. return lengths;
  11852. };
  11853. // Returns min and max coordinates, as well as centroid
  11854. THREE.CurvePath.prototype.getBoundingBox = function () {
  11855. var points = this.getPoints();
  11856. var maxX, maxY;
  11857. var minX, minY;
  11858. maxX = maxY = Number.NEGATIVE_INFINITY;
  11859. minX = minY = Number.POSITIVE_INFINITY;
  11860. var p, i, il, sum;
  11861. sum = new THREE.Vector2();
  11862. for ( i = 0, il = points.length; i < il; i ++ ) {
  11863. p = points[ i ];
  11864. if ( p.x > maxX ) maxX = p.x;
  11865. else if ( p.x < minX ) minX = p.x;
  11866. if ( p.y > maxY ) maxY = p.y;
  11867. else if ( p.y < maxY ) minY = p.y;
  11868. sum.addSelf( p.x, p.y );
  11869. }
  11870. return {
  11871. minX: minX,
  11872. minY: minY,
  11873. maxX: maxX,
  11874. maxY: maxY,
  11875. centroid: sum.divideScalar( il )
  11876. };
  11877. };
  11878. /**************************************************************
  11879. * Create Geometries Helpers
  11880. **************************************************************/
  11881. /// Generate geometry from path points (for Line or ParticleSystem objects)
  11882. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  11883. var pts = this.getPoints( divisions, true );
  11884. return this.createGeometry( pts );
  11885. };
  11886. // Generate geometry from equidistance sampling along the path
  11887. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  11888. var pts = this.getSpacedPoints( divisions, true );
  11889. return this.createGeometry( pts );
  11890. };
  11891. THREE.CurvePath.prototype.createGeometry = function( points ) {
  11892. var geometry = new THREE.Geometry();
  11893. for( var i = 0; i < points.length; i ++ ) {
  11894. geometry.vertices.push( new THREE.Vertex( new THREE.Vector3( points[ i ].x, points[ i ].y, 0 ) ) );
  11895. }
  11896. return geometry;
  11897. };
  11898. /**************************************************************
  11899. * Bend / Wrap Helper Methods
  11900. **************************************************************/
  11901. // Wrap path / Bend modifiers?
  11902. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  11903. this.bends.push( bendpath );
  11904. };
  11905. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  11906. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  11907. var i, il;
  11908. if ( !bends ) {
  11909. bends = this.bends;
  11910. }
  11911. for ( i = 0, il = bends.length; i < il; i ++ ) {
  11912. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  11913. }
  11914. return oldPts;
  11915. };
  11916. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  11917. var oldPts = this.getSpacedPoints( segments );
  11918. var i, il;
  11919. if ( !bends ) {
  11920. bends = this.bends;
  11921. }
  11922. for ( i = 0, il = bends.length; i < il; i ++ ) {
  11923. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  11924. }
  11925. return oldPts;
  11926. };
  11927. // This returns getPoints() bend/wrapped around the contour of a path.
  11928. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  11929. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  11930. var bounds = this.getBoundingBox();
  11931. var i, il, p, oldX, oldY, xNorm;
  11932. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  11933. p = oldPts[ i ];
  11934. oldX = p.x;
  11935. oldY = p.y;
  11936. xNorm = oldX / bounds.maxX;
  11937. // If using actual distance, for length > path, requires line extrusions
  11938. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  11939. xNorm = path.getUtoTmapping( xNorm, oldX );
  11940. // check for out of bounds?
  11941. var pathPt = path.getPoint( xNorm );
  11942. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  11943. p.x = pathPt.x + normal.x;
  11944. p.y = pathPt.y + normal.y;
  11945. }
  11946. return oldPts;
  11947. };
  11948. /**
  11949. * https://github.com/mrdoob/eventtarget.js/
  11950. */
  11951. THREE.EventTarget = function () {
  11952. var listeners = {};
  11953. this.addEventListener = function ( type, listener ) {
  11954. if ( listeners[ type ] == undefined ) {
  11955. listeners[ type ] = [];
  11956. }
  11957. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  11958. listeners[ type ].push( listener );
  11959. }
  11960. };
  11961. this.dispatchEvent = function ( event ) {
  11962. for ( var listener in listeners[ event.type ] ) {
  11963. listeners[ event.type ][ listener ]( event );
  11964. }
  11965. };
  11966. this.removeEventListener = function ( type, listener ) {
  11967. var index = listeners[ type ].indexOf( listener );
  11968. if ( index !== - 1 ) {
  11969. listeners[ type ].splice( index, 1 );
  11970. }
  11971. };
  11972. };
  11973. /**
  11974. * @author alteredq / http://alteredqualia.com/
  11975. */
  11976. THREE.Gyroscope = function () {
  11977. THREE.Object3D.call( this );
  11978. };
  11979. THREE.Gyroscope.prototype = new THREE.Object3D();
  11980. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  11981. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  11982. this.matrixAutoUpdate && this.updateMatrix();
  11983. // update matrixWorld
  11984. if ( this.matrixWorldNeedsUpdate || force ) {
  11985. if ( this.parent ) {
  11986. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  11987. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  11988. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  11989. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  11990. } else {
  11991. this.matrixWorld.copy( this.matrix );
  11992. }
  11993. this.matrixWorldNeedsUpdate = false;
  11994. force = true;
  11995. }
  11996. // update children
  11997. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  11998. this.children[ i ].updateMatrixWorld( force );
  11999. }
  12000. };
  12001. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  12002. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  12003. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  12004. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  12005. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  12006. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  12007. /**
  12008. * @author zz85 / http://www.lab4games.net/zz85/blog
  12009. * Creates free form 2d path using series of points, lines or curves.
  12010. *
  12011. **/
  12012. THREE.Path = function ( points ) {
  12013. THREE.CurvePath.call(this);
  12014. this.actions = [];
  12015. if ( points ) {
  12016. this.fromPoints( points );
  12017. }
  12018. };
  12019. THREE.Path.prototype = new THREE.CurvePath();
  12020. THREE.Path.prototype.constructor = THREE.Path;
  12021. THREE.PathActions = {
  12022. MOVE_TO: 'moveTo',
  12023. LINE_TO: 'lineTo',
  12024. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  12025. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  12026. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  12027. ARC: 'arc' // Circle
  12028. };
  12029. // TODO Clean up PATH API
  12030. // Create path using straight lines to connect all points
  12031. // - vectors: array of Vector2
  12032. THREE.Path.prototype.fromPoints = function ( vectors ) {
  12033. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  12034. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  12035. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  12036. };
  12037. };
  12038. // startPath() endPath()?
  12039. THREE.Path.prototype.moveTo = function ( x, y ) {
  12040. var args = Array.prototype.slice.call( arguments );
  12041. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  12042. };
  12043. THREE.Path.prototype.lineTo = function ( x, y ) {
  12044. var args = Array.prototype.slice.call( arguments );
  12045. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12046. var x0 = lastargs[ lastargs.length - 2 ];
  12047. var y0 = lastargs[ lastargs.length - 1 ];
  12048. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  12049. this.curves.push( curve );
  12050. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  12051. };
  12052. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  12053. var args = Array.prototype.slice.call( arguments );
  12054. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12055. var x0 = lastargs[ lastargs.length - 2 ];
  12056. var y0 = lastargs[ lastargs.length - 1 ];
  12057. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  12058. new THREE.Vector2( aCPx, aCPy ),
  12059. new THREE.Vector2( aX, aY ) );
  12060. this.curves.push( curve );
  12061. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  12062. };
  12063. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  12064. aCP2x, aCP2y,
  12065. aX, aY ) {
  12066. var args = Array.prototype.slice.call( arguments );
  12067. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12068. var x0 = lastargs[ lastargs.length - 2 ];
  12069. var y0 = lastargs[ lastargs.length - 1 ];
  12070. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  12071. new THREE.Vector2( aCP1x, aCP1y ),
  12072. new THREE.Vector2( aCP2x, aCP2y ),
  12073. new THREE.Vector2( aX, aY ) );
  12074. this.curves.push( curve );
  12075. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  12076. };
  12077. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  12078. var args = Array.prototype.slice.call( arguments );
  12079. var lastargs = this.actions[ this.actions.length - 1 ].args;
  12080. var x0 = lastargs[ lastargs.length - 2 ];
  12081. var y0 = lastargs[ lastargs.length - 1 ];
  12082. //---
  12083. var npts = [ new THREE.Vector2( x0, y0 ) ];
  12084. Array.prototype.push.apply( npts, pts );
  12085. var curve = new THREE.SplineCurve( npts );
  12086. this.curves.push( curve );
  12087. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  12088. };
  12089. // FUTURE: Change the API or follow canvas API?
  12090. // TODO ARC ( x, y, x - radius, y - radius, startAngle, endAngle )
  12091. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  12092. aStartAngle, aEndAngle, aClockwise ) {
  12093. var args = Array.prototype.slice.call( arguments );
  12094. var laste = this.actions[ this.actions.length - 1];
  12095. var curve = new THREE.ArcCurve( laste.x + aX, laste.y + aY, aRadius,
  12096. aStartAngle, aEndAngle, aClockwise );
  12097. this.curves.push( curve );
  12098. // All of the other actions look to the last two elements in the list to
  12099. // find the ending point, so we need to append them.
  12100. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  12101. args.push(lastPoint.x);
  12102. args.push(lastPoint.y);
  12103. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  12104. };
  12105. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  12106. aStartAngle, aEndAngle, aClockwise ) {
  12107. var args = Array.prototype.slice.call( arguments );
  12108. var curve = new THREE.ArcCurve( aX, aY, aRadius,
  12109. aStartAngle, aEndAngle, aClockwise );
  12110. this.curves.push( curve );
  12111. // console.log( 'arc', args );
  12112. // All of the other actions look to the last two elements in the list to
  12113. // find the ending point, so we need to append them.
  12114. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  12115. args.push(lastPoint.x);
  12116. args.push(lastPoint.y);
  12117. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  12118. };
  12119. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  12120. if ( ! divisions ) divisions = 40;
  12121. var points = [];
  12122. for ( var i = 0; i < divisions; i ++ ) {
  12123. points.push( this.getPoint( i / divisions ) );
  12124. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  12125. }
  12126. // if ( closedPath ) {
  12127. //
  12128. // points.push( points[ 0 ] );
  12129. //
  12130. // }
  12131. return points;
  12132. };
  12133. /* Return an array of vectors based on contour of the path */
  12134. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  12135. if (this.useSpacedPoints) {
  12136. console.log('tata');
  12137. return this.getSpacedPoints( divisions, closedPath );
  12138. }
  12139. divisions = divisions || 12;
  12140. var points = [];
  12141. var i, il, item, action, args;
  12142. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  12143. laste, j,
  12144. t, tx, ty;
  12145. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12146. item = this.actions[ i ];
  12147. action = item.action;
  12148. args = item.args;
  12149. switch( action ) {
  12150. case THREE.PathActions.MOVE_TO:
  12151. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  12152. break;
  12153. case THREE.PathActions.LINE_TO:
  12154. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  12155. break;
  12156. case THREE.PathActions.QUADRATIC_CURVE_TO:
  12157. cpx = args[ 2 ];
  12158. cpy = args[ 3 ];
  12159. cpx1 = args[ 0 ];
  12160. cpy1 = args[ 1 ];
  12161. if ( points.length > 0 ) {
  12162. laste = points[ points.length - 1 ];
  12163. cpx0 = laste.x;
  12164. cpy0 = laste.y;
  12165. } else {
  12166. laste = this.actions[ i - 1 ].args;
  12167. cpx0 = laste[ laste.length - 2 ];
  12168. cpy0 = laste[ laste.length - 1 ];
  12169. }
  12170. for ( j = 1; j <= divisions; j ++ ) {
  12171. t = j / divisions;
  12172. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  12173. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  12174. points.push( new THREE.Vector2( tx, ty ) );
  12175. }
  12176. break;
  12177. case THREE.PathActions.BEZIER_CURVE_TO:
  12178. cpx = args[ 4 ];
  12179. cpy = args[ 5 ];
  12180. cpx1 = args[ 0 ];
  12181. cpy1 = args[ 1 ];
  12182. cpx2 = args[ 2 ];
  12183. cpy2 = args[ 3 ];
  12184. if ( points.length > 0 ) {
  12185. laste = points[ points.length - 1 ];
  12186. cpx0 = laste.x;
  12187. cpy0 = laste.y;
  12188. } else {
  12189. laste = this.actions[ i - 1 ].args;
  12190. cpx0 = laste[ laste.length - 2 ];
  12191. cpy0 = laste[ laste.length - 1 ];
  12192. }
  12193. for ( j = 1; j <= divisions; j ++ ) {
  12194. t = j / divisions;
  12195. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  12196. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  12197. points.push( new THREE.Vector2( tx, ty ) );
  12198. }
  12199. break;
  12200. case THREE.PathActions.CSPLINE_THRU:
  12201. laste = this.actions[ i - 1 ].args;
  12202. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  12203. var spts = [ last ];
  12204. var n = divisions * args[ 0 ].length;
  12205. spts = spts.concat( args[ 0 ] );
  12206. var spline = new THREE.SplineCurve( spts );
  12207. for ( j = 1; j <= n; j ++ ) {
  12208. points.push( spline.getPointAt( j / n ) ) ;
  12209. }
  12210. break;
  12211. case THREE.PathActions.ARC:
  12212. laste = this.actions[ i - 1 ].args;
  12213. var aX = args[ 0 ], aY = args[ 1 ],
  12214. aRadius = args[ 2 ],
  12215. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  12216. aClockwise = !!args[ 5 ];
  12217. var deltaAngle = aEndAngle - aStartAngle;
  12218. var angle;
  12219. var tdivisions = divisions * 2;
  12220. for ( j = 1; j <= tdivisions; j ++ ) {
  12221. t = j / tdivisions;
  12222. if ( ! aClockwise ) {
  12223. t = 1 - t;
  12224. }
  12225. angle = aStartAngle + t * deltaAngle;
  12226. tx = aX + aRadius * Math.cos( angle );
  12227. ty = aY + aRadius * Math.sin( angle );
  12228. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  12229. points.push( new THREE.Vector2( tx, ty ) );
  12230. }
  12231. //console.log(points);
  12232. break;
  12233. } // end switch
  12234. }
  12235. // Normalize to remove the closing point by default.
  12236. var lastPoint = points[ points.length - 1];
  12237. var EPSILON = 0.0000000001;
  12238. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  12239. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  12240. points.splice( points.length - 1, 1);
  12241. if ( closedPath ) {
  12242. points.push( points[ 0 ] );
  12243. }
  12244. return points;
  12245. };
  12246. // This was used for testing purposes. Should be removed soon.
  12247. THREE.Path.prototype.transform = function( path, segments ) {
  12248. var bounds = this.getBoundingBox();
  12249. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  12250. //console.log( path.cacheArcLengths() );
  12251. //path.getLengths(400);
  12252. //segments = 40;
  12253. return this.getWrapPoints( oldPts, path );
  12254. };
  12255. // Read http://www.tinaja.com/glib/nonlingr.pdf
  12256. // nonlinear transforms
  12257. THREE.Path.prototype.nltransform = function( a, b, c, d, e, f ) {
  12258. // a - horizontal size
  12259. // b - lean
  12260. // c - x offset
  12261. // d - vertical size
  12262. // e - climb
  12263. // f - y offset
  12264. var oldPts = this.getPoints();
  12265. var i, il, p, oldX, oldY;
  12266. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  12267. p = oldPts[i];
  12268. oldX = p.x;
  12269. oldY = p.y;
  12270. p.x = a * oldX + b * oldY + c;
  12271. p.y = d * oldY + e * oldX + f;
  12272. }
  12273. return oldPts;
  12274. };
  12275. // FUTURE Export JSON Format
  12276. /* Draws this path onto a 2d canvas easily */
  12277. THREE.Path.prototype.debug = function( canvas ) {
  12278. var bounds = this.getBoundingBox();
  12279. if ( !canvas ) {
  12280. canvas = document.createElement( "canvas" );
  12281. canvas.setAttribute( 'width', bounds.maxX + 100 );
  12282. canvas.setAttribute( 'height', bounds.maxY + 100 );
  12283. document.body.appendChild( canvas );
  12284. }
  12285. var ctx = canvas.getContext( "2d" );
  12286. ctx.fillStyle = "white";
  12287. ctx.fillRect( 0, 0, canvas.width, canvas.height );
  12288. ctx.strokeStyle = "black";
  12289. ctx.beginPath();
  12290. var i, il, item, action, args;
  12291. // Debug Path
  12292. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12293. item = this.actions[ i ];
  12294. args = item.args;
  12295. action = item.action;
  12296. // Short hand for now
  12297. if ( action != THREE.PathActions.CSPLINE_THRU ) {
  12298. ctx[ action ].apply( ctx, args );
  12299. }
  12300. /*
  12301. switch ( action ) {
  12302. case THREE.PathActions.MOVE_TO:
  12303. ctx[ action ]( args[ 0 ], args[ 1 ] );
  12304. break;
  12305. case THREE.PathActions.LINE_TO:
  12306. ctx[ action ]( args[ 0 ], args[ 1 ] );
  12307. break;
  12308. case THREE.PathActions.QUADRATIC_CURVE_TO:
  12309. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ] );
  12310. break;
  12311. case THREE.PathActions.CUBIC_CURVE_TO:
  12312. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ], args[ 4 ], args[ 5 ] );
  12313. break;
  12314. }
  12315. */
  12316. }
  12317. ctx.stroke();
  12318. ctx.closePath();
  12319. // Debug Points
  12320. ctx.strokeStyle = "red";
  12321. /* TO CLEAN UP */
  12322. var p, points = this.getPoints();
  12323. for ( i = 0, il = points.length; i < il; i ++ ) {
  12324. p = points[ i ];
  12325. ctx.beginPath();
  12326. ctx.arc( p.x, p.y, 1.5, 0, Math.PI * 2, false );
  12327. ctx.stroke();
  12328. ctx.closePath();
  12329. }
  12330. };
  12331. // Breaks path into shapes
  12332. THREE.Path.prototype.toShapes = function() {
  12333. var i, il, item, action, args;
  12334. var subPaths = [], lastPath = new THREE.Path();
  12335. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  12336. item = this.actions[ i ];
  12337. args = item.args;
  12338. action = item.action;
  12339. if ( action == THREE.PathActions.MOVE_TO ) {
  12340. if ( lastPath.actions.length != 0 ) {
  12341. subPaths.push( lastPath );
  12342. lastPath = new THREE.Path();
  12343. }
  12344. }
  12345. lastPath[ action ].apply( lastPath, args );
  12346. }
  12347. if ( lastPath.actions.length != 0 ) {
  12348. subPaths.push( lastPath );
  12349. }
  12350. // console.log(subPaths);
  12351. if ( subPaths.length == 0 ) return [];
  12352. var tmpPath, tmpShape, shapes = [];
  12353. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  12354. // console.log("Holes first", holesFirst);
  12355. if ( subPaths.length == 1) {
  12356. tmpPath = subPaths[0];
  12357. tmpShape = new THREE.Shape();
  12358. tmpShape.actions = tmpPath.actions;
  12359. tmpShape.curves = tmpPath.curves;
  12360. shapes.push( tmpShape );
  12361. return shapes;
  12362. };
  12363. if ( holesFirst ) {
  12364. tmpShape = new THREE.Shape();
  12365. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  12366. tmpPath = subPaths[ i ];
  12367. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  12368. tmpShape.actions = tmpPath.actions;
  12369. tmpShape.curves = tmpPath.curves;
  12370. shapes.push( tmpShape );
  12371. tmpShape = new THREE.Shape();
  12372. //console.log('cw', i);
  12373. } else {
  12374. tmpShape.holes.push( tmpPath );
  12375. //console.log('ccw', i);
  12376. }
  12377. }
  12378. } else {
  12379. // Shapes first
  12380. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  12381. tmpPath = subPaths[ i ];
  12382. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  12383. if ( tmpShape ) shapes.push( tmpShape );
  12384. tmpShape = new THREE.Shape();
  12385. tmpShape.actions = tmpPath.actions;
  12386. tmpShape.curves = tmpPath.curves;
  12387. } else {
  12388. tmpShape.holes.push( tmpPath );
  12389. }
  12390. }
  12391. shapes.push( tmpShape );
  12392. }
  12393. //console.log("shape", shapes);
  12394. return shapes;
  12395. };
  12396. /**
  12397. * @author zz85 / http://www.lab4games.net/zz85/blog
  12398. * Defines a 2d shape plane using paths.
  12399. **/
  12400. // STEP 1 Create a path.
  12401. // STEP 2 Turn path into shape.
  12402. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  12403. // STEP 3a - Extract points from each shape, turn to vertices
  12404. // STEP 3b - Triangulate each shape, add faces.
  12405. THREE.Shape = function ( ) {
  12406. THREE.Path.apply( this, arguments );
  12407. this.holes = [];
  12408. };
  12409. THREE.Shape.prototype = new THREE.Path();
  12410. THREE.Shape.prototype.constructor = THREE.Path;
  12411. // Convenience method to return ExtrudeGeometry
  12412. THREE.Shape.prototype.extrude = function ( options ) {
  12413. var extruded = new THREE.ExtrudeGeometry( this, options );
  12414. return extruded;
  12415. };
  12416. // Get points of holes
  12417. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  12418. var i, il = this.holes.length, holesPts = [];
  12419. for ( i = 0; i < il; i ++ ) {
  12420. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  12421. }
  12422. return holesPts;
  12423. };
  12424. // Get points of holes (spaced by regular distance)
  12425. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  12426. var i, il = this.holes.length, holesPts = [];
  12427. for ( i = 0; i < il; i ++ ) {
  12428. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  12429. }
  12430. return holesPts;
  12431. };
  12432. // Get points of shape and holes (keypoints based on segments parameter)
  12433. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  12434. return {
  12435. shape: this.getTransformedPoints( divisions ),
  12436. holes: this.getPointsHoles( divisions )
  12437. };
  12438. };
  12439. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  12440. if (this.useSpacedPoints) {
  12441. return this.extractAllSpacedPoints(divisions);
  12442. }
  12443. return this.extractAllPoints(divisions);
  12444. };
  12445. //
  12446. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  12447. //
  12448. // return {
  12449. //
  12450. // shape: this.transform( bend, divisions ),
  12451. // holes: this.getPointsHoles( divisions, bend )
  12452. //
  12453. // };
  12454. //
  12455. // };
  12456. // Get points of shape and holes (spaced by regular distance)
  12457. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  12458. return {
  12459. shape: this.getTransformedSpacedPoints( divisions ),
  12460. holes: this.getSpacedPointsHoles( divisions )
  12461. };
  12462. };
  12463. /**************************************************************
  12464. * Utils
  12465. **************************************************************/
  12466. THREE.Shape.Utils = {
  12467. /*
  12468. contour - array of vector2 for contour
  12469. holes - array of array of vector2
  12470. */
  12471. removeHoles: function ( contour, holes ) {
  12472. var shape = contour.concat(); // work on this shape
  12473. var allpoints = shape.concat();
  12474. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  12475. var prevShapeVert, nextShapeVert,
  12476. prevHoleVert, nextHoleVert,
  12477. holeIndex, shapeIndex,
  12478. shapeId, shapeGroup,
  12479. h, h2,
  12480. hole, shortest, d,
  12481. p, pts1, pts2,
  12482. tmpShape1, tmpShape2,
  12483. tmpHole1, tmpHole2,
  12484. verts = [];
  12485. for ( h = 0; h < holes.length; h ++ ) {
  12486. hole = holes[ h ];
  12487. /*
  12488. shapeholes[ h ].concat(); // preserves original
  12489. holes.push( hole );
  12490. */
  12491. Array.prototype.push.apply( allpoints, hole );
  12492. shortest = Number.POSITIVE_INFINITY;
  12493. // Find the shortest pair of pts between shape and hole
  12494. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  12495. // Using distanceToSquared() intead of distanceTo() should speed a little
  12496. // since running square roots operations are reduced.
  12497. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  12498. pts1 = hole[ h2 ];
  12499. var dist = [];
  12500. for ( p = 0; p < shape.length; p++ ) {
  12501. pts2 = shape[ p ];
  12502. d = pts1.distanceToSquared( pts2 );
  12503. dist.push( d );
  12504. if ( d < shortest ) {
  12505. shortest = d;
  12506. holeIndex = h2;
  12507. shapeIndex = p;
  12508. }
  12509. }
  12510. }
  12511. //console.log("shortest", shortest, dist);
  12512. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12513. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12514. var areaapts = [
  12515. hole[ holeIndex ],
  12516. shape[ shapeIndex ],
  12517. shape[ prevShapeVert ]
  12518. ];
  12519. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  12520. var areabpts = [
  12521. hole[ holeIndex ],
  12522. hole[ prevHoleVert ],
  12523. shape[ shapeIndex ]
  12524. ];
  12525. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  12526. var shapeOffset = 1;
  12527. var holeOffset = -1;
  12528. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  12529. shapeIndex += shapeOffset;
  12530. holeIndex += holeOffset;
  12531. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  12532. shapeIndex %= shape.length;
  12533. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  12534. holeIndex %= hole.length;
  12535. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12536. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12537. areaapts = [
  12538. hole[ holeIndex ],
  12539. shape[ shapeIndex ],
  12540. shape[ prevShapeVert ]
  12541. ];
  12542. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  12543. areabpts = [
  12544. hole[ holeIndex ],
  12545. hole[ prevHoleVert ],
  12546. shape[ shapeIndex ]
  12547. ];
  12548. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  12549. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  12550. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  12551. // In case areas are not correct.
  12552. //console.log("USE THIS");
  12553. shapeIndex = oldShapeIndex;
  12554. holeIndex = oldHoleIndex ;
  12555. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  12556. shapeIndex %= shape.length;
  12557. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  12558. holeIndex %= hole.length;
  12559. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  12560. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  12561. } else {
  12562. //console.log("USE THAT ")
  12563. }
  12564. tmpShape1 = shape.slice( 0, shapeIndex );
  12565. tmpShape2 = shape.slice( shapeIndex );
  12566. tmpHole1 = hole.slice( holeIndex );
  12567. tmpHole2 = hole.slice( 0, holeIndex );
  12568. // Should check orders here again?
  12569. var trianglea = [
  12570. hole[ holeIndex ],
  12571. shape[ shapeIndex ],
  12572. shape[ prevShapeVert ]
  12573. ];
  12574. var triangleb = [
  12575. hole[ holeIndex ] ,
  12576. hole[ prevHoleVert ],
  12577. shape[ shapeIndex ]
  12578. ];
  12579. verts.push( trianglea );
  12580. verts.push( triangleb );
  12581. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  12582. }
  12583. return {
  12584. shape:shape, /* shape with no holes */
  12585. isolatedPts: verts, /* isolated faces */
  12586. allpoints: allpoints
  12587. }
  12588. },
  12589. triangulateShape: function ( contour, holes ) {
  12590. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  12591. var shape = shapeWithoutHoles.shape,
  12592. allpoints = shapeWithoutHoles.allpoints,
  12593. isolatedPts = shapeWithoutHoles.isolatedPts;
  12594. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  12595. // 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.
  12596. //console.log( "triangles",triangles, triangles.length );
  12597. //console.log( "allpoints",allpoints, allpoints.length );
  12598. var i, il, f, face,
  12599. key, index,
  12600. allPointsMap = {},
  12601. isolatedPointsMap = {};
  12602. // prepare all points map
  12603. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  12604. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  12605. if ( allPointsMap[ key ] !== undefined ) {
  12606. console.log( "Duplicate point", key );
  12607. }
  12608. allPointsMap[ key ] = i;
  12609. }
  12610. // check all face vertices against all points map
  12611. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  12612. face = triangles[ i ];
  12613. for ( f = 0; f < 3; f ++ ) {
  12614. key = face[ f ].x + ":" + face[ f ].y;
  12615. index = allPointsMap[ key ];
  12616. if ( index !== undefined ) {
  12617. face[ f ] = index;
  12618. }
  12619. }
  12620. }
  12621. // check isolated points vertices against all points map
  12622. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  12623. face = isolatedPts[ i ];
  12624. for ( f = 0; f < 3; f ++ ) {
  12625. key = face[ f ].x + ":" + face[ f ].y;
  12626. index = allPointsMap[ key ];
  12627. if ( index !== undefined ) {
  12628. face[ f ] = index;
  12629. }
  12630. }
  12631. }
  12632. return triangles.concat( isolatedPts );
  12633. }, // end triangulate shapes
  12634. /*
  12635. triangulate2 : function( pts, holes ) {
  12636. // For use with Poly2Tri.js
  12637. var allpts = pts.concat();
  12638. var shape = [];
  12639. for (var p in pts) {
  12640. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  12641. }
  12642. var swctx = new js.poly2tri.SweepContext(shape);
  12643. for (var h in holes) {
  12644. var aHole = holes[h];
  12645. var newHole = []
  12646. for (i in aHole) {
  12647. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  12648. allpts.push(aHole[i]);
  12649. }
  12650. swctx.AddHole(newHole);
  12651. }
  12652. var find;
  12653. var findIndexForPt = function (pt) {
  12654. find = new THREE.Vector2(pt.x, pt.y);
  12655. var p;
  12656. for (p=0, pl = allpts.length; p<pl; p++) {
  12657. if (allpts[p].equals(find)) return p;
  12658. }
  12659. return -1;
  12660. };
  12661. // triangulate
  12662. js.poly2tri.sweep.Triangulate(swctx);
  12663. var triangles = swctx.GetTriangles();
  12664. var tr ;
  12665. var facesPts = [];
  12666. for (var t in triangles) {
  12667. tr = triangles[t];
  12668. facesPts.push([
  12669. findIndexForPt(tr.GetPoint(0)),
  12670. findIndexForPt(tr.GetPoint(1)),
  12671. findIndexForPt(tr.GetPoint(2))
  12672. ]);
  12673. }
  12674. // console.log(facesPts);
  12675. // console.log("triangles", triangles.length, triangles);
  12676. // Returns array of faces with 3 element each
  12677. return facesPts;
  12678. },
  12679. */
  12680. isClockWise: function ( pts ) {
  12681. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  12682. },
  12683. // Bezier Curves formulas obtained from
  12684. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  12685. // Quad Bezier Functions
  12686. b2p0: function ( t, p ) {
  12687. var k = 1 - t;
  12688. return k * k * p;
  12689. },
  12690. b2p1: function ( t, p ) {
  12691. return 2 * ( 1 - t ) * t * p;
  12692. },
  12693. b2p2: function ( t, p ) {
  12694. return t * t * p;
  12695. },
  12696. b2: function ( t, p0, p1, p2 ) {
  12697. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  12698. },
  12699. // Cubic Bezier Functions
  12700. b3p0: function ( t, p ) {
  12701. var k = 1 - t;
  12702. return k * k * k * p;
  12703. },
  12704. b3p1: function ( t, p ) {
  12705. var k = 1 - t;
  12706. return 3 * k * k * t * p;
  12707. },
  12708. b3p2: function ( t, p ) {
  12709. var k = 1 - t;
  12710. return 3 * k * t * t * p;
  12711. },
  12712. b3p3: function ( t, p ) {
  12713. return t * t * t * p;
  12714. },
  12715. b3: function ( t, p0, p1, p2, p3 ) {
  12716. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  12717. }
  12718. };
  12719. /**
  12720. * @author zz85 / http://www.lab4games.net/zz85/blog
  12721. *
  12722. * TextPath
  12723. *
  12724. **/
  12725. THREE.TextPath = function ( text, parameters ) {
  12726. THREE.Path.call( this );
  12727. this.parameters = parameters || {};
  12728. this.set( text );
  12729. };
  12730. THREE.TextPath.prototype.set = function ( text, parameters ) {
  12731. parameters = parameters || this.parameters;
  12732. this.text = text;
  12733. var size = parameters.size !== undefined ? parameters.size : 100;
  12734. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  12735. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  12736. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  12737. var style = parameters.style !== undefined ? parameters.style : "normal";
  12738. THREE.FontUtils.size = size;
  12739. THREE.FontUtils.divisions = curveSegments;
  12740. THREE.FontUtils.face = font;
  12741. THREE.FontUtils.weight = weight;
  12742. THREE.FontUtils.style = style;
  12743. };
  12744. THREE.TextPath.prototype.toShapes = function () {
  12745. // Get a Font data json object
  12746. var data = THREE.FontUtils.drawText( this.text );
  12747. var paths = data.paths;
  12748. var shapes = [];
  12749. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  12750. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  12751. }
  12752. return shapes;
  12753. //console.log(path);
  12754. //console.log(fontShapes);
  12755. // Either find actions or curves.
  12756. //var text3d = new THREE.ExtrudeGeometry( shapes , { amount: 20, bevelEnabled:true, bevelThickness:3 } );
  12757. //return text3d;
  12758. };
  12759. /**
  12760. * @author mikael emtinger / http://gomo.se/
  12761. */
  12762. THREE.AnimationHandler = (function() {
  12763. var playing = [];
  12764. var library = {};
  12765. var that = {};
  12766. //--- update ---
  12767. that.update = function( deltaTimeMS ) {
  12768. for( var i = 0; i < playing.length; i++ )
  12769. playing[ i ].update( deltaTimeMS );
  12770. };
  12771. //--- add ---
  12772. that.addToUpdate = function( animation ) {
  12773. if( playing.indexOf( animation ) === -1 )
  12774. playing.push( animation );
  12775. };
  12776. //--- remove ---
  12777. that.removeFromUpdate = function( animation ) {
  12778. var index = playing.indexOf( animation );
  12779. if( index !== -1 )
  12780. playing.splice( index, 1 );
  12781. };
  12782. //--- add ---
  12783. that.add = function( data ) {
  12784. if( library[ data.name ] !== undefined )
  12785. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  12786. library[ data.name ] = data;
  12787. initData( data );
  12788. };
  12789. //--- get ---
  12790. that.get = function( name ) {
  12791. if( typeof name === "string" ) {
  12792. if( library[ name ] ) {
  12793. return library[ name ];
  12794. } else {
  12795. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  12796. return null;
  12797. }
  12798. } else {
  12799. // todo: add simple tween library
  12800. }
  12801. };
  12802. //--- parse ---
  12803. that.parse = function( root ) {
  12804. // setup hierarchy
  12805. var hierarchy = [];
  12806. if ( root instanceof THREE.SkinnedMesh ) {
  12807. for( var b = 0; b < root.bones.length; b++ ) {
  12808. hierarchy.push( root.bones[ b ] );
  12809. }
  12810. } else {
  12811. parseRecurseHierarchy( root, hierarchy );
  12812. }
  12813. return hierarchy;
  12814. };
  12815. var parseRecurseHierarchy = function( root, hierarchy ) {
  12816. hierarchy.push( root );
  12817. for( var c = 0; c < root.children.length; c++ )
  12818. parseRecurseHierarchy( root.children[ c ], hierarchy );
  12819. }
  12820. //--- init data ---
  12821. var initData = function( data ) {
  12822. if( data.initialized === true )
  12823. return;
  12824. // loop through all keys
  12825. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  12826. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12827. // remove minus times
  12828. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  12829. data.hierarchy[ h ].keys[ k ].time = 0;
  12830. // create quaternions
  12831. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  12832. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  12833. var quat = data.hierarchy[ h ].keys[ k ].rot;
  12834. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  12835. }
  12836. }
  12837. // prepare morph target keys
  12838. if( data.hierarchy[h].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  12839. // get all used
  12840. var usedMorphTargets = {};
  12841. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12842. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  12843. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  12844. usedMorphTargets[ morphTargetName ] = -1;
  12845. }
  12846. }
  12847. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  12848. // set all used on all frames
  12849. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12850. var influences = {};
  12851. for( var morphTargetName in usedMorphTargets ) {
  12852. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  12853. if( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  12854. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  12855. break;
  12856. }
  12857. }
  12858. if( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  12859. influences[ morphTargetName ] = 0;
  12860. }
  12861. }
  12862. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  12863. }
  12864. }
  12865. // remove all keys that are on the same time
  12866. for( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12867. if( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  12868. data.hierarchy[ h ].keys.splice( k, 1 );
  12869. k --;
  12870. }
  12871. }
  12872. // set index
  12873. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  12874. data.hierarchy[ h ].keys[ k ].index = k;
  12875. }
  12876. }
  12877. // JIT
  12878. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  12879. data.JIT = {};
  12880. data.JIT.hierarchy = [];
  12881. for( var h = 0; h < data.hierarchy.length; h ++ )
  12882. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  12883. // done
  12884. data.initialized = true;
  12885. };
  12886. // interpolation types
  12887. that.LINEAR = 0;
  12888. that.CATMULLROM = 1;
  12889. that.CATMULLROM_FORWARD = 2;
  12890. return that;
  12891. }());
  12892. /**
  12893. * @author mikael emtinger / http://gomo.se/
  12894. * @author mrdoob / http://mrdoob.com/
  12895. * @author alteredq / http://alteredqualia.com/
  12896. */
  12897. THREE.Animation = function( root, data, interpolationType, JITCompile ) {
  12898. this.root = root;
  12899. this.data = THREE.AnimationHandler.get( data );
  12900. this.hierarchy = THREE.AnimationHandler.parse( root );
  12901. this.currentTime = 0;
  12902. this.timeScale = 1;
  12903. this.isPlaying = false;
  12904. this.isPaused = true;
  12905. this.loop = true;
  12906. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  12907. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  12908. this.points = [];
  12909. this.target = new THREE.Vector3();
  12910. };
  12911. // Play
  12912. THREE.Animation.prototype.play = function( loop, startTimeMS ) {
  12913. if( !this.isPlaying ) {
  12914. this.isPlaying = true;
  12915. this.loop = loop !== undefined ? loop : true;
  12916. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  12917. // reset key cache
  12918. var h, hl = this.hierarchy.length,
  12919. object;
  12920. for ( h = 0; h < hl; h++ ) {
  12921. object = this.hierarchy[ h ];
  12922. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  12923. object.useQuaternion = true;
  12924. }
  12925. object.matrixAutoUpdate = true;
  12926. if ( object.animationCache === undefined ) {
  12927. object.animationCache = {};
  12928. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  12929. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  12930. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  12931. }
  12932. var prevKey = object.animationCache.prevKey;
  12933. var nextKey = object.animationCache.nextKey;
  12934. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  12935. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  12936. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  12937. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  12938. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  12939. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  12940. }
  12941. this.update( 0 );
  12942. }
  12943. this.isPaused = false;
  12944. THREE.AnimationHandler.addToUpdate( this );
  12945. };
  12946. // Pause
  12947. THREE.Animation.prototype.pause = function() {
  12948. if( this.isPaused ) {
  12949. THREE.AnimationHandler.addToUpdate( this );
  12950. } else {
  12951. THREE.AnimationHandler.removeFromUpdate( this );
  12952. }
  12953. this.isPaused = !this.isPaused;
  12954. };
  12955. // Stop
  12956. THREE.Animation.prototype.stop = function() {
  12957. this.isPlaying = false;
  12958. this.isPaused = false;
  12959. THREE.AnimationHandler.removeFromUpdate( this );
  12960. // reset JIT matrix and remove cache
  12961. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  12962. if ( this.hierarchy[ h ].animationCache !== undefined ) {
  12963. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  12964. this.hierarchy[ h ].skinMatrix = this.hierarchy[ h ].animationCache.originalMatrix;
  12965. } else {
  12966. this.hierarchy[ h ].matrix = this.hierarchy[ h ].animationCache.originalMatrix;
  12967. }
  12968. delete this.hierarchy[ h ].animationCache;
  12969. }
  12970. }
  12971. };
  12972. // Update
  12973. THREE.Animation.prototype.update = function( deltaTimeMS ) {
  12974. // early out
  12975. if( !this.isPlaying ) return;
  12976. // vars
  12977. var types = [ "pos", "rot", "scl" ];
  12978. var type;
  12979. var scale;
  12980. var vector;
  12981. var prevXYZ, nextXYZ;
  12982. var prevKey, nextKey;
  12983. var object;
  12984. var animationCache;
  12985. var frame;
  12986. var JIThierarchy = this.data.JIT.hierarchy;
  12987. var currentTime, unloopedCurrentTime;
  12988. var currentPoint, forwardPoint, angle;
  12989. // update
  12990. this.currentTime += deltaTimeMS * this.timeScale;
  12991. unloopedCurrentTime = this.currentTime;
  12992. currentTime = this.currentTime = this.currentTime % this.data.length;
  12993. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  12994. // update
  12995. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  12996. object = this.hierarchy[ h ];
  12997. animationCache = object.animationCache;
  12998. // use JIT?
  12999. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  13000. if( object instanceof THREE.Bone ) {
  13001. object.skinMatrix = JIThierarchy[ h ][ frame ];
  13002. object.matrixAutoUpdate = false;
  13003. object.matrixWorldNeedsUpdate = false;
  13004. } else {
  13005. object.matrix = JIThierarchy[ h ][ frame ];
  13006. object.matrixAutoUpdate = false;
  13007. object.matrixWorldNeedsUpdate = true;
  13008. }
  13009. // use interpolation
  13010. } else {
  13011. // make sure so original matrix and not JIT matrix is set
  13012. if ( this.JITCompile ) {
  13013. if( object instanceof THREE.Bone ) {
  13014. object.skinMatrix = object.animationCache.originalMatrix;
  13015. } else {
  13016. object.matrix = object.animationCache.originalMatrix;
  13017. }
  13018. }
  13019. // loop through pos/rot/scl
  13020. for ( var t = 0; t < 3; t++ ) {
  13021. // get keys
  13022. type = types[ t ];
  13023. prevKey = animationCache.prevKey[ type ];
  13024. nextKey = animationCache.nextKey[ type ];
  13025. // switch keys?
  13026. if ( nextKey.time <= unloopedCurrentTime ) {
  13027. // did we loop?
  13028. if ( currentTime < unloopedCurrentTime ) {
  13029. if ( this.loop ) {
  13030. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  13031. nextKey = this.getNextKeyWith( type, h, 1 );
  13032. while( nextKey.time < currentTime ) {
  13033. prevKey = nextKey;
  13034. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  13035. }
  13036. } else {
  13037. this.stop();
  13038. return;
  13039. }
  13040. } else {
  13041. do {
  13042. prevKey = nextKey;
  13043. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  13044. } while( nextKey.time < currentTime )
  13045. }
  13046. animationCache.prevKey[ type ] = prevKey;
  13047. animationCache.nextKey[ type ] = nextKey;
  13048. }
  13049. object.matrixAutoUpdate = true;
  13050. object.matrixWorldNeedsUpdate = true;
  13051. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  13052. prevXYZ = prevKey[ type ];
  13053. nextXYZ = nextKey[ type ];
  13054. // check scale error
  13055. if ( scale < 0 || scale > 1 ) {
  13056. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  13057. scale = scale < 0 ? 0 : 1;
  13058. }
  13059. // interpolate
  13060. if ( type === "pos" ) {
  13061. vector = object.position;
  13062. if( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  13063. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  13064. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  13065. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  13066. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13067. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13068. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  13069. this.points[ 1 ] = prevXYZ;
  13070. this.points[ 2 ] = nextXYZ;
  13071. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  13072. scale = scale * 0.33 + 0.33;
  13073. currentPoint = this.interpolateCatmullRom( this.points, scale );
  13074. vector.x = currentPoint[ 0 ];
  13075. vector.y = currentPoint[ 1 ];
  13076. vector.z = currentPoint[ 2 ];
  13077. if( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13078. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  13079. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  13080. this.target.subSelf( vector );
  13081. this.target.y = 0;
  13082. this.target.normalize();
  13083. angle = Math.atan2( this.target.x, this.target.z );
  13084. object.rotation.set( 0, angle, 0 );
  13085. }
  13086. }
  13087. } else if ( type === "rot" ) {
  13088. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  13089. } else if( type === "scl" ) {
  13090. vector = object.scale;
  13091. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  13092. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  13093. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  13094. }
  13095. }
  13096. }
  13097. }
  13098. // update JIT?
  13099. if ( this.JITCompile ) {
  13100. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  13101. this.hierarchy[ 0 ].updateMatrixWorld( true );
  13102. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  13103. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  13104. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  13105. } else {
  13106. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  13107. }
  13108. }
  13109. }
  13110. }
  13111. };
  13112. // Catmull-Rom spline
  13113. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  13114. var c = [], v3 = [],
  13115. point, intPoint, weight, w2, w3,
  13116. pa, pb, pc, pd;
  13117. point = ( points.length - 1 ) * scale;
  13118. intPoint = Math.floor( point );
  13119. weight = point - intPoint;
  13120. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  13121. c[ 1 ] = intPoint;
  13122. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  13123. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  13124. pa = points[ c[ 0 ] ];
  13125. pb = points[ c[ 1 ] ];
  13126. pc = points[ c[ 2 ] ];
  13127. pd = points[ c[ 3 ] ];
  13128. w2 = weight * weight;
  13129. w3 = weight * w2;
  13130. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  13131. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  13132. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  13133. return v3;
  13134. };
  13135. THREE.Animation.prototype.interpolate = function( p0, p1, p2, p3, t, t2, t3 ) {
  13136. var v0 = ( p2 - p0 ) * 0.5,
  13137. v1 = ( p3 - p1 ) * 0.5;
  13138. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  13139. };
  13140. // Get next key with
  13141. THREE.Animation.prototype.getNextKeyWith = function( type, h, key ) {
  13142. var keys = this.data.hierarchy[ h ].keys;
  13143. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13144. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13145. key = key < keys.length - 1 ? key : keys.length - 1;
  13146. } else {
  13147. key = key % keys.length;
  13148. }
  13149. for ( ; key < keys.length; key++ ) {
  13150. if ( keys[ key ][ type ] !== undefined ) {
  13151. return keys[ key ];
  13152. }
  13153. }
  13154. return this.data.hierarchy[ h ].keys[ 0 ];
  13155. };
  13156. // Get previous key with
  13157. THREE.Animation.prototype.getPrevKeyWith = function( type, h, key ) {
  13158. var keys = this.data.hierarchy[ h ].keys;
  13159. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  13160. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  13161. key = key > 0 ? key : 0;
  13162. } else {
  13163. key = key >= 0 ? key : key + keys.length;
  13164. }
  13165. for ( ; key >= 0; key-- ) {
  13166. if ( keys[ key ][ type ] !== undefined ) {
  13167. return keys[ key ];
  13168. }
  13169. }
  13170. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  13171. };/**
  13172. * @author mikael emtinger / http://gomo.se/
  13173. * @author mrdoob / http://mrdoob.com/
  13174. * @author alteredq / http://alteredqualia.com/
  13175. * @author khang duong
  13176. * @author erik kitson
  13177. */
  13178. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  13179. this.root = root;
  13180. this.data = THREE.AnimationHandler.get( data );
  13181. this.hierarchy = THREE.AnimationHandler.parse( root );
  13182. this.currentTime = 0;
  13183. this.timeScale = 0.001;
  13184. this.isPlaying = false;
  13185. this.isPaused = true;
  13186. this.loop = true;
  13187. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  13188. // initialize to first keyframes
  13189. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13190. var keys = this.data.hierarchy[h].keys,
  13191. sids = this.data.hierarchy[h].sids,
  13192. obj = this.hierarchy[h];
  13193. if ( keys.length && sids ) {
  13194. for ( var s = 0; s < sids.length; s++ ) {
  13195. var sid = sids[ s ],
  13196. next = this.getNextKeyWith( sid, h, 0 );
  13197. if ( next ) {
  13198. next.apply( sid );
  13199. }
  13200. }
  13201. obj.matrixAutoUpdate = false;
  13202. this.data.hierarchy[h].node.updateMatrix();
  13203. obj.matrixWorldNeedsUpdate = true;
  13204. }
  13205. }
  13206. };
  13207. // Play
  13208. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  13209. if( !this.isPlaying ) {
  13210. this.isPlaying = true;
  13211. this.loop = loop !== undefined ? loop : true;
  13212. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  13213. this.startTimeMs = startTimeMS;
  13214. this.startTime = 10000000;
  13215. this.endTime = -this.startTime;
  13216. // reset key cache
  13217. var h, hl = this.hierarchy.length,
  13218. object,
  13219. node;
  13220. for ( h = 0; h < hl; h++ ) {
  13221. object = this.hierarchy[ h ];
  13222. node = this.data.hierarchy[ h ];
  13223. object.useQuaternion = true;
  13224. if ( node.animationCache === undefined ) {
  13225. node.animationCache = {};
  13226. node.animationCache.prevKey = null;
  13227. node.animationCache.nextKey = null;
  13228. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  13229. }
  13230. var keys = this.data.hierarchy[h].keys;
  13231. if (keys.length) {
  13232. node.animationCache.prevKey = keys[ 0 ];
  13233. node.animationCache.nextKey = keys[ 1 ];
  13234. this.startTime = Math.min( keys[0].time, this.startTime );
  13235. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  13236. }
  13237. }
  13238. this.update( 0 );
  13239. }
  13240. this.isPaused = false;
  13241. THREE.AnimationHandler.addToUpdate( this );
  13242. };
  13243. // Pause
  13244. THREE.KeyFrameAnimation.prototype.pause = function() {
  13245. if( this.isPaused ) {
  13246. THREE.AnimationHandler.addToUpdate( this );
  13247. } else {
  13248. THREE.AnimationHandler.removeFromUpdate( this );
  13249. }
  13250. this.isPaused = !this.isPaused;
  13251. };
  13252. // Stop
  13253. THREE.KeyFrameAnimation.prototype.stop = function() {
  13254. this.isPlaying = false;
  13255. this.isPaused = false;
  13256. THREE.AnimationHandler.removeFromUpdate( this );
  13257. // reset JIT matrix and remove cache
  13258. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  13259. var obj = this.hierarchy[ h ];
  13260. var node = this.data.hierarchy[ h ];
  13261. if ( node.animationCache !== undefined ) {
  13262. var original = node.animationCache.originalMatrix;
  13263. if( obj instanceof THREE.Bone ) {
  13264. original.copy( obj.skinMatrix );
  13265. obj.skinMatrix = original;
  13266. } else {
  13267. original.copy( obj.matrix );
  13268. obj.matrix = original;
  13269. }
  13270. delete node.animationCache;
  13271. }
  13272. }
  13273. };
  13274. // Update
  13275. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  13276. // early out
  13277. if( !this.isPlaying ) return;
  13278. // vars
  13279. var prevKey, nextKey;
  13280. var object;
  13281. var node;
  13282. var frame;
  13283. var JIThierarchy = this.data.JIT.hierarchy;
  13284. var currentTime, unloopedCurrentTime;
  13285. var looped;
  13286. // update
  13287. this.currentTime += deltaTimeMS * this.timeScale;
  13288. unloopedCurrentTime = this.currentTime;
  13289. currentTime = this.currentTime = this.currentTime % this.data.length;
  13290. // if looped around, the current time should be based on the startTime
  13291. if ( currentTime < this.startTimeMs ) {
  13292. currentTime = this.currentTime = this.startTimeMs + currentTime;
  13293. }
  13294. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  13295. looped = currentTime < unloopedCurrentTime;
  13296. if ( looped && !this.loop ) {
  13297. // Set the animation to the last keyframes and stop
  13298. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13299. var keys = this.data.hierarchy[h].keys,
  13300. sids = this.data.hierarchy[h].sids,
  13301. end = keys.length-1,
  13302. obj = this.hierarchy[h];
  13303. if ( keys.length ) {
  13304. for ( var s = 0; s < sids.length; s++ ) {
  13305. var sid = sids[ s ],
  13306. prev = this.getPrevKeyWith( sid, h, end );
  13307. if ( prev ) {
  13308. prev.apply( sid );
  13309. }
  13310. }
  13311. this.data.hierarchy[h].node.updateMatrix();
  13312. obj.matrixWorldNeedsUpdate = true;
  13313. }
  13314. }
  13315. this.stop();
  13316. return;
  13317. }
  13318. // check pre-infinity
  13319. if ( currentTime < this.startTime ) {
  13320. return;
  13321. }
  13322. // update
  13323. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  13324. object = this.hierarchy[ h ];
  13325. node = this.data.hierarchy[ h ];
  13326. var keys = node.keys,
  13327. animationCache = node.animationCache;
  13328. // use JIT?
  13329. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  13330. if( object instanceof THREE.Bone ) {
  13331. object.skinMatrix = JIThierarchy[ h ][ frame ];
  13332. object.matrixWorldNeedsUpdate = false;
  13333. } else {
  13334. object.matrix = JIThierarchy[ h ][ frame ];
  13335. object.matrixWorldNeedsUpdate = true;
  13336. }
  13337. // use interpolation
  13338. } else if ( keys.length ) {
  13339. // make sure so original matrix and not JIT matrix is set
  13340. if ( this.JITCompile && animationCache ) {
  13341. if( object instanceof THREE.Bone ) {
  13342. object.skinMatrix = animationCache.originalMatrix;
  13343. } else {
  13344. object.matrix = animationCache.originalMatrix;
  13345. }
  13346. }
  13347. prevKey = animationCache.prevKey;
  13348. nextKey = animationCache.nextKey;
  13349. if ( prevKey && nextKey ) {
  13350. // switch keys?
  13351. if ( nextKey.time <= unloopedCurrentTime ) {
  13352. // did we loop?
  13353. if ( looped && this.loop ) {
  13354. prevKey = keys[ 0 ];
  13355. nextKey = keys[ 1 ];
  13356. while ( nextKey.time < currentTime ) {
  13357. prevKey = nextKey;
  13358. nextKey = keys[ prevKey.index + 1 ];
  13359. }
  13360. } else if ( !looped ) {
  13361. var lastIndex = keys.length - 1;
  13362. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  13363. prevKey = nextKey;
  13364. nextKey = keys[ prevKey.index + 1 ];
  13365. }
  13366. }
  13367. animationCache.prevKey = prevKey;
  13368. animationCache.nextKey = nextKey;
  13369. }
  13370. if(nextKey.time >= currentTime)
  13371. prevKey.interpolate( nextKey, currentTime );
  13372. else
  13373. prevKey.interpolate( nextKey, nextKey.time);
  13374. }
  13375. this.data.hierarchy[h].node.updateMatrix();
  13376. object.matrixWorldNeedsUpdate = true;
  13377. }
  13378. }
  13379. // update JIT?
  13380. if ( this.JITCompile ) {
  13381. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  13382. this.hierarchy[ 0 ].updateMatrixWorld( true );
  13383. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  13384. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  13385. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  13386. } else {
  13387. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  13388. }
  13389. }
  13390. }
  13391. }
  13392. };
  13393. // Get next key with
  13394. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  13395. var keys = this.data.hierarchy[ h ].keys;
  13396. key = key % keys.length;
  13397. for ( ; key < keys.length; key++ ) {
  13398. if ( keys[ key ].hasTarget( sid ) ) {
  13399. return keys[ key ];
  13400. }
  13401. }
  13402. return keys[ 0 ];
  13403. };
  13404. // Get previous key with
  13405. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  13406. var keys = this.data.hierarchy[ h ].keys;
  13407. key = key >= 0 ? key : key + keys.length;
  13408. for ( ; key >= 0; key-- ) {
  13409. if ( keys[ key ].hasTarget( sid ) ) {
  13410. return keys[ key ];
  13411. }
  13412. }
  13413. return keys[ keys.length - 1 ];
  13414. };
  13415. /**
  13416. * Camera for rendering cube maps
  13417. * - renders scene into axis-aligned cube
  13418. *
  13419. * @author alteredq / http://alteredqualia.com/
  13420. */
  13421. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  13422. this.position = new THREE.Vector3();
  13423. var fov = 90, aspect = 1;
  13424. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13425. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13426. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13427. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13428. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13429. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  13430. cameraPX.position = this.position;
  13431. cameraPX.up.set( 0, -1, 0 );
  13432. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  13433. cameraNX.position = this.position;
  13434. cameraNX.up.set( 0, -1, 0 );
  13435. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  13436. cameraPY.position = this.position;
  13437. cameraPY.up.set( 0, 0, 1 );
  13438. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  13439. cameraNY.position = this.position;
  13440. cameraNY.up.set( 0, 0, -1 );
  13441. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  13442. cameraPZ.position = this.position;
  13443. cameraPZ.up.set( 0, -1, 0 );
  13444. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  13445. cameraNZ.position = this.position;
  13446. cameraNZ.up.set( 0, -1, 0 );
  13447. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  13448. // cube render target
  13449. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  13450. this.updateCubeMap = function ( renderer, scene ) {
  13451. var cubeTarget = this.renderTarget;
  13452. var oldGenerateMipmaps = cubeTarget.generateMipmaps;
  13453. cubeTarget.generateMipmaps = false;
  13454. cubeTarget.activeCubeFace = 0;
  13455. renderer.render( scene, cameraPX, cubeTarget );
  13456. cubeTarget.activeCubeFace = 1;
  13457. renderer.render( scene, cameraNX, cubeTarget );
  13458. cubeTarget.activeCubeFace = 2;
  13459. renderer.render( scene, cameraPY, cubeTarget );
  13460. cubeTarget.activeCubeFace = 3;
  13461. renderer.render( scene, cameraNY, cubeTarget );
  13462. cubeTarget.activeCubeFace = 4;
  13463. renderer.render( scene, cameraPZ, cubeTarget );
  13464. cubeTarget.generateMipmaps = oldGenerateMipmaps;
  13465. cubeTarget.activeCubeFace = 5;
  13466. renderer.render( scene, cameraNZ, cubeTarget );
  13467. };
  13468. };
  13469. /*
  13470. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  13471. *
  13472. * A handy general perpose camera, for setting FOV, Lens Focal Length,
  13473. * and switching between perspective and orthographic views easily.
  13474. *
  13475. */
  13476. THREE.CombinedCamera = function ( width, height, fov, near, far, orthonear, orthofar ) {
  13477. THREE.Camera.call( this );
  13478. this.fov = fov;
  13479. this.left = -width / 2;
  13480. this.right = width / 2
  13481. this.top = height / 2;
  13482. this.bottom = -height / 2;
  13483. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  13484. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthonear, orthofar );
  13485. this.cameraP = new THREE.PerspectiveCamera( fov, width/height, near, far );
  13486. this.zoom = 1;
  13487. this.toPerspective();
  13488. var aspect = width/height;
  13489. };
  13490. THREE.CombinedCamera.prototype = new THREE.Camera();
  13491. THREE.CombinedCamera.prototype.constructor = THREE.CoolCamera;
  13492. THREE.CombinedCamera.prototype.toPerspective = function () {
  13493. this.near = this.cameraP.near;
  13494. this.far = this.cameraP.far;
  13495. this.cameraP.fov = this.fov / this.zoom ;
  13496. this.cameraP.updateProjectionMatrix();
  13497. this.projectionMatrix = this.cameraP.projectionMatrix;
  13498. this.inPersepectiveMode = true;
  13499. this.inOrthographicMode = false;
  13500. };
  13501. THREE.CombinedCamera.prototype.toOrthographic = function () {
  13502. // Orthographic from Perspective
  13503. var fov = this.fov;
  13504. var aspect = this.cameraP.aspect;
  13505. var near = this.cameraP.near;
  13506. var far = this.cameraP.far;
  13507. // Just pretend we want the mid plane of the viewing frustum
  13508. var hyperfocus = ( near + far ) / 2;
  13509. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  13510. var planeHeight = 2 * halfHeight;
  13511. var planeWidth = planeHeight * aspect;
  13512. var halfWidth = planeWidth / 2;
  13513. halfHeight /= this.zoom;
  13514. halfWidth /= this.zoom;
  13515. this.cameraO.left = -halfWidth;
  13516. this.cameraO.right = halfWidth;
  13517. this.cameraO.top = halfHeight;
  13518. this.cameraO.bottom = -halfHeight;
  13519. // this.cameraO.left = -farHalfWidth;
  13520. // this.cameraO.right = farHalfWidth;
  13521. // this.cameraO.top = farHalfHeight;
  13522. // this.cameraO.bottom = -farHalfHeight;
  13523. // this.cameraO.left = this.left / this.zoom;
  13524. // this.cameraO.right = this.right / this.zoom;
  13525. // this.cameraO.top = this.top / this.zoom;
  13526. // this.cameraO.bottom = this.bottom / this.zoom;
  13527. this.cameraO.updateProjectionMatrix();
  13528. this.near = this.cameraO.near;
  13529. this.far = this.cameraO.far;
  13530. this.projectionMatrix = this.cameraO.projectionMatrix;
  13531. this.inPersepectiveMode = false;
  13532. this.inOrthographicMode = true;
  13533. };
  13534. THREE.CombinedCamera.prototype.setFov = function(fov) {
  13535. this.fov = fov;
  13536. if (this.inPersepectiveMode) {
  13537. this.toPerspective();
  13538. } else {
  13539. this.toOrthographic();
  13540. }
  13541. };
  13542. /*
  13543. * Uses Focal Length (in mm) to estimate and set FOV
  13544. * 35mm (fullframe) camera is used if frame size is not specified;
  13545. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  13546. */
  13547. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  13548. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  13549. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  13550. this.setFov( fov );
  13551. return fov;
  13552. };
  13553. THREE.CombinedCamera.prototype.setZoom = function(zoom) {
  13554. this.zoom = zoom;
  13555. if (this.inPersepectiveMode) {
  13556. this.toPerspective();
  13557. } else {
  13558. this.toOrthographic();
  13559. }
  13560. };
  13561. THREE.CombinedCamera.prototype.toFrontView = function() {
  13562. this.rotation.x = 0;
  13563. this.rotation.y = 0;
  13564. this.rotation.z = 0;
  13565. //TODO: Better way to disable camera.lookAt()?
  13566. this.rotationAutoUpdate = false;
  13567. };
  13568. THREE.CombinedCamera.prototype.toBackView = function() {
  13569. this.rotation.x = 0;
  13570. this.rotation.y = Math.PI;
  13571. this.rotation.z = 0;
  13572. this.rotationAutoUpdate = false;
  13573. };
  13574. THREE.CombinedCamera.prototype.toLeftView = function() {
  13575. this.rotation.x = 0;
  13576. this.rotation.y = - Math.PI / 2;
  13577. this.rotation.z = 0;
  13578. this.rotationAutoUpdate = false;
  13579. };
  13580. THREE.CombinedCamera.prototype.toRightView = function() {
  13581. this.rotation.x = 0;
  13582. this.rotation.y = Math.PI / 2;
  13583. this.rotation.z = 0;
  13584. this.rotationAutoUpdate = false;
  13585. };
  13586. THREE.CombinedCamera.prototype.toTopView = function() {
  13587. this.rotation.x = - Math.PI / 2;
  13588. this.rotation.y = 0;
  13589. this.rotation.z = 0;
  13590. this.rotationAutoUpdate = false;
  13591. };
  13592. THREE.CombinedCamera.prototype.toBottomView = function() {
  13593. this.rotation.x = Math.PI / 2;
  13594. this.rotation.y = 0;
  13595. this.rotation.z = 0;
  13596. this.rotationAutoUpdate = false;
  13597. };
  13598. /**
  13599. * @author mrdoob / http://mrdoob.com/
  13600. * @author alteredq / http://alteredqualia.com/
  13601. * @author paulirish / http://paulirish.com/
  13602. */
  13603. THREE.FirstPersonControls = function ( object, domElement ) {
  13604. this.object = object;
  13605. this.target = new THREE.Vector3( 0, 0, 0 );
  13606. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13607. this.movementSpeed = 1.0;
  13608. this.lookSpeed = 0.005;
  13609. this.noFly = false;
  13610. this.lookVertical = true;
  13611. this.autoForward = false;
  13612. this.activeLook = true;
  13613. this.heightSpeed = false;
  13614. this.heightCoef = 1.0;
  13615. this.heightMin = 0.0;
  13616. this.constrainVertical = false;
  13617. this.verticalMin = 0;
  13618. this.verticalMax = Math.PI;
  13619. this.autoSpeedFactor = 0.0;
  13620. this.mouseX = 0;
  13621. this.mouseY = 0;
  13622. this.lat = 0;
  13623. this.lon = 0;
  13624. this.phi = 0;
  13625. this.theta = 0;
  13626. this.moveForward = false;
  13627. this.moveBackward = false;
  13628. this.moveLeft = false;
  13629. this.moveRight = false;
  13630. this.freeze = false;
  13631. this.mouseDragOn = false;
  13632. if ( this.domElement === document ) {
  13633. this.viewHalfX = window.innerWidth / 2;
  13634. this.viewHalfY = window.innerHeight / 2;
  13635. } else {
  13636. this.viewHalfX = this.domElement.offsetWidth / 2;
  13637. this.viewHalfY = this.domElement.offsetHeight / 2;
  13638. this.domElement.setAttribute( 'tabindex', -1 );
  13639. }
  13640. this.onMouseDown = function ( event ) {
  13641. if ( this.domElement !== document ) {
  13642. this.domElement.focus();
  13643. }
  13644. event.preventDefault();
  13645. event.stopPropagation();
  13646. if ( this.activeLook ) {
  13647. switch ( event.button ) {
  13648. case 0: this.moveForward = true; break;
  13649. case 2: this.moveBackward = true; break;
  13650. }
  13651. }
  13652. this.mouseDragOn = true;
  13653. };
  13654. this.onMouseUp = function ( event ) {
  13655. event.preventDefault();
  13656. event.stopPropagation();
  13657. if ( this.activeLook ) {
  13658. switch ( event.button ) {
  13659. case 0: this.moveForward = false; break;
  13660. case 2: this.moveBackward = false; break;
  13661. }
  13662. }
  13663. this.mouseDragOn = false;
  13664. };
  13665. this.onMouseMove = function ( event ) {
  13666. if ( this.domElement === document ) {
  13667. this.mouseX = event.pageX - this.viewHalfX;
  13668. this.mouseY = event.pageY - this.viewHalfY;
  13669. } else {
  13670. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  13671. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  13672. }
  13673. };
  13674. this.onKeyDown = function ( event ) {
  13675. switch( event.keyCode ) {
  13676. case 38: /*up*/
  13677. case 87: /*W*/ this.moveForward = true; break;
  13678. case 37: /*left*/
  13679. case 65: /*A*/ this.moveLeft = true; break;
  13680. case 40: /*down*/
  13681. case 83: /*S*/ this.moveBackward = true; break;
  13682. case 39: /*right*/
  13683. case 68: /*D*/ this.moveRight = true; break;
  13684. case 82: /*R*/ this.moveUp = true; break;
  13685. case 70: /*F*/ this.moveDown = true; break;
  13686. case 81: /*Q*/ this.freeze = !this.freeze; break;
  13687. }
  13688. };
  13689. this.onKeyUp = function ( event ) {
  13690. switch( event.keyCode ) {
  13691. case 38: /*up*/
  13692. case 87: /*W*/ this.moveForward = false; break;
  13693. case 37: /*left*/
  13694. case 65: /*A*/ this.moveLeft = false; break;
  13695. case 40: /*down*/
  13696. case 83: /*S*/ this.moveBackward = false; break;
  13697. case 39: /*right*/
  13698. case 68: /*D*/ this.moveRight = false; break;
  13699. case 82: /*R*/ this.moveUp = false; break;
  13700. case 70: /*F*/ this.moveDown = false; break;
  13701. }
  13702. };
  13703. this.update = function( delta ) {
  13704. var actualMoveSpeed = 0;
  13705. if ( this.freeze ) {
  13706. return;
  13707. } else {
  13708. if ( this.heightSpeed ) {
  13709. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  13710. var heightDelta = y - this.heightMin;
  13711. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  13712. } else {
  13713. this.autoSpeedFactor = 0.0;
  13714. }
  13715. actualMoveSpeed = delta * this.movementSpeed;
  13716. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  13717. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  13718. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  13719. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  13720. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  13721. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  13722. var actualLookSpeed = delta * this.lookSpeed;
  13723. if ( !this.activeLook ) {
  13724. actualLookSpeed = 0;
  13725. }
  13726. this.lon += this.mouseX * actualLookSpeed;
  13727. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed;
  13728. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13729. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  13730. this.theta = this.lon * Math.PI / 180;
  13731. var targetPosition = this.target,
  13732. position = this.object.position;
  13733. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13734. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  13735. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13736. }
  13737. var verticalLookRatio = 1;
  13738. if ( this.constrainVertical ) {
  13739. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  13740. }
  13741. this.lon += this.mouseX * actualLookSpeed;
  13742. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  13743. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13744. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  13745. this.theta = this.lon * Math.PI / 180;
  13746. if ( this.constrainVertical ) {
  13747. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  13748. }
  13749. var targetPosition = this.target,
  13750. position = this.object.position;
  13751. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13752. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  13753. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13754. this.object.lookAt( targetPosition );
  13755. };
  13756. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  13757. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  13758. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  13759. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  13760. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  13761. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  13762. function bind( scope, fn ) {
  13763. return function () {
  13764. fn.apply( scope, arguments );
  13765. };
  13766. };
  13767. };
  13768. /**
  13769. * @author alteredq / http://alteredqualia.com/
  13770. */
  13771. THREE.PathControls = function ( object, domElement ) {
  13772. this.object = object;
  13773. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13774. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  13775. // API
  13776. this.duration = 10 * 1000; // milliseconds
  13777. this.waypoints = [];
  13778. this.useConstantSpeed = true;
  13779. this.resamplingCoef = 50;
  13780. this.debugPath = new THREE.Object3D();
  13781. this.debugDummy = new THREE.Object3D();
  13782. this.animationParent = new THREE.Object3D();
  13783. this.lookSpeed = 0.005;
  13784. this.lookVertical = true;
  13785. this.lookHorizontal = true;
  13786. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  13787. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  13788. // internals
  13789. this.target = new THREE.Object3D();
  13790. this.mouseX = 0;
  13791. this.mouseY = 0;
  13792. this.lat = 0;
  13793. this.lon = 0;
  13794. this.phi = 0;
  13795. this.theta = 0;
  13796. if ( this.domElement === document ) {
  13797. this.viewHalfX = window.innerWidth / 2;
  13798. this.viewHalfY = window.innerHeight / 2;
  13799. } else {
  13800. this.viewHalfX = this.domElement.offsetWidth / 2;
  13801. this.viewHalfY = this.domElement.offsetHeight / 2;
  13802. this.domElement.setAttribute( 'tabindex', -1 );
  13803. }
  13804. var PI2 = Math.PI * 2,
  13805. PI180 = Math.PI / 180;
  13806. // methods
  13807. this.update = function ( delta ) {
  13808. var srcRange, dstRange;
  13809. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  13810. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  13811. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  13812. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  13813. this.phi = ( 90 - this.lat ) * PI180;
  13814. this.theta = this.lon * PI180;
  13815. this.phi = normalize_angle_rad( this.phi );
  13816. // constrain vertical look angle
  13817. srcRange = this.verticalAngleMap.srcRange;
  13818. dstRange = this.verticalAngleMap.dstRange;
  13819. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  13820. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  13821. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  13822. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  13823. // constrain horizontal look angle
  13824. srcRange = this.horizontalAngleMap.srcRange;
  13825. dstRange = this.horizontalAngleMap.dstRange;
  13826. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  13827. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  13828. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  13829. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  13830. var targetPosition = this.target.position,
  13831. position = this.object.position;
  13832. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  13833. targetPosition.y = 100 * Math.cos( this.phi );
  13834. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  13835. this.object.lookAt( this.target.position );
  13836. };
  13837. this.onMouseMove = function ( event ) {
  13838. if ( this.domElement === document ) {
  13839. this.mouseX = event.pageX - this.viewHalfX;
  13840. this.mouseY = event.pageY - this.viewHalfY;
  13841. } else {
  13842. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  13843. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  13844. }
  13845. };
  13846. // utils
  13847. function normalize_angle_rad( a ) {
  13848. var b = a % PI2;
  13849. return b >= 0 ? b : b + PI2;
  13850. };
  13851. function distance( a, b ) {
  13852. var dx = a[ 0 ] - b[ 0 ],
  13853. dy = a[ 1 ] - b[ 1 ],
  13854. dz = a[ 2 ] - b[ 2 ];
  13855. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  13856. };
  13857. function QuadraticEaseInOut ( k ) {
  13858. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  13859. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  13860. };
  13861. function bind( scope, fn ) {
  13862. return function () {
  13863. fn.apply( scope, arguments );
  13864. };
  13865. };
  13866. function initAnimationPath( parent, spline, name, duration ) {
  13867. var animationData = {
  13868. name: name,
  13869. fps: 0.6,
  13870. length: duration,
  13871. hierarchy: []
  13872. };
  13873. var i,
  13874. parentAnimation, childAnimation,
  13875. path = spline.getControlPointsArray(),
  13876. sl = spline.getLength(),
  13877. pl = path.length,
  13878. t = 0,
  13879. first = 0,
  13880. last = pl - 1;
  13881. parentAnimation = { parent: -1, keys: [] };
  13882. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  13883. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  13884. for ( i = 1; i < pl - 1; i++ ) {
  13885. // real distance (approximation via linear segments)
  13886. t = duration * sl.chunks[ i ] / sl.total;
  13887. // equal distance
  13888. //t = duration * ( i / pl );
  13889. // linear distance
  13890. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  13891. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  13892. }
  13893. animationData.hierarchy[ 0 ] = parentAnimation;
  13894. THREE.AnimationHandler.add( animationData );
  13895. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  13896. };
  13897. function createSplineGeometry( spline, n_sub ) {
  13898. var i, index, position,
  13899. geometry = new THREE.Geometry();
  13900. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  13901. index = i / ( spline.points.length * n_sub );
  13902. position = spline.getPoint( index );
  13903. geometry.vertices[ i ] = new THREE.Vertex( new THREE.Vector3( position.x, position.y, position.z ) );
  13904. }
  13905. return geometry;
  13906. };
  13907. function createPath( parent, spline ) {
  13908. var lineGeo = createSplineGeometry( spline, 10 ),
  13909. particleGeo = createSplineGeometry( spline, 10 ),
  13910. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  13911. lineObj = new THREE.Line( lineGeo, lineMat ),
  13912. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  13913. lineObj.scale.set( 1, 1, 1 );
  13914. parent.add( lineObj );
  13915. particleObj.scale.set( 1, 1, 1 );
  13916. parent.add( particleObj );
  13917. var waypoint,
  13918. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  13919. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  13920. for ( var i = 0; i < spline.points.length; i ++ ) {
  13921. waypoint = new THREE.Mesh( geo, mat );
  13922. waypoint.position.copy( spline.points[ i ] );
  13923. parent.add( waypoint );
  13924. }
  13925. };
  13926. this.init = function ( ) {
  13927. // constructor
  13928. this.spline = new THREE.Spline();
  13929. this.spline.initFromArray( this.waypoints );
  13930. if ( this.useConstantSpeed ) {
  13931. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  13932. }
  13933. if ( this.createDebugDummy ) {
  13934. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  13935. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  13936. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  13937. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  13938. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  13939. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  13940. dummyChild.position.set( 0, 10, 0 );
  13941. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  13942. this.animationParent.add( this.object );
  13943. this.animationParent.add( this.target );
  13944. this.animationParent.add( dummyChild );
  13945. } else {
  13946. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  13947. this.animationParent.add( this.target );
  13948. this.animationParent.add( this.object );
  13949. }
  13950. if ( this.createDebugPath ) {
  13951. createPath( this.debugPath, this.spline );
  13952. }
  13953. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  13954. };
  13955. };
  13956. THREE.PathControlsIdCounter = 0;
  13957. /**
  13958. * @author James Baicoianu / http://www.baicoianu.com/
  13959. */
  13960. THREE.FlyControls = function ( object, domElement ) {
  13961. this.object = object;
  13962. this.domElement = ( domElement !== undefined ) ? domElement : document;
  13963. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  13964. // API
  13965. this.movementSpeed = 1.0;
  13966. this.rollSpeed = 0.005;
  13967. this.dragToLook = false;
  13968. this.autoForward = false;
  13969. // disable default target object behavior
  13970. this.object.useQuaternion = true;
  13971. // internals
  13972. this.tmpQuaternion = new THREE.Quaternion();
  13973. this.mouseStatus = 0;
  13974. this.moveState = { up: 0, down: 0, left: 0, right: 0, forward: 0, back: 0, pitchUp: 0, pitchDown: 0, yawLeft: 0, yawRight: 0, rollLeft: 0, rollRight: 0 };
  13975. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  13976. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  13977. this.handleEvent = function ( event ) {
  13978. if ( typeof this[ event.type ] == 'function' ) {
  13979. this[ event.type ]( event );
  13980. }
  13981. };
  13982. this.keydown = function( event ) {
  13983. if ( event.altKey ) {
  13984. return;
  13985. }
  13986. switch( event.keyCode ) {
  13987. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  13988. case 87: /*W*/ this.moveState.forward = 1; break;
  13989. case 83: /*S*/ this.moveState.back = 1; break;
  13990. case 65: /*A*/ this.moveState.left = 1; break;
  13991. case 68: /*D*/ this.moveState.right = 1; break;
  13992. case 82: /*R*/ this.moveState.up = 1; break;
  13993. case 70: /*F*/ this.moveState.down = 1; break;
  13994. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  13995. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  13996. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  13997. case 39: /*right*/ this.moveState.yawRight = 1; break;
  13998. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  13999. case 69: /*E*/ this.moveState.rollRight = 1; break;
  14000. }
  14001. this.updateMovementVector();
  14002. this.updateRotationVector();
  14003. };
  14004. this.keyup = function( event ) {
  14005. switch( event.keyCode ) {
  14006. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  14007. case 87: /*W*/ this.moveState.forward = 0; break;
  14008. case 83: /*S*/ this.moveState.back = 0; break;
  14009. case 65: /*A*/ this.moveState.left = 0; break;
  14010. case 68: /*D*/ this.moveState.right = 0; break;
  14011. case 82: /*R*/ this.moveState.up = 0; break;
  14012. case 70: /*F*/ this.moveState.down = 0; break;
  14013. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  14014. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  14015. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  14016. case 39: /*right*/ this.moveState.yawRight = 0; break;
  14017. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  14018. case 69: /*E*/ this.moveState.rollRight = 0; break;
  14019. }
  14020. this.updateMovementVector();
  14021. this.updateRotationVector();
  14022. };
  14023. this.mousedown = function( event ) {
  14024. if ( this.domElement !== document ) {
  14025. this.domElement.focus();
  14026. }
  14027. event.preventDefault();
  14028. event.stopPropagation();
  14029. if ( this.dragToLook ) {
  14030. this.mouseStatus ++;
  14031. } else {
  14032. switch ( event.button ) {
  14033. case 0: this.object.moveForward = true; break;
  14034. case 2: this.object.moveBackward = true; break;
  14035. }
  14036. }
  14037. };
  14038. this.mousemove = function( event ) {
  14039. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  14040. var container = this.getContainerDimensions();
  14041. var halfWidth = container.size[ 0 ] / 2;
  14042. var halfHeight = container.size[ 1 ] / 2;
  14043. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  14044. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  14045. this.updateRotationVector();
  14046. }
  14047. };
  14048. this.mouseup = function( event ) {
  14049. event.preventDefault();
  14050. event.stopPropagation();
  14051. if ( this.dragToLook ) {
  14052. this.mouseStatus --;
  14053. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  14054. } else {
  14055. switch ( event.button ) {
  14056. case 0: this.moveForward = false; break;
  14057. case 2: this.moveBackward = false; break;
  14058. }
  14059. }
  14060. this.updateRotationVector();
  14061. };
  14062. this.update = function( delta ) {
  14063. var moveMult = delta * this.movementSpeed;
  14064. var rotMult = delta * this.rollSpeed;
  14065. this.object.translateX( this.moveVector.x * moveMult );
  14066. this.object.translateY( this.moveVector.y * moveMult );
  14067. this.object.translateZ( this.moveVector.z * moveMult );
  14068. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  14069. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  14070. this.object.matrix.setPosition( this.object.position );
  14071. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  14072. this.object.matrixWorldNeedsUpdate = true;
  14073. };
  14074. this.updateMovementVector = function() {
  14075. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  14076. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  14077. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  14078. this.moveVector.z = ( -forward + this.moveState.back );
  14079. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  14080. };
  14081. this.updateRotationVector = function() {
  14082. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  14083. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  14084. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  14085. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  14086. };
  14087. this.getContainerDimensions = function() {
  14088. if ( this.domElement != document ) {
  14089. return {
  14090. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  14091. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  14092. };
  14093. } else {
  14094. return {
  14095. size : [ window.innerWidth, window.innerHeight ],
  14096. offset : [ 0, 0 ]
  14097. };
  14098. }
  14099. };
  14100. function bind( scope, fn ) {
  14101. return function () {
  14102. fn.apply( scope, arguments );
  14103. };
  14104. };
  14105. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  14106. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  14107. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  14108. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  14109. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  14110. this.updateMovementVector();
  14111. this.updateRotationVector();
  14112. };
  14113. /**
  14114. * @author mikael emtinger / http://gomo.se/
  14115. * @author alteredq / http://alteredqualia.com/
  14116. */
  14117. THREE.RollControls = function ( object, domElement ) {
  14118. this.object = object;
  14119. this.domElement = ( domElement !== undefined ) ? domElement : document;
  14120. // API
  14121. this.mouseLook = true;
  14122. this.autoForward = false;
  14123. this.lookSpeed = 1;
  14124. this.movementSpeed = 1;
  14125. this.rollSpeed = 1;
  14126. this.constrainVertical = [ -0.9, 0.9 ];
  14127. // disable default target object behavior
  14128. this.object.matrixAutoUpdate = false;
  14129. // internals
  14130. this.forward = new THREE.Vector3( 0, 0, 1 );
  14131. this.roll = 0;
  14132. var xTemp = new THREE.Vector3();
  14133. var yTemp = new THREE.Vector3();
  14134. var zTemp = new THREE.Vector3();
  14135. var rollMatrix = new THREE.Matrix4();
  14136. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  14137. var mouseX = 0, mouseY = 0;
  14138. var windowHalfX = window.innerWidth / 2;
  14139. var windowHalfY = window.innerHeight / 2;
  14140. // custom update
  14141. this.update = function ( delta ) {
  14142. if ( this.mouseLook ) {
  14143. var actualLookSpeed = delta * this.lookSpeed;
  14144. this.rotateHorizontally( actualLookSpeed * mouseX );
  14145. this.rotateVertically( actualLookSpeed * mouseY );
  14146. }
  14147. var actualSpeed = delta * this.movementSpeed;
  14148. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  14149. this.object.translateZ( -actualSpeed * forwardOrAuto );
  14150. this.object.translateX( actualSpeed * sideSpeed );
  14151. this.object.translateY( actualSpeed * upSpeed );
  14152. if( doRoll ) {
  14153. this.roll += this.rollSpeed * delta * rollDirection;
  14154. }
  14155. // cap forward up / down
  14156. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  14157. this.forward.y = this.constrainVertical[ 1 ];
  14158. this.forward.normalize();
  14159. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  14160. this.forward.y = this.constrainVertical[ 0 ];
  14161. this.forward.normalize();
  14162. }
  14163. // construct unrolled camera matrix
  14164. zTemp.copy( this.forward );
  14165. yTemp.set( 0, 1, 0 );
  14166. xTemp.cross( yTemp, zTemp ).normalize();
  14167. yTemp.cross( zTemp, xTemp ).normalize();
  14168. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  14169. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  14170. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  14171. // calculate roll matrix
  14172. rollMatrix.identity();
  14173. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  14174. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  14175. // multiply camera with roll
  14176. this.object.matrix.multiplySelf( rollMatrix );
  14177. this.object.matrixWorldNeedsUpdate = true;
  14178. // set position
  14179. this.object.matrix.elements[12] = this.object.position.x;
  14180. this.object.matrix.elements[13] = this.object.position.y;
  14181. this.object.matrix.elements[14] = this.object.position.z;
  14182. };
  14183. this.translateX = function ( distance ) {
  14184. this.object.position.x += this.object.matrix.elements[0] * distance;
  14185. this.object.position.y += this.object.matrix.elements[1] * distance;
  14186. this.object.position.z += this.object.matrix.elements[2] * distance;
  14187. };
  14188. this.translateY = function ( distance ) {
  14189. this.object.position.x += this.object.matrix.elements[4] * distance;
  14190. this.object.position.y += this.object.matrix.elements[5] * distance;
  14191. this.object.position.z += this.object.matrix.elements[6] * distance;
  14192. };
  14193. this.translateZ = function ( distance ) {
  14194. this.object.position.x -= this.object.matrix.elements[8] * distance;
  14195. this.object.position.y -= this.object.matrix.elements[9] * distance;
  14196. this.object.position.z -= this.object.matrix.elements[10] * distance;
  14197. };
  14198. this.rotateHorizontally = function ( amount ) {
  14199. // please note that the amount is NOT degrees, but a scale value
  14200. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  14201. xTemp.multiplyScalar( amount );
  14202. this.forward.subSelf( xTemp );
  14203. this.forward.normalize();
  14204. };
  14205. this.rotateVertically = function ( amount ) {
  14206. // please note that the amount is NOT degrees, but a scale value
  14207. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  14208. yTemp.multiplyScalar( amount );
  14209. this.forward.addSelf( yTemp );
  14210. this.forward.normalize();
  14211. };
  14212. function onKeyDown( event ) {
  14213. switch( event.keyCode ) {
  14214. case 38: /*up*/
  14215. case 87: /*W*/ forwardSpeed = 1; break;
  14216. case 37: /*left*/
  14217. case 65: /*A*/ sideSpeed = -1; break;
  14218. case 40: /*down*/
  14219. case 83: /*S*/ forwardSpeed = -1; break;
  14220. case 39: /*right*/
  14221. case 68: /*D*/ sideSpeed = 1; break;
  14222. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  14223. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  14224. case 82: /*R*/ upSpeed = 1; break;
  14225. case 70: /*F*/ upSpeed = -1; break;
  14226. }
  14227. };
  14228. function onKeyUp( event ) {
  14229. switch( event.keyCode ) {
  14230. case 38: /*up*/
  14231. case 87: /*W*/ forwardSpeed = 0; break;
  14232. case 37: /*left*/
  14233. case 65: /*A*/ sideSpeed = 0; break;
  14234. case 40: /*down*/
  14235. case 83: /*S*/ forwardSpeed = 0; break;
  14236. case 39: /*right*/
  14237. case 68: /*D*/ sideSpeed = 0; break;
  14238. case 81: /*Q*/ doRoll = false; break;
  14239. case 69: /*E*/ doRoll = false; break;
  14240. case 82: /*R*/ upSpeed = 0; break;
  14241. case 70: /*F*/ upSpeed = 0; break;
  14242. }
  14243. };
  14244. function onMouseMove( event ) {
  14245. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  14246. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  14247. };
  14248. function onMouseDown ( event ) {
  14249. event.preventDefault();
  14250. event.stopPropagation();
  14251. switch ( event.button ) {
  14252. case 0: forwardSpeed = 1; break;
  14253. case 2: forwardSpeed = -1; break;
  14254. }
  14255. };
  14256. function onMouseUp ( event ) {
  14257. event.preventDefault();
  14258. event.stopPropagation();
  14259. switch ( event.button ) {
  14260. case 0: forwardSpeed = 0; break;
  14261. case 2: forwardSpeed = 0; break;
  14262. }
  14263. };
  14264. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  14265. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  14266. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  14267. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  14268. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  14269. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  14270. };
  14271. /**
  14272. * @author Eberhard Graether / http://egraether.com/
  14273. */
  14274. THREE.TrackballControls = function ( object, domElement ) {
  14275. THREE.EventTarget.call( this );
  14276. var _this = this,
  14277. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  14278. this.object = object;
  14279. this.domElement = ( domElement !== undefined ) ? domElement : document;
  14280. // API
  14281. this.enabled = true;
  14282. this.screen = { width: window.innerWidth, height: window.innerHeight, offsetLeft: 0, offsetTop: 0 };
  14283. this.radius = ( this.screen.width + this.screen.height ) / 4;
  14284. this.rotateSpeed = 1.0;
  14285. this.zoomSpeed = 1.2;
  14286. this.panSpeed = 0.3;
  14287. this.noRotate = false;
  14288. this.noZoom = false;
  14289. this.noPan = false;
  14290. this.staticMoving = false;
  14291. this.dynamicDampingFactor = 0.2;
  14292. this.minDistance = 0;
  14293. this.maxDistance = Infinity;
  14294. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  14295. // internals
  14296. this.target = new THREE.Vector3();
  14297. var lastPosition = new THREE.Vector3();
  14298. var _keyPressed = false,
  14299. _state = STATE.NONE,
  14300. _eye = new THREE.Vector3(),
  14301. _rotateStart = new THREE.Vector3(),
  14302. _rotateEnd = new THREE.Vector3(),
  14303. _zoomStart = new THREE.Vector2(),
  14304. _zoomEnd = new THREE.Vector2(),
  14305. _panStart = new THREE.Vector2(),
  14306. _panEnd = new THREE.Vector2();
  14307. // events
  14308. var changeEvent = { type: 'change' };
  14309. // methods
  14310. this.handleEvent = function ( event ) {
  14311. if ( typeof this[ event.type ] == 'function' ) {
  14312. this[ event.type ]( event );
  14313. }
  14314. };
  14315. this.getMouseOnScreen = function ( clientX, clientY ) {
  14316. return new THREE.Vector2(
  14317. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  14318. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  14319. );
  14320. };
  14321. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  14322. var mouseOnBall = new THREE.Vector3(
  14323. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  14324. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  14325. 0.0
  14326. );
  14327. var length = mouseOnBall.length();
  14328. if ( length > 1.0 ) {
  14329. mouseOnBall.normalize();
  14330. } else {
  14331. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  14332. }
  14333. _eye.copy( _this.object.position ).subSelf( _this.target );
  14334. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  14335. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  14336. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  14337. return projection;
  14338. };
  14339. this.rotateCamera = function () {
  14340. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  14341. if ( angle ) {
  14342. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  14343. quaternion = new THREE.Quaternion();
  14344. angle *= _this.rotateSpeed;
  14345. quaternion.setFromAxisAngle( axis, -angle );
  14346. quaternion.multiplyVector3( _eye );
  14347. quaternion.multiplyVector3( _this.object.up );
  14348. quaternion.multiplyVector3( _rotateEnd );
  14349. if ( _this.staticMoving ) {
  14350. _rotateStart = _rotateEnd;
  14351. } else {
  14352. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  14353. quaternion.multiplyVector3( _rotateStart );
  14354. }
  14355. }
  14356. };
  14357. this.zoomCamera = function () {
  14358. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  14359. if ( factor !== 1.0 && factor > 0.0 ) {
  14360. _eye.multiplyScalar( factor );
  14361. if ( _this.staticMoving ) {
  14362. _zoomStart = _zoomEnd;
  14363. } else {
  14364. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  14365. }
  14366. }
  14367. };
  14368. this.panCamera = function () {
  14369. var mouseChange = _panEnd.clone().subSelf( _panStart );
  14370. if ( mouseChange.lengthSq() ) {
  14371. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  14372. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  14373. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  14374. _this.object.position.addSelf( pan );
  14375. _this.target.addSelf( pan );
  14376. if ( _this.staticMoving ) {
  14377. _panStart = _panEnd;
  14378. } else {
  14379. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  14380. }
  14381. }
  14382. };
  14383. this.checkDistances = function () {
  14384. if ( !_this.noZoom || !_this.noPan ) {
  14385. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  14386. _this.object.position.setLength( _this.maxDistance );
  14387. }
  14388. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  14389. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  14390. }
  14391. }
  14392. };
  14393. this.update = function () {
  14394. _eye.copy( _this.object.position ).subSelf( _this.target );
  14395. if ( !_this.noRotate ) {
  14396. _this.rotateCamera();
  14397. }
  14398. if ( !_this.noZoom ) {
  14399. _this.zoomCamera();
  14400. }
  14401. if ( !_this.noPan ) {
  14402. _this.panCamera();
  14403. }
  14404. _this.object.position.add( _this.target, _eye );
  14405. _this.checkDistances();
  14406. _this.object.lookAt( _this.target );
  14407. if ( lastPosition.distanceTo( _this.object.position ) > 0 ) {
  14408. _this.dispatchEvent( changeEvent );
  14409. lastPosition.copy( _this.object.position );
  14410. }
  14411. };
  14412. // listeners
  14413. function keydown( event ) {
  14414. if ( ! _this.enabled ) return;
  14415. if ( _state !== STATE.NONE ) {
  14416. return;
  14417. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  14418. _state = STATE.ROTATE;
  14419. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  14420. _state = STATE.ZOOM;
  14421. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  14422. _state = STATE.PAN;
  14423. }
  14424. if ( _state !== STATE.NONE ) {
  14425. _keyPressed = true;
  14426. }
  14427. };
  14428. function keyup( event ) {
  14429. if ( ! _this.enabled ) return;
  14430. if ( _state !== STATE.NONE ) {
  14431. _state = STATE.NONE;
  14432. }
  14433. };
  14434. function mousedown( event ) {
  14435. if ( ! _this.enabled ) return;
  14436. event.preventDefault();
  14437. event.stopPropagation();
  14438. if ( _state === STATE.NONE ) {
  14439. _state = event.button;
  14440. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  14441. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14442. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  14443. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14444. } else if ( !this.noPan ) {
  14445. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14446. }
  14447. }
  14448. };
  14449. function mousemove( event ) {
  14450. if ( ! _this.enabled ) return;
  14451. if ( _keyPressed ) {
  14452. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14453. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14454. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14455. _keyPressed = false;
  14456. }
  14457. if ( _state === STATE.NONE ) {
  14458. return;
  14459. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  14460. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  14461. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  14462. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14463. } else if ( _state === STATE.PAN && !_this.noPan ) {
  14464. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  14465. }
  14466. };
  14467. function mouseup( event ) {
  14468. if ( ! _this.enabled ) return;
  14469. event.preventDefault();
  14470. event.stopPropagation();
  14471. _state = STATE.NONE;
  14472. };
  14473. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  14474. this.domElement.addEventListener( 'mousemove', mousemove, false );
  14475. this.domElement.addEventListener( 'mousedown', mousedown, false );
  14476. this.domElement.addEventListener( 'mouseup', mouseup, false );
  14477. window.addEventListener( 'keydown', keydown, false );
  14478. window.addEventListener( 'keyup', keyup, false );
  14479. };
  14480. /**
  14481. * @author mr.doob / http://mrdoob.com/
  14482. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  14483. */
  14484. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  14485. THREE.Geometry.call( this );
  14486. var scope = this,
  14487. width_half = width / 2,
  14488. height_half = height / 2,
  14489. depth_half = depth / 2;
  14490. var mpx, mpy, mpz, mnx, mny, mnz;
  14491. if ( materials !== undefined ) {
  14492. if ( materials instanceof Array ) {
  14493. this.materials = materials;
  14494. } else {
  14495. this.materials = [];
  14496. for ( var i = 0; i < 6; i ++ ) {
  14497. this.materials.push( materials );
  14498. }
  14499. }
  14500. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  14501. } else {
  14502. this.materials = [];
  14503. }
  14504. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  14505. if ( sides != undefined ) {
  14506. for ( var s in sides ) {
  14507. if ( this.sides[ s ] !== undefined ) {
  14508. this.sides[ s ] = sides[ s ];
  14509. }
  14510. }
  14511. }
  14512. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  14513. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  14514. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  14515. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  14516. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  14517. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  14518. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  14519. var w, ix, iy,
  14520. gridX = segmentsWidth || 1,
  14521. gridY = segmentsHeight || 1,
  14522. width_half = width / 2,
  14523. height_half = height / 2,
  14524. offset = scope.vertices.length;
  14525. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  14526. w = 'z';
  14527. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  14528. w = 'y';
  14529. gridY = segmentsDepth || 1;
  14530. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  14531. w = 'x';
  14532. gridX = segmentsDepth || 1;
  14533. }
  14534. var gridX1 = gridX + 1,
  14535. gridY1 = gridY + 1,
  14536. segment_width = width / gridX,
  14537. segment_height = height / gridY,
  14538. normal = new THREE.Vector3();
  14539. normal[ w ] = depth > 0 ? 1 : - 1;
  14540. for ( iy = 0; iy < gridY1; iy ++ ) {
  14541. for ( ix = 0; ix < gridX1; ix ++ ) {
  14542. var vector = new THREE.Vector3();
  14543. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  14544. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  14545. vector[ w ] = depth;
  14546. scope.vertices.push( new THREE.Vertex( vector ) );
  14547. }
  14548. }
  14549. for ( iy = 0; iy < gridY; iy++ ) {
  14550. for ( ix = 0; ix < gridX; ix++ ) {
  14551. var a = ix + gridX1 * iy;
  14552. var b = ix + gridX1 * ( iy + 1 );
  14553. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  14554. var d = ( ix + 1 ) + gridX1 * iy;
  14555. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  14556. face.normal.copy( normal );
  14557. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  14558. face.materialIndex = material;
  14559. scope.faces.push( face );
  14560. scope.faceVertexUvs[ 0 ].push( [
  14561. new THREE.UV( ix / gridX, iy / gridY ),
  14562. new THREE.UV( ix / gridX, ( iy + 1 ) / gridY ),
  14563. new THREE.UV( ( ix + 1 ) / gridX, ( iy + 1 ) / gridY ),
  14564. new THREE.UV( ( ix + 1 ) / gridX, iy / gridY )
  14565. ] );
  14566. }
  14567. }
  14568. }
  14569. this.computeCentroids();
  14570. this.mergeVertices();
  14571. };
  14572. THREE.CubeGeometry.prototype = new THREE.Geometry();
  14573. THREE.CubeGeometry.prototype.constructor = THREE.CubeGeometry;
  14574. /**
  14575. * @author mr.doob / http://mrdoob.com/
  14576. */
  14577. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  14578. THREE.Geometry.call( this );
  14579. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  14580. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  14581. height = height !== undefined ? height : 100;
  14582. var heightHalf = height / 2;
  14583. var segmentsX = segmentsRadius || 8;
  14584. var segmentsY = segmentsHeight || 1;
  14585. var x, y, vertices = [], uvs = [];
  14586. for ( y = 0; y <= segmentsY; y ++ ) {
  14587. var verticesRow = [];
  14588. var uvsRow = [];
  14589. var v = y / segmentsY;
  14590. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  14591. for ( x = 0; x <= segmentsX; x ++ ) {
  14592. var u = x / segmentsX;
  14593. var xpos = radius * Math.sin( u * Math.PI * 2 );
  14594. var ypos = - v * height + heightHalf;
  14595. var zpos = radius * Math.cos( u * Math.PI * 2 );
  14596. this.vertices.push( new THREE.Vertex( new THREE.Vector3( xpos, ypos, zpos ) ) );
  14597. verticesRow.push( this.vertices.length - 1 );
  14598. uvsRow.push( new THREE.UV( u, v ) );
  14599. }
  14600. vertices.push( verticesRow );
  14601. uvs.push( uvsRow );
  14602. }
  14603. for ( y = 0; y < segmentsY; y ++ ) {
  14604. for ( x = 0; x < segmentsX; x ++ ) {
  14605. var v1 = vertices[ y ][ x ];
  14606. var v2 = vertices[ y + 1 ][ x ];
  14607. var v3 = vertices[ y + 1 ][ x + 1 ];
  14608. var v4 = vertices[ y ][ x + 1 ];
  14609. // FIXME: These normals aren't right for cones.
  14610. var n1 = this.vertices[ v1 ].position.clone().setY( 0 ).normalize();
  14611. var n2 = this.vertices[ v2 ].position.clone().setY( 0 ).normalize();
  14612. var n3 = this.vertices[ v3 ].position.clone().setY( 0 ).normalize();
  14613. var n4 = this.vertices[ v4 ].position.clone().setY( 0 ).normalize();
  14614. var uv1 = uvs[ y ][ x ].clone();
  14615. var uv2 = uvs[ y + 1 ][ x ].clone();
  14616. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  14617. var uv4 = uvs[ y ][ x + 1 ].clone();
  14618. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  14619. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  14620. }
  14621. }
  14622. // top cap
  14623. if ( !openEnded && radiusTop > 0 ) {
  14624. this.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, heightHalf, 0 ) ) );
  14625. for ( x = 0; x < segmentsX; x ++ ) {
  14626. var v1 = vertices[ 0 ][ x ];
  14627. var v2 = vertices[ 0 ][ x + 1 ];
  14628. var v3 = this.vertices.length - 1;
  14629. var n1 = new THREE.Vector3( 0, 1, 0 );
  14630. var n2 = new THREE.Vector3( 0, 1, 0 );
  14631. var n3 = new THREE.Vector3( 0, 1, 0 );
  14632. var uv1 = uvs[ 0 ][ x ].clone();
  14633. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  14634. var uv3 = new THREE.UV( uv2.u, 0 );
  14635. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  14636. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  14637. }
  14638. }
  14639. // bottom cap
  14640. if ( !openEnded && radiusBottom > 0 ) {
  14641. this.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, - heightHalf, 0 ) ) );
  14642. for ( x = 0; x < segmentsX; x ++ ) {
  14643. var v1 = vertices[ y ][ x + 1 ];
  14644. var v2 = vertices[ y ][ x ];
  14645. var v3 = this.vertices.length - 1;
  14646. var n1 = new THREE.Vector3( 0, - 1, 0 );
  14647. var n2 = new THREE.Vector3( 0, - 1, 0 );
  14648. var n3 = new THREE.Vector3( 0, - 1, 0 );
  14649. var uv1 = uvs[ y ][ x + 1 ].clone();
  14650. var uv2 = uvs[ y ][ x ].clone();
  14651. var uv3 = new THREE.UV( uv2.u, 1 );
  14652. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  14653. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  14654. }
  14655. }
  14656. this.computeCentroids();
  14657. this.computeFaceNormals();
  14658. }
  14659. THREE.CylinderGeometry.prototype = new THREE.Geometry();
  14660. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  14661. /**
  14662. * @author zz85 / http://www.lab4games.net/zz85/blog
  14663. *
  14664. * Creates extruded geometry from a path shape.
  14665. *
  14666. * parameters = {
  14667. *
  14668. * size: <float>, // size of the text
  14669. * height: <float>, // thickness to extrude text
  14670. * curveSegments: <int>, // number of points on the curves
  14671. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  14672. amount: <int>, // Amount
  14673. *
  14674. * bevelEnabled: <bool>, // turn on bevel
  14675. * bevelThickness: <float>, // how deep into text bevel goes
  14676. * bevelSize: <float>, // how far from text outline is bevel
  14677. * bevelSegments: <int>, // number of bevel layers
  14678. *
  14679. * extrudePath: <THREE.CurvePath> // 2d/3d spline path to extrude shape orthogonality to
  14680. * bendPath: <THREE.CurvePath> // 2d path for bend the shape around x/y plane
  14681. *
  14682. * material: <int> // material index for front and back faces
  14683. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  14684. *
  14685. * }
  14686. **/
  14687. THREE.ExtrudeGeometry = function( shapes, options ) {
  14688. if ( typeof( shapes ) === "undefined" ) {
  14689. shapes = [];
  14690. return;
  14691. }
  14692. THREE.Geometry.call( this );
  14693. shapes = shapes instanceof Array ? shapes : [ shapes ];
  14694. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  14695. this.addShapeList( shapes, options );
  14696. this.computeCentroids();
  14697. this.computeFaceNormals();
  14698. // can't really use automatic vertex normals
  14699. // as then front and back sides get smoothed too
  14700. // should do separate smoothing just for sides
  14701. //this.computeVertexNormals();
  14702. //console.log( "took", ( Date.now() - startTime ) );
  14703. };
  14704. THREE.ExtrudeGeometry.prototype = new THREE.Geometry();
  14705. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  14706. THREE.ExtrudeGeometry.prototype.addShapeList = function(shapes, options) {
  14707. var sl = shapes.length;
  14708. for ( var s = 0; s < sl; s ++ ) {
  14709. var shape = shapes[ s ];
  14710. this.addShape( shape, options );
  14711. }
  14712. };
  14713. THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
  14714. var amount = options.amount !== undefined ? options.amount : 100;
  14715. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  14716. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  14717. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  14718. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  14719. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  14720. var steps = options.steps !== undefined ? options.steps : 1;
  14721. var bendPath = options.bendPath;
  14722. var extrudePath = options.extrudePath;
  14723. var extrudePts, extrudeByPath = false;
  14724. var material = options.material;
  14725. var extrudeMaterial = options.extrudeMaterial;
  14726. var shapebb = this.shapebb;
  14727. //shapebb = shape.getBoundingBox();
  14728. var splineTube, binormal, normal, position2;
  14729. if ( extrudePath ) {
  14730. extrudePts = extrudePath.getSpacedPoints( steps );
  14731. extrudeByPath = true;
  14732. bevelEnabled = false; // bevels not supported for path extrusion
  14733. // SETUP TNB variables
  14734. // Reuse TNB from TubeGeomtry for now.
  14735. // TODO1 - have a .isClosed in spline?
  14736. // TODO2 - have have TNBs calculation refactored from TubeGeometry?
  14737. splineTube = new THREE.TubeGeometry(extrudePath, steps, 1, 1, false, false);
  14738. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  14739. binormal = new THREE.Vector3();
  14740. normal = new THREE.Vector3();
  14741. position2 = new THREE.Vector3();
  14742. }
  14743. // Safeguards if bevels are not enabled
  14744. if ( ! bevelEnabled ) {
  14745. bevelSegments = 0;
  14746. bevelThickness = 0;
  14747. bevelSize = 0;
  14748. }
  14749. // Variables initalization
  14750. var ahole, h, hl; // looping of holes
  14751. var scope = this;
  14752. var bevelPoints = [];
  14753. var shapesOffset = this.vertices.length;
  14754. if ( bendPath ) {
  14755. shape.addWrapPath( bendPath );
  14756. }
  14757. var shapePoints = shape.extractPoints();
  14758. var vertices = shapePoints.shape;
  14759. var holes = shapePoints.holes;
  14760. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  14761. if ( reverse ) {
  14762. vertices = vertices.reverse();
  14763. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  14764. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14765. ahole = holes[ h ];
  14766. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  14767. holes[ h ] = ahole.reverse();
  14768. }
  14769. }
  14770. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  14771. }
  14772. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  14773. //var faces = THREE.Shape.Utils.triangulate2( vertices, holes );
  14774. // Would it be better to move points after triangulation?
  14775. // shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
  14776. // vertices = shapePoints.shape;
  14777. // holes = shapePoints.holes;
  14778. //console.log(faces);
  14779. ////
  14780. /// Handle Vertices
  14781. ////
  14782. var contour = vertices; // vertices has all points but contour has only points of circumference
  14783. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14784. ahole = holes[ h ];
  14785. vertices = vertices.concat( ahole );
  14786. }
  14787. function scalePt2 ( pt, vec, size ) {
  14788. if ( !vec ) console.log( "die" );
  14789. return vec.clone().multiplyScalar( size ).addSelf( pt );
  14790. }
  14791. var b, bs, t, z,
  14792. vert, vlen = vertices.length,
  14793. face, flen = faces.length,
  14794. cont, clen = contour.length;
  14795. //------
  14796. // Find directions for point movement
  14797. //
  14798. var RAD_TO_DEGREES = 180 / Math.PI;
  14799. function getBevelVec( pt_i, pt_j, pt_k ) {
  14800. // Algorithm 2
  14801. return getBevelVec2( pt_i, pt_j, pt_k );
  14802. }
  14803. function getBevelVec1( pt_i, pt_j, pt_k ) {
  14804. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  14805. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  14806. if ( anglea > angleb ) {
  14807. angleb += Math.PI * 2;
  14808. }
  14809. var anglec = ( anglea + angleb ) / 2;
  14810. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  14811. var x = - Math.cos( anglec );
  14812. var y = - Math.sin( anglec );
  14813. var vec = new THREE.Vector2( x, y ); //.normalize();
  14814. return vec;
  14815. }
  14816. function getBevelVec2( pt_i, pt_j, pt_k ) {
  14817. var a = THREE.ExtrudeGeometry.__v1,
  14818. b = THREE.ExtrudeGeometry.__v2,
  14819. v_hat = THREE.ExtrudeGeometry.__v3,
  14820. w_hat = THREE.ExtrudeGeometry.__v4,
  14821. p = THREE.ExtrudeGeometry.__v5,
  14822. q = THREE.ExtrudeGeometry.__v6,
  14823. v, w,
  14824. v_dot_w_hat, q_sub_p_dot_w_hat,
  14825. s, intersection;
  14826. // good reading for line-line intersection
  14827. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  14828. // define a as vector j->i
  14829. // define b as vectot k->i
  14830. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  14831. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  14832. // get unit vectors
  14833. v = a.normalize();
  14834. w = b.normalize();
  14835. // normals from pt i
  14836. v_hat.set( -v.y, v.x );
  14837. w_hat.set( w.y, -w.x );
  14838. // pts from i
  14839. p.copy( pt_i ).addSelf( v_hat );
  14840. q.copy( pt_i ).addSelf( w_hat );
  14841. if ( p.equals( q ) ) {
  14842. //console.log("Warning: lines are straight");
  14843. return w_hat.clone();
  14844. }
  14845. // Points from j, k. helps prevents points cross overover most of the time
  14846. p.copy( pt_j ).addSelf( v_hat );
  14847. q.copy( pt_k ).addSelf( w_hat );
  14848. v_dot_w_hat = v.dot( w_hat );
  14849. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  14850. // We should not reach these conditions
  14851. if ( v_dot_w_hat === 0 ) {
  14852. console.log( "Either infinite or no solutions!" );
  14853. if ( q_sub_p_dot_w_hat === 0 ) {
  14854. console.log( "Its finite solutions." );
  14855. } else {
  14856. console.log( "Too bad, no solutions." );
  14857. }
  14858. }
  14859. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  14860. if ( s < 0 ) {
  14861. // in case of emergecy, revert to algorithm 1.
  14862. return getBevelVec1( pt_i, pt_j, pt_k );
  14863. }
  14864. intersection = v.multiplyScalar( s ).addSelf( p );
  14865. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  14866. }
  14867. var contourMovements = [];
  14868. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14869. if ( j === il ) j = 0;
  14870. if ( k === il ) k = 0;
  14871. // (j)---(i)---(k)
  14872. // console.log('i,j,k', i, j , k)
  14873. var pt_i = contour[ i ];
  14874. var pt_j = contour[ j ];
  14875. var pt_k = contour[ k ];
  14876. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  14877. }
  14878. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  14879. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14880. ahole = holes[ h ];
  14881. oneHoleMovements = [];
  14882. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  14883. if ( j === il ) j = 0;
  14884. if ( k === il ) k = 0;
  14885. // (j)---(i)---(k)
  14886. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  14887. }
  14888. holesMovements.push( oneHoleMovements );
  14889. verticesMovements = verticesMovements.concat( oneHoleMovements );
  14890. }
  14891. // Loop bevelSegments, 1 for the front, 1 for the back
  14892. for ( b = 0; b < bevelSegments; b ++ ) {
  14893. //for ( b = bevelSegments; b > 0; b -- ) {
  14894. t = b / bevelSegments;
  14895. z = bevelThickness * ( 1 - t );
  14896. //z = bevelThickness * t;
  14897. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  14898. //bs = bevelSize * t ; // linear
  14899. // contract shape
  14900. for ( i = 0, il = contour.length; i < il; i ++ ) {
  14901. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14902. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  14903. v( vert.x, vert.y, - z );
  14904. }
  14905. // expand holes
  14906. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  14907. ahole = holes[ h ];
  14908. oneHoleMovements = holesMovements[ h ];
  14909. for ( i = 0, il = ahole.length; i < il; i++ ) {
  14910. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14911. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  14912. v( vert.x, vert.y, -z );
  14913. }
  14914. }
  14915. }
  14916. bs = bevelSize;
  14917. // Back facing vertices
  14918. for ( i = 0; i < vlen; i ++ ) {
  14919. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14920. if ( !extrudeByPath ) {
  14921. v( vert.x, vert.y, 0 );
  14922. } else {
  14923. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  14924. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  14925. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  14926. position2.copy(extrudePts[0]).addSelf(normal).addSelf(binormal);
  14927. v(position2.x, position2.y, position2.z);
  14928. }
  14929. }
  14930. // Add stepped vertices...
  14931. // Including front facing vertices
  14932. var s;
  14933. for ( s = 1; s <= steps; s ++ ) {
  14934. for ( i = 0; i < vlen; i ++ ) {
  14935. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  14936. if ( !extrudeByPath ) {
  14937. v( vert.x, vert.y, amount / steps * s );
  14938. } else {
  14939. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  14940. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  14941. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  14942. position2.copy(extrudePts[s]).addSelf(normal).addSelf(binormal);
  14943. v(position2.x, position2.y, position2.z );
  14944. }
  14945. }
  14946. }
  14947. // Add bevel segments planes
  14948. //for ( b = 1; b <= bevelSegments; b ++ ) {
  14949. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  14950. t = b / bevelSegments;
  14951. z = bevelThickness * ( 1 - t );
  14952. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  14953. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  14954. // contract shape
  14955. for ( i = 0, il = contour.length; i < il; i ++ ) {
  14956. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  14957. v( vert.x, vert.y, amount + z );
  14958. }
  14959. // expand holes
  14960. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  14961. ahole = holes[ h ];
  14962. oneHoleMovements = holesMovements[ h ];
  14963. for ( i = 0, il = ahole.length; i < il; i++ ) {
  14964. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  14965. if ( !extrudeByPath ) {
  14966. v( vert.x, vert.y, amount + z );
  14967. } else {
  14968. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  14969. }
  14970. }
  14971. }
  14972. }
  14973. // set UV generator
  14974. var uvgen = THREE.ExtrudeGeometry.WorldUVGenerator;
  14975. ////
  14976. /// Handle Faces
  14977. ////
  14978. // Top and bottom faces
  14979. buildLidFaces();
  14980. // Sides faces
  14981. buildSideFaces();
  14982. ///// Internal functions
  14983. function buildLidFaces() {
  14984. if ( bevelEnabled ) {
  14985. var layer = 0 ; // steps + 1
  14986. var offset = vlen * layer;
  14987. // Bottom faces
  14988. for ( i = 0; i < flen; i ++ ) {
  14989. face = faces[ i ];
  14990. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  14991. }
  14992. layer = steps + bevelSegments * 2;
  14993. offset = vlen * layer;
  14994. // Top faces
  14995. for ( i = 0; i < flen; i ++ ) {
  14996. face = faces[ i ];
  14997. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  14998. }
  14999. } else {
  15000. // Bottom faces
  15001. for ( i = 0; i < flen; i++ ) {
  15002. face = faces[ i ];
  15003. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  15004. }
  15005. // Top faces
  15006. for ( i = 0; i < flen; i ++ ) {
  15007. face = faces[ i ];
  15008. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  15009. }
  15010. }
  15011. }
  15012. // Create faces for the z-sides of the shape
  15013. function buildSideFaces() {
  15014. var layeroffset = 0;
  15015. sidewalls( contour, layeroffset );
  15016. layeroffset += contour.length;
  15017. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  15018. ahole = holes[ h ];
  15019. sidewalls( ahole, layeroffset );
  15020. //, true
  15021. layeroffset += ahole.length;
  15022. }
  15023. }
  15024. function sidewalls( contour, layeroffset ) {
  15025. var j, k;
  15026. i = contour.length;
  15027. while ( --i >= 0 ) {
  15028. j = i;
  15029. k = i - 1;
  15030. if ( k < 0 ) k = contour.length - 1;
  15031. //console.log('b', i,j, i-1, k,vertices.length);
  15032. var s = 0, sl = steps + bevelSegments * 2;
  15033. for ( s = 0; s < sl; s ++ ) {
  15034. var slen1 = vlen * s;
  15035. var slen2 = vlen * ( s + 1 );
  15036. var a = layeroffset + j + slen1,
  15037. b = layeroffset + k + slen1,
  15038. c = layeroffset + k + slen2,
  15039. d = layeroffset + j + slen2;
  15040. f4( a, b, c, d, contour, s, sl );
  15041. }
  15042. }
  15043. }
  15044. function v( x, y, z ) {
  15045. scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  15046. }
  15047. function f3( a, b, c, isBottom ) {
  15048. a += shapesOffset;
  15049. b += shapesOffset;
  15050. c += shapesOffset;
  15051. // normal, color, material
  15052. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  15053. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c)
  15054. : uvgen.generateTopUV( scope, shape, options, a, b, c);
  15055. scope.faceVertexUvs[ 0 ].push(uvs);
  15056. }
  15057. function f4( a, b, c, d, wallContour, stepIndex, stepsLength ) {
  15058. a += shapesOffset;
  15059. b += shapesOffset;
  15060. c += shapesOffset;
  15061. d += shapesOffset;
  15062. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  15063. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d, stepIndex, stepsLength);
  15064. scope.faceVertexUvs[ 0 ].push(uvs);
  15065. }
  15066. };
  15067. THREE.ExtrudeGeometry.WorldUVGenerator = {
  15068. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  15069. var ax = geometry.vertices[ indexA ].position.x,
  15070. ay = geometry.vertices[ indexA ].position.y,
  15071. bx = geometry.vertices[ indexB ].position.x,
  15072. by = geometry.vertices[ indexB ].position.y,
  15073. cx = geometry.vertices[ indexC ].position.x,
  15074. cy = geometry.vertices[ indexC ].position.y;
  15075. return [
  15076. new THREE.UV( ax, 1 - ay ),
  15077. new THREE.UV( bx, 1 - by ),
  15078. new THREE.UV( cx, 1 - cy )
  15079. ];
  15080. },
  15081. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  15082. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  15083. },
  15084. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  15085. indexA, indexB, indexC, indexD, stepIndex, stepsLength) {
  15086. var ax = geometry.vertices[ indexA ].position.x,
  15087. ay = geometry.vertices[ indexA ].position.y,
  15088. az = geometry.vertices[ indexA ].position.z,
  15089. bx = geometry.vertices[ indexB ].position.x,
  15090. by = geometry.vertices[ indexB ].position.y,
  15091. bz = geometry.vertices[ indexB ].position.z,
  15092. cx = geometry.vertices[ indexC ].position.x,
  15093. cy = geometry.vertices[ indexC ].position.y,
  15094. cz = geometry.vertices[ indexC ].position.z,
  15095. dx = geometry.vertices[ indexD ].position.x,
  15096. dy = geometry.vertices[ indexD ].position.y,
  15097. dz = geometry.vertices[ indexD ].position.z;
  15098. if ( Math.abs( ay - by ) < 0.01 ) {
  15099. return [
  15100. new THREE.UV( ax, az ),
  15101. new THREE.UV( bx, bz ),
  15102. new THREE.UV( cx, cz ),
  15103. new THREE.UV( dx, dz )
  15104. ];
  15105. } else {
  15106. return [
  15107. new THREE.UV( ay, az ),
  15108. new THREE.UV( by, bz ),
  15109. new THREE.UV( cy, cz ),
  15110. new THREE.UV( dy, dz )
  15111. ];
  15112. }
  15113. }
  15114. };
  15115. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  15116. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  15117. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  15118. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  15119. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  15120. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  15121. /**
  15122. * @author astrodud / http://astrodud.isgreat.org/
  15123. */
  15124. THREE.LatheGeometry = function ( points, steps, angle ) {
  15125. THREE.Geometry.call( this );
  15126. this.steps = steps || 12;
  15127. this.angle = angle || 2 * Math.PI;
  15128. var stepSize = this.angle / this.steps,
  15129. newV = [], oldInds = [], newInds = [], startInds = [],
  15130. matrix = new THREE.Matrix4().makeRotationZ( stepSize );
  15131. for ( var j = 0; j < points.length; j ++ ) {
  15132. this.vertices.push( new THREE.Vertex( points[ j ] ) );
  15133. newV[ j ] = points[ j ].clone();
  15134. oldInds[ j ] = this.vertices.length - 1;
  15135. }
  15136. for ( var r = 0; r <= this.angle + 0.001; r += stepSize ) { // need the +0.001 for it go up to angle
  15137. for ( var j = 0; j < newV.length; j ++ ) {
  15138. if ( r < this.angle ) {
  15139. newV[ j ] = matrix.multiplyVector3( newV[ j ].clone() );
  15140. this.vertices.push( new THREE.Vertex( newV[ j ] ) );
  15141. newInds[ j ] = this.vertices.length - 1;
  15142. } else {
  15143. newInds = startInds; // wrap it up!
  15144. }
  15145. }
  15146. if ( r == 0 ) startInds = oldInds;
  15147. for ( var j = 0; j < oldInds.length - 1; j ++ ) {
  15148. this.faces.push( new THREE.Face4( newInds[ j ], newInds[ j + 1 ], oldInds[ j + 1 ], oldInds[ j ] ) );
  15149. this.faceVertexUvs[ 0 ].push( [
  15150. new THREE.UV( 1 - r / this.angle, j / points.length ),
  15151. new THREE.UV( 1 - r / this.angle, ( j + 1 ) / points.length ),
  15152. new THREE.UV( 1 - ( r - stepSize ) / this.angle, ( j + 1 ) / points.length ),
  15153. new THREE.UV( 1 - ( r - stepSize ) / this.angle, j / points.length )
  15154. ] );
  15155. }
  15156. oldInds = newInds;
  15157. newInds = [];
  15158. }
  15159. this.computeCentroids();
  15160. this.computeFaceNormals();
  15161. this.computeVertexNormals();
  15162. };
  15163. THREE.LatheGeometry.prototype = new THREE.Geometry();
  15164. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  15165. /**
  15166. * @author mr.doob / http://mrdoob.com/
  15167. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  15168. */
  15169. THREE.PlaneGeometry = function ( width, depth, segmentsWidth, segmentsDepth ) {
  15170. THREE.Geometry.call( this );
  15171. var ix, iz,
  15172. width_half = width / 2,
  15173. depth_half = depth / 2,
  15174. gridX = segmentsWidth || 1,
  15175. gridZ = segmentsDepth || 1,
  15176. gridX1 = gridX + 1,
  15177. gridZ1 = gridZ + 1,
  15178. segment_width = width / gridX,
  15179. segment_depth = depth / gridZ,
  15180. normal = new THREE.Vector3( 0, 1, 0 );
  15181. for ( iz = 0; iz < gridZ1; iz ++ ) {
  15182. for ( ix = 0; ix < gridX1; ix ++ ) {
  15183. var x = ix * segment_width - width_half;
  15184. var z = iz * segment_depth - depth_half;
  15185. this.vertices.push( new THREE.Vertex( new THREE.Vector3( x, 0, z ) ) );
  15186. }
  15187. }
  15188. for ( iz = 0; iz < gridZ; iz ++ ) {
  15189. for ( ix = 0; ix < gridX; ix ++ ) {
  15190. var a = ix + gridX1 * iz;
  15191. var b = ix + gridX1 * ( iz + 1 );
  15192. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  15193. var d = ( ix + 1 ) + gridX1 * iz;
  15194. var face = new THREE.Face4( a, b, c, d );
  15195. face.normal.copy( normal );
  15196. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  15197. this.faces.push( face );
  15198. this.faceVertexUvs[ 0 ].push( [
  15199. new THREE.UV( ix / gridX, iz / gridZ ),
  15200. new THREE.UV( ix / gridX, ( iz + 1 ) / gridZ ),
  15201. new THREE.UV( ( ix + 1 ) / gridX, ( iz + 1 ) / gridZ ),
  15202. new THREE.UV( ( ix + 1 ) / gridX, iz / gridZ )
  15203. ] );
  15204. }
  15205. }
  15206. this.computeCentroids();
  15207. };
  15208. THREE.PlaneGeometry.prototype = new THREE.Geometry();
  15209. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  15210. /**
  15211. * @author mr.doob / http://mrdoob.com/
  15212. */
  15213. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  15214. THREE.Geometry.call( this );
  15215. radius = radius || 50;
  15216. phiStart = phiStart !== undefined ? phiStart : 0;
  15217. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  15218. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  15219. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  15220. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  15221. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  15222. var x, y, vertices = [], uvs = [];
  15223. for ( y = 0; y <= segmentsY; y ++ ) {
  15224. var verticesRow = [];
  15225. var uvsRow = [];
  15226. for ( x = 0; x <= segmentsX; x ++ ) {
  15227. var u = x / segmentsX;
  15228. var v = y / segmentsY;
  15229. var xpos = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15230. var ypos = radius * Math.cos( thetaStart + v * thetaLength );
  15231. var zpos = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  15232. this.vertices.push( new THREE.Vertex( new THREE.Vector3( xpos, ypos, zpos ) ) );
  15233. verticesRow.push( this.vertices.length - 1 );
  15234. uvsRow.push( new THREE.UV( u, v ) );
  15235. }
  15236. vertices.push( verticesRow );
  15237. uvs.push( uvsRow );
  15238. }
  15239. for ( y = 0; y < segmentsY; y ++ ) {
  15240. for ( x = 0; x < segmentsX; x ++ ) {
  15241. var v1 = vertices[ y ][ x + 1 ];
  15242. var v2 = vertices[ y ][ x ];
  15243. var v3 = vertices[ y + 1 ][ x ];
  15244. var v4 = vertices[ y + 1 ][ x + 1 ];
  15245. var n1 = this.vertices[ v1 ].position.clone().normalize();
  15246. var n2 = this.vertices[ v2 ].position.clone().normalize();
  15247. var n3 = this.vertices[ v3 ].position.clone().normalize();
  15248. var n4 = this.vertices[ v4 ].position.clone().normalize();
  15249. var uv1 = uvs[ y ][ x + 1 ].clone();
  15250. var uv2 = uvs[ y ][ x ].clone();
  15251. var uv3 = uvs[ y + 1 ][ x ].clone();
  15252. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  15253. if ( Math.abs( this.vertices[ v1 ].position.y ) == radius ) {
  15254. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  15255. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  15256. } else if ( Math.abs( this.vertices[ v3 ].position.y ) == radius ) {
  15257. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  15258. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  15259. } else {
  15260. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  15261. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  15262. }
  15263. }
  15264. }
  15265. this.computeCentroids();
  15266. this.computeFaceNormals();
  15267. this.boundingSphere = { radius: radius };
  15268. };
  15269. THREE.SphereGeometry.prototype = new THREE.Geometry();
  15270. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  15271. /**
  15272. * @author zz85 / http://www.lab4games.net/zz85/blog
  15273. * @author alteredq / http://alteredqualia.com/
  15274. *
  15275. * For creating 3D text geometry in three.js
  15276. *
  15277. * Text = 3D Text
  15278. *
  15279. * parameters = {
  15280. * size: <float>, // size of the text
  15281. * height: <float>, // thickness to extrude text
  15282. * curveSegments: <int>, // number of points on the curves
  15283. *
  15284. * font: <string>, // font name
  15285. * weight: <string>, // font weight (normal, bold)
  15286. * style: <string>, // font style (normal, italics)
  15287. *
  15288. * bevelEnabled: <bool>, // turn on bevel
  15289. * bevelThickness: <float>, // how deep into text bevel goes
  15290. * bevelSize: <float>, // how far from text outline is bevel
  15291. *
  15292. * bend: <bool> // bend according to hardcoded curve (generates bendPath)
  15293. * bendPath: <curve> // wraps text according to bend Path
  15294. * }
  15295. *
  15296. * It uses techniques used in:
  15297. *
  15298. * typeface.js and canvastext
  15299. * For converting fonts and rendering with javascript
  15300. * http://typeface.neocracy.org
  15301. *
  15302. * Triangulation ported from AS3
  15303. * Simple Polygon Triangulation
  15304. * http://actionsnippet.com/?p=1462
  15305. *
  15306. * A Method to triangulate shapes with holes
  15307. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  15308. *
  15309. */
  15310. /* Usage Examples
  15311. // TextGeometry wrapper
  15312. var text3d = new TextGeometry( text, options );
  15313. // Complete manner
  15314. var textPath = new THREE.TextPath( text, options );
  15315. var textShapes = textPath.toShapes();
  15316. var text3d = new ExtrudeGeometry( textShapes, options );
  15317. */
  15318. THREE.TextGeometry = function ( text, parameters ) {
  15319. var textPath = new THREE.TextPath( text, parameters );
  15320. var textShapes = textPath.toShapes();
  15321. // translate parameters to ExtrudeGeometry API
  15322. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  15323. // defaults
  15324. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  15325. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  15326. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  15327. if ( parameters.bend ) {
  15328. var b = textShapes[ textShapes.length - 1 ].getBoundingBox();
  15329. var max = b.maxX;
  15330. parameters.bendPath = new THREE.QuadraticBezierCurve( new THREE.Vector2( 0, 0 ),
  15331. new THREE.Vector2( max / 2, 120 ),
  15332. new THREE.Vector2( max, 0 ) );
  15333. }
  15334. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  15335. };
  15336. THREE.TextGeometry.prototype = new THREE.ExtrudeGeometry();
  15337. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  15338. THREE.FontUtils = {
  15339. faces : {},
  15340. // Just for now. face[weight][style]
  15341. face : "helvetiker",
  15342. weight: "normal",
  15343. style : "normal",
  15344. size : 150,
  15345. divisions : 10,
  15346. getFace : function() {
  15347. return this.faces[ this.face ][ this.weight ][ this.style ];
  15348. },
  15349. loadFace : function( data ) {
  15350. var family = data.familyName.toLowerCase();
  15351. var ThreeFont = this;
  15352. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  15353. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  15354. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15355. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  15356. return data;
  15357. },
  15358. drawText : function( text ) {
  15359. var characterPts = [], allPts = [];
  15360. // RenderText
  15361. var i, p,
  15362. face = this.getFace(),
  15363. scale = this.size / face.resolution,
  15364. offset = 0,
  15365. chars = String( text ).split( '' ),
  15366. length = chars.length;
  15367. var fontPaths = [];
  15368. for ( i = 0; i < length; i ++ ) {
  15369. var path = new THREE.Path();
  15370. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  15371. offset += ret.offset;
  15372. //characterPts.push( ret.points );
  15373. //allPts = allPts.concat( ret.points );
  15374. fontPaths.push( ret.path );
  15375. }
  15376. // get the width
  15377. var width = offset / 2;
  15378. //
  15379. // for ( p = 0; p < allPts.length; p++ ) {
  15380. //
  15381. // allPts[ p ].x -= width;
  15382. //
  15383. // }
  15384. //var extract = this.extractPoints( allPts, characterPts );
  15385. //extract.contour = allPts;
  15386. //extract.paths = fontPaths;
  15387. //extract.offset = width;
  15388. return { paths : fontPaths, offset : width };
  15389. },
  15390. extractGlyphPoints : function( c, face, scale, offset, path ) {
  15391. var pts = [];
  15392. var i, i2, divisions,
  15393. outline, action, length,
  15394. scaleX, scaleY,
  15395. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  15396. laste,
  15397. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  15398. if ( !glyph ) return;
  15399. if ( glyph.o ) {
  15400. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  15401. length = outline.length;
  15402. scaleX = scale;
  15403. scaleY = scale;
  15404. for ( i = 0; i < length; ) {
  15405. action = outline[ i ++ ];
  15406. //console.log( action );
  15407. switch( action ) {
  15408. case 'm':
  15409. // Move To
  15410. x = outline[ i++ ] * scaleX + offset;
  15411. y = outline[ i++ ] * scaleY;
  15412. pts.push( new THREE.Vector2( x, y ) );
  15413. path.moveTo( x, y );
  15414. break;
  15415. case 'l':
  15416. // Line To
  15417. x = outline[ i++ ] * scaleX + offset;
  15418. y = outline[ i++ ] * scaleY;
  15419. pts.push( new THREE.Vector2( x, y ) );
  15420. path.lineTo(x,y);
  15421. break;
  15422. case 'q':
  15423. // QuadraticCurveTo
  15424. cpx = outline[ i++ ] * scaleX + offset;
  15425. cpy = outline[ i++ ] * scaleY;
  15426. cpx1 = outline[ i++ ] * scaleX + offset;
  15427. cpy1 = outline[ i++ ] * scaleY;
  15428. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  15429. laste = pts[ pts.length - 1 ];
  15430. if ( laste ) {
  15431. cpx0 = laste.x;
  15432. cpy0 = laste.y;
  15433. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15434. var t = i2 / divisions;
  15435. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  15436. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  15437. pts.push( new THREE.Vector2( tx, ty ) );
  15438. }
  15439. }
  15440. break;
  15441. case 'b':
  15442. // Cubic Bezier Curve
  15443. cpx = outline[ i++ ] * scaleX + offset;
  15444. cpy = outline[ i++ ] * scaleY;
  15445. cpx1 = outline[ i++ ] * scaleX + offset;
  15446. cpy1 = outline[ i++ ] * -scaleY;
  15447. cpx2 = outline[ i++ ] * scaleX + offset;
  15448. cpy2 = outline[ i++ ] * -scaleY;
  15449. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  15450. laste = pts[ pts.length - 1 ];
  15451. if ( laste ) {
  15452. cpx0 = laste.x;
  15453. cpy0 = laste.y;
  15454. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  15455. var t = i2 / divisions;
  15456. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  15457. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  15458. pts.push( new THREE.Vector2( tx, ty ) );
  15459. }
  15460. }
  15461. break;
  15462. }
  15463. }
  15464. }
  15465. return { offset: glyph.ha*scale, points:pts, path:path};
  15466. }
  15467. };
  15468. /**
  15469. * This code is a quick port of code written in C++ which was submitted to
  15470. * flipcode.com by John W. Ratcliff // July 22, 2000
  15471. * See original code and more information here:
  15472. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  15473. *
  15474. * ported to actionscript by Zevan Rosser
  15475. * www.actionsnippet.com
  15476. *
  15477. * ported to javascript by Joshua Koo
  15478. * http://www.lab4games.net/zz85/blog
  15479. *
  15480. */
  15481. ( function( namespace ) {
  15482. var EPSILON = 0.0000000001;
  15483. // takes in an contour array and returns
  15484. var process = function( contour, indices ) {
  15485. var n = contour.length;
  15486. if ( n < 3 ) return null;
  15487. var result = [],
  15488. verts = [],
  15489. vertIndices = [];
  15490. /* we want a counter-clockwise polygon in verts */
  15491. var u, v, w;
  15492. if ( area( contour ) > 0.0 ) {
  15493. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  15494. } else {
  15495. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  15496. }
  15497. var nv = n;
  15498. /* remove nv - 2 vertices, creating 1 triangle every time */
  15499. var count = 2 * nv; /* error detection */
  15500. for( v = nv - 1; nv > 2; ) {
  15501. /* if we loop, it is probably a non-simple polygon */
  15502. if ( ( count-- ) <= 0 ) {
  15503. //** Triangulate: ERROR - probable bad polygon!
  15504. //throw ( "Warning, unable to triangulate polygon!" );
  15505. //return null;
  15506. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  15507. console.log( "Warning, unable to triangulate polygon!" );
  15508. if ( indices ) return vertIndices;
  15509. return result;
  15510. }
  15511. /* three consecutive vertices in current polygon, <u,v,w> */
  15512. u = v; if ( nv <= u ) u = 0; /* previous */
  15513. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  15514. w = v + 1; if ( nv <= w ) w = 0; /* next */
  15515. if ( snip( contour, u, v, w, nv, verts ) ) {
  15516. var a, b, c, s, t;
  15517. /* true names of the vertices */
  15518. a = verts[ u ];
  15519. b = verts[ v ];
  15520. c = verts[ w ];
  15521. /* output Triangle */
  15522. /*
  15523. result.push( contour[ a ] );
  15524. result.push( contour[ b ] );
  15525. result.push( contour[ c ] );
  15526. */
  15527. result.push( [ contour[ a ],
  15528. contour[ b ],
  15529. contour[ c ] ] );
  15530. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  15531. /* remove v from the remaining polygon */
  15532. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  15533. verts[ s ] = verts[ t ];
  15534. }
  15535. nv--;
  15536. /* reset error detection counter */
  15537. count = 2 * nv;
  15538. }
  15539. }
  15540. if ( indices ) return vertIndices;
  15541. return result;
  15542. };
  15543. // calculate area of the contour polygon
  15544. var area = function ( contour ) {
  15545. var n = contour.length;
  15546. var a = 0.0;
  15547. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  15548. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  15549. }
  15550. return a * 0.5;
  15551. };
  15552. // see if p is inside triangle abc
  15553. var insideTriangle = function( ax, ay,
  15554. bx, by,
  15555. cx, cy,
  15556. px, py ) {
  15557. var aX, aY, bX, bY;
  15558. var cX, cY, apx, apy;
  15559. var bpx, bpy, cpx, cpy;
  15560. var cCROSSap, bCROSScp, aCROSSbp;
  15561. aX = cx - bx; aY = cy - by;
  15562. bX = ax - cx; bY = ay - cy;
  15563. cX = bx - ax; cY = by - ay;
  15564. apx= px -ax; apy= py - ay;
  15565. bpx= px - bx; bpy= py - by;
  15566. cpx= px - cx; cpy= py - cy;
  15567. aCROSSbp = aX*bpy - aY*bpx;
  15568. cCROSSap = cX*apy - cY*apx;
  15569. bCROSScp = bX*cpy - bY*cpx;
  15570. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  15571. };
  15572. var snip = function ( contour, u, v, w, n, verts ) {
  15573. var p;
  15574. var ax, ay, bx, by;
  15575. var cx, cy, px, py;
  15576. ax = contour[ verts[ u ] ].x;
  15577. ay = contour[ verts[ u ] ].y;
  15578. bx = contour[ verts[ v ] ].x;
  15579. by = contour[ verts[ v ] ].y;
  15580. cx = contour[ verts[ w ] ].x;
  15581. cy = contour[ verts[ w ] ].y;
  15582. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  15583. for ( p = 0; p < n; p++ ) {
  15584. if( (p == u) || (p == v) || (p == w) ) continue;
  15585. px = contour[ verts[ p ] ].x
  15586. py = contour[ verts[ p ] ].y
  15587. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  15588. }
  15589. return true;
  15590. };
  15591. namespace.Triangulate = process;
  15592. namespace.Triangulate.area = area;
  15593. return namespace;
  15594. })(THREE.FontUtils);
  15595. // To use the typeface.js face files, hook up the API
  15596. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  15597. /**
  15598. * @author oosmoxiecode
  15599. * @author mr.doob / http://mrdoob.com/
  15600. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  15601. */
  15602. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  15603. THREE.Geometry.call( this );
  15604. var scope = this;
  15605. this.radius = radius || 100;
  15606. this.tube = tube || 40;
  15607. this.segmentsR = segmentsR || 8;
  15608. this.segmentsT = segmentsT || 6;
  15609. this.arc = arc || Math.PI * 2;
  15610. var center = new THREE.Vector3(), uvs = [], normals = [];
  15611. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  15612. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  15613. var u = i / this.segmentsT * this.arc;
  15614. var v = j / this.segmentsR * Math.PI * 2;
  15615. center.x = this.radius * Math.cos( u );
  15616. center.y = this.radius * Math.sin( u );
  15617. var vector = new THREE.Vector3();
  15618. vector.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  15619. vector.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  15620. vector.z = this.tube * Math.sin( v );
  15621. this.vertices.push( new THREE.Vertex( vector ) );
  15622. uvs.push( new THREE.UV( i / this.segmentsT, 1 - j / this.segmentsR ) );
  15623. normals.push( vector.clone().subSelf( center ).normalize() );
  15624. }
  15625. }
  15626. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  15627. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  15628. var a = ( this.segmentsT + 1 ) * j + i - 1;
  15629. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  15630. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  15631. var d = ( this.segmentsT + 1 ) * j + i;
  15632. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  15633. face.normal.addSelf( normals[ a ] );
  15634. face.normal.addSelf( normals[ b ] );
  15635. face.normal.addSelf( normals[ c ] );
  15636. face.normal.addSelf( normals[ d ] );
  15637. face.normal.normalize();
  15638. this.faces.push( face );
  15639. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  15640. }
  15641. }
  15642. this.computeCentroids();
  15643. };
  15644. THREE.TorusGeometry.prototype = new THREE.Geometry();
  15645. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  15646. /**
  15647. * @author oosmoxiecode
  15648. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  15649. */
  15650. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  15651. THREE.Geometry.call( this );
  15652. var scope = this;
  15653. this.radius = radius || 200;
  15654. this.tube = tube || 40;
  15655. this.segmentsR = segmentsR || 64;
  15656. this.segmentsT = segmentsT || 8;
  15657. this.p = p || 2;
  15658. this.q = q || 3;
  15659. this.heightScale = heightScale || 1;
  15660. this.grid = new Array(this.segmentsR);
  15661. var tang = new THREE.Vector3();
  15662. var n = new THREE.Vector3();
  15663. var bitan = new THREE.Vector3();
  15664. for ( var i = 0; i < this.segmentsR; ++ i ) {
  15665. this.grid[ i ] = new Array( this.segmentsT );
  15666. for ( var j = 0; j < this.segmentsT; ++ j ) {
  15667. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  15668. var v = j / this.segmentsT * 2 * Math.PI;
  15669. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  15670. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  15671. var cx, cy;
  15672. tang.sub( p2, p1 );
  15673. n.add( p2, p1 );
  15674. bitan.cross( tang, n );
  15675. n.cross( bitan, tang );
  15676. bitan.normalize();
  15677. n.normalize();
  15678. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  15679. cy = this.tube * Math.sin( v );
  15680. p1.x += cx * n.x + cy * bitan.x;
  15681. p1.y += cx * n.y + cy * bitan.y;
  15682. p1.z += cx * n.z + cy * bitan.z;
  15683. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  15684. }
  15685. }
  15686. for ( var i = 0; i < this.segmentsR; ++ i ) {
  15687. for ( var j = 0; j < this.segmentsT; ++ j ) {
  15688. var ip = ( i + 1 ) % this.segmentsR;
  15689. var jp = ( j + 1 ) % this.segmentsT;
  15690. var a = this.grid[ i ][ j ];
  15691. var b = this.grid[ ip ][ j ];
  15692. var c = this.grid[ ip ][ jp ];
  15693. var d = this.grid[ i ][ jp ];
  15694. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  15695. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  15696. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  15697. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  15698. this.faces.push( new THREE.Face4( a, b, c, d ) );
  15699. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  15700. }
  15701. }
  15702. this.computeCentroids();
  15703. this.computeFaceNormals();
  15704. this.computeVertexNormals();
  15705. function vert( x, y, z ) {
  15706. return scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) ) - 1;
  15707. }
  15708. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  15709. var cu = Math.cos( u );
  15710. var cv = Math.cos( v );
  15711. var su = Math.sin( u );
  15712. var quOverP = in_q / in_p * u;
  15713. var cs = Math.cos( quOverP );
  15714. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  15715. var ty = radius * ( 2 + cs ) * su * 0.5;
  15716. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  15717. return new THREE.Vector3( tx, ty, tz );
  15718. }
  15719. };
  15720. THREE.TorusKnotGeometry.prototype = new THREE.Geometry();
  15721. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  15722. /**
  15723. * @author WestLangley / https://github.com/WestLangley
  15724. * @author zz85 / https://github.com/zz85
  15725. * @author miningold / https://github.com/miningold
  15726. *
  15727. * Modified from the TorusKnotGeometry by @oosmoxiecode
  15728. *
  15729. * Creates a tube which extrudes along a 3d spline
  15730. *
  15731. * Uses parallel transport frames as described in
  15732. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  15733. */
  15734. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  15735. THREE.Geometry.call( this );
  15736. this.path = path;
  15737. this.segments = segments || 64;
  15738. this.radius = radius || 1;
  15739. this.segmentsRadius = segmentsRadius || 8;
  15740. this.closed = closed || false;
  15741. if ( debug ) this.debug = new THREE.Object3D();
  15742. this.grid = [];
  15743. var scope = this,
  15744. tangent = new THREE.Vector3(),
  15745. normal = new THREE.Vector3(),
  15746. binormal = new THREE.Vector3(),
  15747. vec = new THREE.Vector3(),
  15748. mat = new THREE.Matrix4(),
  15749. tangents = [],
  15750. normals = [],
  15751. binormals = [],
  15752. numpoints = this.segments + 1,
  15753. theta,
  15754. epsilon = 0.0001,
  15755. smallest,
  15756. x, y, z,
  15757. tx, ty, tz,
  15758. u, v,
  15759. p1, p2,
  15760. cx, cy,
  15761. pos, pos2,
  15762. i, j,
  15763. ip, jp,
  15764. a, b, c, d,
  15765. uva, uvb, uvc, uvd;
  15766. // expose internals
  15767. this.tangents = tangents;
  15768. this.normals = normals;
  15769. this.binormals = binormals;
  15770. function vert( x, y, z ) {
  15771. return scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) ) - 1;
  15772. }
  15773. // compute the tangent vectors for each segment on the path
  15774. for ( i = 0; i < numpoints; i++ ) {
  15775. u = i / ( numpoints - 1 );
  15776. tangents[ i ] = this.path.getTangentAt( u );
  15777. tangents[ i ].normalize();
  15778. }
  15779. initialNormal3();
  15780. function initialNormal1() {
  15781. // fixed start binormal. Has dangers of 0 vectors
  15782. normals[ 0 ] = new THREE.Vector3();
  15783. binormals[ 0 ] = new THREE.Vector3();
  15784. var lastBinormal = new THREE.Vector3( 0, 0, 1 );
  15785. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  15786. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  15787. }
  15788. function initialNormal2() {
  15789. // This uses the Frenet-Serret formula for deriving binormal
  15790. var t2 = path.getTangentAt( epsilon );
  15791. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize()
  15792. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  15793. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  15794. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  15795. }
  15796. function initialNormal3() {
  15797. // select an initial normal vector perpenicular to the first tangent vector,
  15798. // and in the direction of the smallest tangent xyz component
  15799. normals[ 0 ] = new THREE.Vector3();
  15800. binormals[ 0 ] = new THREE.Vector3();
  15801. smallest = Number.MAX_VALUE;
  15802. tx = Math.abs( tangents[ 0 ].x );
  15803. ty = Math.abs( tangents[ 0 ].y );
  15804. tz = Math.abs( tangents[ 0 ].z );
  15805. if ( tx <= smallest ) {
  15806. smallest = tx;
  15807. vec.set( 1, 0, 0 );
  15808. }
  15809. if ( ty <= smallest ) {
  15810. smallest = ty;
  15811. vec.set( 0, 1, 0 );
  15812. }
  15813. if ( tz <= smallest ) {
  15814. vec.set( 0, 0, 1 );
  15815. }
  15816. // vec.cross( tangents[ 0 ], normal ).normalize();
  15817. normals[ 0 ].cross( tangents[ 0 ], vec );
  15818. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  15819. }
  15820. // compute the slowly-varying normal and binormal vectors for each segment on the path
  15821. for ( i = 1; i < numpoints; i++ ) {
  15822. normals[ i ] = normals[ i-1 ].clone();
  15823. binormals[ i ] = binormals[ i-1 ].clone();
  15824. vec.cross( tangents[ i-1 ], tangents[ i ] );
  15825. if ( vec.length() > epsilon ) {
  15826. vec.normalize();
  15827. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  15828. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  15829. }
  15830. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  15831. }
  15832. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  15833. if ( this.closed ) {
  15834. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  15835. theta /= ( numpoints - 1 );
  15836. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  15837. theta = -theta;
  15838. }
  15839. for ( i = 1; i < numpoints; i++ ) {
  15840. // twist a little...
  15841. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  15842. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  15843. }
  15844. }
  15845. // consruct the grid
  15846. for ( i = 0; i < numpoints; i++ ) {
  15847. this.grid[ i ] = [];
  15848. u = i / ( numpoints - 1 );
  15849. pos = this.path.getPointAt( u );
  15850. tangent = tangents[ i ];
  15851. normal = normals[ i ];
  15852. binormal = binormals[ i ];
  15853. if ( this.debug ) {
  15854. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  15855. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  15856. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  15857. }
  15858. for ( j = 0; j < this.segmentsRadius; j++ ) {
  15859. v = j / this.segmentsRadius * 2 * Math.PI;
  15860. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  15861. cy = this.radius * Math.sin( v );
  15862. pos2 = new THREE.Vector3().copy( pos );
  15863. pos2.x += cx * normal.x + cy * binormal.x;
  15864. pos2.y += cx * normal.y + cy * binormal.y;
  15865. pos2.z += cx * normal.z + cy * binormal.z;
  15866. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  15867. }
  15868. }
  15869. // construct the mesh
  15870. for ( i = 0; i < this.segments; i++ ) {
  15871. for ( j = 0; j < this.segmentsRadius; j++ ) {
  15872. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  15873. jp = (j + 1) % this.segmentsRadius;
  15874. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  15875. b = this.grid[ ip ][ j ];
  15876. c = this.grid[ ip ][ jp ];
  15877. d = this.grid[ i ][ jp ];
  15878. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  15879. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  15880. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  15881. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  15882. this.faces.push( new THREE.Face4( a, b, c, d ) );
  15883. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  15884. }
  15885. }
  15886. this.computeCentroids();
  15887. this.computeFaceNormals();
  15888. this.computeVertexNormals();
  15889. };
  15890. THREE.TubeGeometry.prototype = new THREE.Geometry();
  15891. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  15892. /**
  15893. * @author clockworkgeek / https://github.com/clockworkgeek
  15894. * @author timothypratley / https://github.com/timothypratley
  15895. */
  15896. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  15897. THREE.Geometry.call( this );
  15898. radius = radius || 1;
  15899. detail = detail || 0;
  15900. var that = this;
  15901. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  15902. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  15903. }
  15904. var midpoints = [], p = this.vertices;
  15905. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  15906. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  15907. }
  15908. this.mergeVertices();
  15909. // Apply radius
  15910. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  15911. this.vertices[ i ].position.multiplyScalar( radius );
  15912. }
  15913. /**
  15914. * Project vector onto sphere's surface
  15915. */
  15916. function prepare( vector ) {
  15917. var vertex = new THREE.Vertex( vector.normalize() );
  15918. vertex.index = that.vertices.push( vertex ) - 1;
  15919. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  15920. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  15921. var v = inclination( vector ) / Math.PI + 0.5;
  15922. vertex.uv = new THREE.UV( u, v );
  15923. return vertex;
  15924. }
  15925. /**
  15926. * Approximate a curved face with recursively sub-divided triangles.
  15927. */
  15928. function make( v1, v2, v3, detail ) {
  15929. if ( detail < 1 ) {
  15930. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.position.clone(), v2.position.clone(), v3.position.clone() ] );
  15931. face.centroid.addSelf( v1.position ).addSelf( v2.position ).addSelf( v3.position ).divideScalar( 3 );
  15932. face.normal = face.centroid.clone().normalize();
  15933. that.faces.push( face );
  15934. var azi = azimuth( face.centroid );
  15935. that.faceVertexUvs[ 0 ].push( [
  15936. correctUV( v1.uv, v1.position, azi ),
  15937. correctUV( v2.uv, v2.position, azi ),
  15938. correctUV( v3.uv, v3.position, azi )
  15939. ] );
  15940. }
  15941. else {
  15942. detail -= 1;
  15943. // split triangle into 4 smaller triangles
  15944. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  15945. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  15946. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  15947. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  15948. }
  15949. }
  15950. function midpoint( v1, v2 ) {
  15951. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  15952. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  15953. var mid = midpoints[ v1.index ][ v2.index ];
  15954. if ( mid === undefined ) {
  15955. // generate mean point and project to surface with prepare()
  15956. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  15957. new THREE.Vector3().add( v1.position, v2.position ).divideScalar( 2 )
  15958. );
  15959. }
  15960. return mid;
  15961. }
  15962. /**
  15963. * Angle around the Y axis, counter-clockwise when looking from above.
  15964. */
  15965. function azimuth( vector ) {
  15966. return Math.atan2( vector.z, -vector.x );
  15967. }
  15968. /**
  15969. * Angle above the XZ plane.
  15970. */
  15971. function inclination( vector ) {
  15972. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  15973. }
  15974. /**
  15975. * Texture fixing helper. Spheres have some odd behaviours.
  15976. */
  15977. function correctUV( uv, vector, azimuth ) {
  15978. if ( (azimuth < 0) && (uv.u === 1) ) uv = new THREE.UV( uv.u - 1, uv.v );
  15979. if ( (vector.x === 0) && (vector.z === 0) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  15980. return uv;
  15981. }
  15982. this.computeCentroids();
  15983. this.boundingSphere = { radius: radius };
  15984. };
  15985. THREE.PolyhedronGeometry.prototype = new THREE.Geometry();
  15986. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  15987. /**
  15988. * @author timothypratley / https://github.com/timothypratley
  15989. */
  15990. THREE.IcosahedronGeometry = function ( radius, detail ) {
  15991. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  15992. var vertices = [
  15993. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  15994. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  15995. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  15996. ];
  15997. var faces = [
  15998. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  15999. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  16000. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  16001. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  16002. ];
  16003. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16004. };
  16005. THREE.IcosahedronGeometry.prototype = new THREE.Geometry();
  16006. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  16007. /**
  16008. * @author timothypratley / https://github.com/timothypratley
  16009. */
  16010. THREE.OctahedronGeometry = function ( radius, detail ) {
  16011. var vertices = [
  16012. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  16013. ];
  16014. var faces = [
  16015. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  16016. ];
  16017. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16018. };
  16019. THREE.OctahedronGeometry.prototype = new THREE.Geometry();
  16020. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  16021. /**
  16022. * @author timothypratley / https://github.com/timothypratley
  16023. */
  16024. THREE.TetrahedronGeometry = function ( radius, detail ) {
  16025. var vertices = [
  16026. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  16027. ];
  16028. var faces = [
  16029. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  16030. ];
  16031. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  16032. };
  16033. THREE.TetrahedronGeometry.prototype = new THREE.Geometry();
  16034. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  16035. /**
  16036. * @author sroucheray / http://sroucheray.org/
  16037. * @author mr.doob / http://mrdoob.com/
  16038. */
  16039. THREE.AxisHelper = function () {
  16040. THREE.Object3D.call( this );
  16041. var lineGeometry = new THREE.Geometry();
  16042. lineGeometry.vertices.push( new THREE.Vertex() );
  16043. lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 100, 0 ) ) );
  16044. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  16045. var line, cone;
  16046. // x
  16047. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  16048. line.rotation.z = - Math.PI / 2;
  16049. this.add( line );
  16050. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  16051. cone.position.x = 100;
  16052. cone.rotation.z = - Math.PI / 2;
  16053. this.add( cone );
  16054. // y
  16055. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  16056. this.add( line );
  16057. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  16058. cone.position.y = 100;
  16059. this.add( cone );
  16060. // z
  16061. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  16062. line.rotation.x = Math.PI / 2;
  16063. this.add( line );
  16064. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  16065. cone.position.z = 100;
  16066. cone.rotation.x = Math.PI / 2;
  16067. this.add( cone );
  16068. };
  16069. THREE.AxisHelper.prototype = new THREE.Object3D();
  16070. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  16071. /**
  16072. * @author WestLangley / https://github.com/WestLangley
  16073. * @author zz85 / https://github.com/zz85
  16074. *
  16075. * Creates an arrow for visualizing directions
  16076. *
  16077. * Parameters:
  16078. * dir - Vector3
  16079. * origin - Vector3
  16080. * length - Number
  16081. * hex - color in hex value
  16082. */
  16083. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  16084. THREE.Object3D.call( this );
  16085. if ( hex === undefined ) hex = 0xffff00;
  16086. if ( length === undefined ) length = 20;
  16087. var lineGeometry = new THREE.Geometry();
  16088. lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 0, 0 ) ) );
  16089. lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3( 0, 1, 0 ) ) );
  16090. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : hex } ) );
  16091. this.add( this.line );
  16092. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  16093. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : hex } ) );
  16094. this.cone.position.set( 0, 1, 0 );
  16095. this.add( this.cone );
  16096. if ( origin instanceof THREE.Vector3 ) {
  16097. this.position = origin;
  16098. }
  16099. this.setDirection( dir );
  16100. this.setLength( length );
  16101. };
  16102. THREE.ArrowHelper.prototype = new THREE.Object3D();
  16103. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  16104. THREE.ArrowHelper.prototype.setDirection = function( dir ) {
  16105. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  16106. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  16107. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  16108. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  16109. };
  16110. THREE.ArrowHelper.prototype.setLength = function( length ) {
  16111. this.scale.set( length, length, length );
  16112. };
  16113. THREE.ArrowHelper.prototype.setColor = function( hex ) {
  16114. this.line.material.color.setHex( hex );
  16115. this.cone.material.color.setHex( hex );
  16116. };
  16117. /**
  16118. * @author alteredq / http://alteredqualia.com/
  16119. *
  16120. * - shows frustum, line of sight and up of the camera
  16121. * - suitable for fast updates
  16122. * - based on frustum visualization in lightgl.js shadowmap example
  16123. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  16124. */
  16125. THREE.CameraHelper = function ( camera ) {
  16126. THREE.Object3D.call( this );
  16127. var _this = this;
  16128. this.lineGeometry = new THREE.Geometry();
  16129. this.lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  16130. this.pointMap = {};
  16131. // colors
  16132. var hexFrustum = 0xffaa00,
  16133. hexCone = 0xff0000,
  16134. hexUp = 0x00aaff,
  16135. hexTarget = 0xffffff,
  16136. hexCross = 0x333333;
  16137. // near
  16138. addLine( "n1", "n2", hexFrustum );
  16139. addLine( "n2", "n4", hexFrustum );
  16140. addLine( "n4", "n3", hexFrustum );
  16141. addLine( "n3", "n1", hexFrustum );
  16142. // far
  16143. addLine( "f1", "f2", hexFrustum );
  16144. addLine( "f2", "f4", hexFrustum );
  16145. addLine( "f4", "f3", hexFrustum );
  16146. addLine( "f3", "f1", hexFrustum );
  16147. // sides
  16148. addLine( "n1", "f1", hexFrustum );
  16149. addLine( "n2", "f2", hexFrustum );
  16150. addLine( "n3", "f3", hexFrustum );
  16151. addLine( "n4", "f4", hexFrustum );
  16152. // cone
  16153. addLine( "p", "n1", hexCone );
  16154. addLine( "p", "n2", hexCone );
  16155. addLine( "p", "n3", hexCone );
  16156. addLine( "p", "n4", hexCone );
  16157. // up
  16158. addLine( "u1", "u2", hexUp );
  16159. addLine( "u2", "u3", hexUp );
  16160. addLine( "u3", "u1", hexUp );
  16161. // target
  16162. addLine( "c", "t", hexTarget );
  16163. addLine( "p", "c", hexCross );
  16164. // cross
  16165. addLine( "cn1", "cn2", hexCross );
  16166. addLine( "cn3", "cn4", hexCross );
  16167. addLine( "cf1", "cf2", hexCross );
  16168. addLine( "cf3", "cf4", hexCross );
  16169. this.camera = camera;
  16170. function addLine( a, b, hex ) {
  16171. addPoint( a, hex );
  16172. addPoint( b, hex );
  16173. }
  16174. function addPoint( id, hex ) {
  16175. _this.lineGeometry.vertices.push( new THREE.Vertex( new THREE.Vector3() ) );
  16176. _this.lineGeometry.colors.push( new THREE.Color( hex ) );
  16177. if ( _this.pointMap[ id ] === undefined ) _this.pointMap[ id ] = [];
  16178. _this.pointMap[ id ].push( _this.lineGeometry.vertices.length - 1 );
  16179. }
  16180. this.update( camera );
  16181. this.lines = new THREE.Line( this.lineGeometry, this.lineMaterial, THREE.LinePieces );
  16182. this.add( this.lines );
  16183. };
  16184. THREE.CameraHelper.prototype = new THREE.Object3D();
  16185. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  16186. THREE.CameraHelper.prototype.update = function () {
  16187. var camera = this.camera;
  16188. var w = 1;
  16189. var h = 1;
  16190. var _this = this;
  16191. // we need just camera projection matrix
  16192. // world matrix must be identity
  16193. THREE.CameraHelper.__c.projectionMatrix.copy( camera.projectionMatrix );
  16194. // center / target
  16195. setPoint( "c", 0, 0, -1 );
  16196. setPoint( "t", 0, 0, 1 );
  16197. // near
  16198. setPoint( "n1", -w, -h, -1 );
  16199. setPoint( "n2", w, -h, -1 );
  16200. setPoint( "n3", -w, h, -1 );
  16201. setPoint( "n4", w, h, -1 );
  16202. // far
  16203. setPoint( "f1", -w, -h, 1 );
  16204. setPoint( "f2", w, -h, 1 );
  16205. setPoint( "f3", -w, h, 1 );
  16206. setPoint( "f4", w, h, 1 );
  16207. // up
  16208. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  16209. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  16210. setPoint( "u3", 0, h * 2, -1 );
  16211. // cross
  16212. setPoint( "cf1", -w, 0, 1 );
  16213. setPoint( "cf2", w, 0, 1 );
  16214. setPoint( "cf3", 0, -h, 1 );
  16215. setPoint( "cf4", 0, h, 1 );
  16216. setPoint( "cn1", -w, 0, -1 );
  16217. setPoint( "cn2", w, 0, -1 );
  16218. setPoint( "cn3", 0, -h, -1 );
  16219. setPoint( "cn4", 0, h, -1 );
  16220. function setPoint( point, x, y, z ) {
  16221. THREE.CameraHelper.__v.set( x, y, z );
  16222. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  16223. var points = _this.pointMap[ point ];
  16224. if ( points !== undefined ) {
  16225. for ( var i = 0, il = points.length; i < il; i ++ ) {
  16226. var j = points[ i ];
  16227. _this.lineGeometry.vertices[ j ].position.copy( THREE.CameraHelper.__v );
  16228. }
  16229. }
  16230. }
  16231. this.lineGeometry.__dirtyVertices = true;
  16232. };
  16233. THREE.CameraHelper.__projector = new THREE.Projector();
  16234. THREE.CameraHelper.__v = new THREE.Vector3();
  16235. THREE.CameraHelper.__c = new THREE.Camera();
  16236. /*
  16237. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  16238. *
  16239. * Subdivision Geometry Modifier
  16240. * using Catmull-Clark Subdivision Surfaces
  16241. * for creating smooth geometry meshes
  16242. *
  16243. * Note: a modifier modifies vertices and faces of geometry,
  16244. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  16245. *
  16246. * Readings:
  16247. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  16248. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  16249. * http://xrt.wikidot.com/blog:31
  16250. * "Subdivision Surfaces in Character Animation"
  16251. *
  16252. * Supports:
  16253. * Closed and Open geometries.
  16254. *
  16255. * TODO:
  16256. * crease vertex and "semi-sharp" features
  16257. * selective subdivision
  16258. */
  16259. THREE.SubdivisionModifier = function( subdivisions ) {
  16260. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  16261. // Settings
  16262. this.useOldVertexColors = false;
  16263. this.supportUVs = true;
  16264. };
  16265. //THREE.SubdivisionModifier.prototype = new THREE.Modifier();
  16266. THREE.SubdivisionModifier.prototype.constructor = THREE.SubdivisionModifier;
  16267. // Applies the "modify" pattern
  16268. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  16269. var repeats = this.subdivisions;
  16270. while ( repeats-- > 0 ) {
  16271. this.smooth( geometry );
  16272. }
  16273. };
  16274. // Performs an iteration of Catmull-Clark Subdivision
  16275. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  16276. //console.log( 'running smooth' );
  16277. // New set of vertices, faces and uvs
  16278. var newVertices = [], newFaces = [], newUVs = [];
  16279. function v( x, y, z ) {
  16280. newVertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  16281. }
  16282. var scope = this;
  16283. function f4( a, b, c, d, oldFace, orders ) {
  16284. // TODO move vertex selection over here!
  16285. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.material );
  16286. if (scope.useOldVertexColors) {
  16287. newFace.vertexColors = [];
  16288. var color, tmpColor, order;
  16289. for (var i=0;i<4;i++) {
  16290. order = orders[i];
  16291. color = new THREE.Color(),
  16292. color.setRGB(0,0,0);
  16293. for (var j=0, jl=0; j<order.length;j++) {
  16294. tmpColor = oldFace.vertexColors[order[j]-1];
  16295. color.r += tmpColor.r;
  16296. color.g += tmpColor.g;
  16297. color.b += tmpColor.b;
  16298. }
  16299. color.r /= order.length;
  16300. color.g /= order.length;
  16301. color.b /= order.length;
  16302. newFace.vertexColors[i] = color;
  16303. }
  16304. }
  16305. newFaces.push( newFace );
  16306. if (!scope.supportUVs || uvForVertices.length!=0) {
  16307. newUVs.push( [
  16308. uvForVertices[a],
  16309. uvForVertices[b],
  16310. uvForVertices[c],
  16311. uvForVertices[d]
  16312. ] );
  16313. }
  16314. }
  16315. function edge_hash( a, b ) {
  16316. return Math.min( a, b ) + "_" + Math.max( a, b );
  16317. };
  16318. function computeEdgeFaces( geometry ) {
  16319. function addToMap( map, hash, i ) {
  16320. if ( map[ hash ] === undefined ) {
  16321. map[ hash ] = [];
  16322. }
  16323. map[ hash ].push( i );
  16324. };
  16325. var i, il, v1, v2, j, k,
  16326. face, faceIndices, faceIndex,
  16327. edge,
  16328. hash,
  16329. vfMap = {};
  16330. // construct vertex -> face map
  16331. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  16332. face = geometry.faces[ i ];
  16333. if ( face instanceof THREE.Face3 ) {
  16334. hash = edge_hash( face.a, face.b );
  16335. addToMap( vfMap, hash, i );
  16336. hash = edge_hash( face.b, face.c );
  16337. addToMap( vfMap, hash, i );
  16338. hash = edge_hash( face.c, face.a );
  16339. addToMap( vfMap, hash, i );
  16340. } else if ( face instanceof THREE.Face4 ) {
  16341. hash = edge_hash( face.a, face.b );
  16342. addToMap( vfMap, hash, i );
  16343. hash = edge_hash( face.b, face.c );
  16344. addToMap( vfMap, hash, i );
  16345. hash = edge_hash( face.c, face.d );
  16346. addToMap( vfMap, hash, i );
  16347. hash = edge_hash( face.d, face.a );
  16348. addToMap( vfMap, hash, i );
  16349. }
  16350. }
  16351. // extract faces
  16352. // var edges = [];
  16353. //
  16354. // var numOfEdges = 0;
  16355. // for (i in vfMap) {
  16356. // numOfEdges++;
  16357. //
  16358. // edge = vfMap[i];
  16359. // edges.push(edge);
  16360. //
  16361. // }
  16362. //console.log('vfMap', vfMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  16363. return vfMap;
  16364. };
  16365. var originalPoints = oldGeometry.vertices;
  16366. var originalFaces = oldGeometry.faces;
  16367. var newPoints = originalPoints.concat(); // Vertices
  16368. var facePoints = [], edgePoints = {};
  16369. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  16370. var uvForVertices = [];
  16371. // Step 1
  16372. // For each face, add a face point
  16373. // Set each face point to be the centroid of all original points for the respective face.
  16374. var i, il, j, jl, face;
  16375. // For Uvs
  16376. var uvs = oldGeometry.faceVertexUvs[0];
  16377. var abcd = 'abcd', vertice;
  16378. for (i=0, il = uvs.length; i<il; i++ ) {
  16379. for (j=0,jl=uvs[i].length;j<jl;j++) {
  16380. vertice = originalFaces[i][abcd.charAt(j)];
  16381. if (!uvForVertices[vertice]) {
  16382. uvForVertices[vertice] = uvs[i][j];
  16383. } else {
  16384. //console.log('dup', uvForVertices[vertice]);
  16385. }
  16386. }
  16387. }
  16388. var avgUv ;
  16389. for (i=0, il = originalFaces.length; i<il ;i++) {
  16390. face = originalFaces[i];
  16391. facePoints.push(face.centroid);
  16392. newPoints.push( new THREE.Vertex(face.centroid) );
  16393. if (!scope.supportUVs || uvForVertices.length==0) continue;
  16394. // Prepare subdivided uv
  16395. avgUv = new THREE.UV();
  16396. if ( face instanceof THREE.Face3 ) {
  16397. avgUv.u = uvForVertices[face.a].u + uvForVertices[face.b].u + uvForVertices[face.c].u;
  16398. avgUv.v = uvForVertices[face.a].v + uvForVertices[face.b].v + uvForVertices[face.c].v;
  16399. avgUv.u /= 3;
  16400. avgUv.v /= 3;
  16401. } else if ( face instanceof THREE.Face4 ) {
  16402. avgUv.u = uvForVertices[face.a].u + uvForVertices[face.b].u + uvForVertices[face.c].u + uvForVertices[face.d].u;
  16403. avgUv.v = uvForVertices[face.a].v + uvForVertices[face.b].v + uvForVertices[face.c].v + uvForVertices[face.d].v;
  16404. avgUv.u /= 4;
  16405. avgUv.v /= 4;
  16406. }
  16407. uvForVertices.push(avgUv);
  16408. }
  16409. // Step 2
  16410. // For each edge, add an edge point.
  16411. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  16412. var vfMap = computeEdgeFaces ( oldGeometry );
  16413. var edge, faceIndexA, faceIndexB, avg;
  16414. //console.log('vfMap', vfMap);
  16415. var edgeCount = 0;
  16416. var originalVerticesLength = originalPoints.length;
  16417. var edgeVertex, edgeVertexA, edgeVertexB;
  16418. ////
  16419. var vertexEdgeMap = {};
  16420. var vertexFaceMap = {};
  16421. var addVertexEdgeMap = function(vertex, edge) {
  16422. if (vertexEdgeMap[vertex]===undefined) {
  16423. vertexEdgeMap[vertex] = [];
  16424. }
  16425. vertexEdgeMap[vertex].push(edge);
  16426. };
  16427. var addVertexFaceMap = function(vertex, face, edge) {
  16428. if (vertexFaceMap[vertex]===undefined) {
  16429. vertexFaceMap[vertex] = {};
  16430. }
  16431. //vertexFaceMap[vertex][face] = edge;
  16432. vertexFaceMap[vertex][face] = null;
  16433. };
  16434. // Prepares vertexEdgeMap and vertexFaceMap
  16435. for (i in vfMap) { // This is for every edge
  16436. edge = vfMap[i];
  16437. edgeVertex = i.split('_');
  16438. edgeVertexA = edgeVertex[0];
  16439. edgeVertexB = edgeVertex[1];
  16440. // Maps an edgeVertex to connecting edges
  16441. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  16442. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  16443. // faceIndexA = edge[0]; // face index a
  16444. // faceIndexB = edge[1]; // face index b
  16445. //
  16446. // // Add connecting faces for edge
  16447. // addVertexFaceMap(edgeVertexA, faceIndexA);
  16448. // addVertexFaceMap(edgeVertexB, faceIndexA);
  16449. //
  16450. //
  16451. // if (faceIndexB) {
  16452. // addVertexFaceMap(edgeVertexA, faceIndexB);
  16453. // addVertexFaceMap(edgeVertexB, faceIndexB);
  16454. // } else {
  16455. // addVertexFaceMap(edgeVertexA, faceIndexA);
  16456. // addVertexFaceMap(edgeVertexB, faceIndexA);
  16457. // }
  16458. for (j=0,jl=edge.length;j<jl;j++) {
  16459. face = edge[j];
  16460. addVertexFaceMap(edgeVertexA, face, i);
  16461. addVertexFaceMap(edgeVertexB, face, i);
  16462. }
  16463. if (edge.length < 2) {
  16464. // edge is "sharp";
  16465. sharpEdges[i] = true;
  16466. sharpVertices[edgeVertexA] = true;
  16467. sharpVertices[edgeVertexB] = true;
  16468. }
  16469. }
  16470. //console.log('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  16471. for (i in vfMap) {
  16472. edge = vfMap[i];
  16473. faceIndexA = edge[0]; // face index a
  16474. faceIndexB = edge[1]; // face index b
  16475. edgeVertex = i.split('_');
  16476. edgeVertexA = edgeVertex[0];
  16477. edgeVertexB = edgeVertex[1];
  16478. avg = new THREE.Vector3();
  16479. //console.log(i, faceIndexB,facePoints[faceIndexB]);
  16480. if (sharpEdges[i]) {
  16481. //console.log('warning, ', i, 'edge has only 1 connecting face', edge);
  16482. // For a sharp edge, average the edge end points.
  16483. avg.addSelf(originalPoints[edgeVertexA].position);
  16484. avg.addSelf(originalPoints[edgeVertexB].position);
  16485. avg.multiplyScalar(0.5);
  16486. sharpVertices[newPoints.length] = true;
  16487. } else {
  16488. avg.addSelf(facePoints[faceIndexA]);
  16489. avg.addSelf(facePoints[faceIndexB]);
  16490. avg.addSelf(originalPoints[edgeVertexA].position);
  16491. avg.addSelf(originalPoints[edgeVertexB].position);
  16492. avg.multiplyScalar(0.25);
  16493. }
  16494. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  16495. //console.log(edgePoints[i], newPoints.length);
  16496. newPoints.push( new THREE.Vertex(avg) );
  16497. edgeCount ++;
  16498. if (!scope.supportUVs || uvForVertices.length==0) continue;
  16499. // Prepare subdivided uv
  16500. avgUv = new THREE.UV();
  16501. avgUv.u = uvForVertices[edgeVertexA].u + uvForVertices[edgeVertexB].u;
  16502. avgUv.v = uvForVertices[edgeVertexA].v + uvForVertices[edgeVertexB].v;
  16503. avgUv.u /= 2;
  16504. avgUv.v /= 2;
  16505. uvForVertices.push(avgUv);
  16506. }
  16507. // Step 3
  16508. // For each face point, add an edge for every edge of the face,
  16509. // connecting the face point to each edge point for the face.
  16510. var facePt, currentVerticeIndex;
  16511. var hashAB, hashBC, hashCD, hashDA, hashCA;
  16512. var abc123 = ['123', '12', '2', '23'];
  16513. var bca123 = ['123', '23', '3', '31'];
  16514. var cab123 = ['123', '31', '1', '12'];
  16515. var abc1234 = ['1234', '12', '2', '23'];
  16516. var bcd1234 = ['1234', '23', '3', '34'];
  16517. var cda1234 = ['1234', '34', '4', '41'];
  16518. var dab1234 = ['1234', '41', '1', '12'];
  16519. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  16520. facePt = facePoints[i];
  16521. face = originalFaces[i];
  16522. currentVerticeIndex = originalVerticesLength+ i;
  16523. if ( face instanceof THREE.Face3 ) {
  16524. // create 3 face4s
  16525. hashAB = edge_hash( face.a, face.b );
  16526. hashBC = edge_hash( face.b, face.c );
  16527. hashCA = edge_hash( face.c, face.a );
  16528. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123 );
  16529. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123 );
  16530. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123 );
  16531. } else if ( face instanceof THREE.Face4 ) {
  16532. // create 4 face4s
  16533. hashAB = edge_hash( face.a, face.b );
  16534. hashBC = edge_hash( face.b, face.c );
  16535. hashCD = edge_hash( face.c, face.d );
  16536. hashDA = edge_hash( face.d, face.a );
  16537. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234 );
  16538. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234 );
  16539. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234 );
  16540. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234 );
  16541. } else {
  16542. console.log('face should be a face!', face);
  16543. }
  16544. }
  16545. newVertices = newPoints;
  16546. // console.log('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  16547. // console.log('new points', newPoints.length, 'faces', newFaces.length );
  16548. // Step 4
  16549. // For each original point P,
  16550. // take the average F of all n face points for faces touching P,
  16551. // and take the average R of all n edge midpoints for edges touching P,
  16552. // where each edge midpoint is the average of its two endpoint vertices.
  16553. // Move each original point to the point
  16554. var F = new THREE.Vector3();
  16555. var R = new THREE.Vector3();
  16556. var n;
  16557. for (i=0, il = originalPoints.length; i<il; i++) {
  16558. // (F + 2R + (n-3)P) / n
  16559. if (vertexEdgeMap[i]===undefined) continue;
  16560. F.set(0,0,0);
  16561. R.set(0,0,0);
  16562. var newPos = new THREE.Vector3(0,0,0);
  16563. var f =0;
  16564. for (j in vertexFaceMap[i]) {
  16565. F.addSelf(facePoints[j]);
  16566. f++;
  16567. }
  16568. var sharpEdgeCount = 0;
  16569. n = vertexEdgeMap[i].length;
  16570. for (j=0;j<n;j++) {
  16571. if (
  16572. sharpEdges[
  16573. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  16574. ]) {
  16575. sharpEdgeCount++;
  16576. }
  16577. }
  16578. if ( sharpEdgeCount==2 ) {
  16579. continue;
  16580. // Do not move vertex if there's 2 connecting sharp edges.
  16581. }
  16582. /*
  16583. if (sharpEdgeCount>2) {
  16584. // TODO
  16585. }
  16586. */
  16587. F.divideScalar(f);
  16588. for (j=0; j<n;j++) {
  16589. edge = vertexEdgeMap[i][j];
  16590. var midPt = originalPoints[edge[0]].position.clone().addSelf(originalPoints[edge[1]].position).divideScalar(2);
  16591. R.addSelf(midPt);
  16592. // R.addSelf(originalPoints[edge[0]].position);
  16593. // R.addSelf(originalPoints[edge[1]].position);
  16594. }
  16595. R.divideScalar(n)
  16596. newPos.addSelf(originalPoints[i].position);
  16597. newPos.multiplyScalar(n - 3);
  16598. newPos.addSelf(F);
  16599. newPos.addSelf(R.multiplyScalar(2));
  16600. newPos.divideScalar(n);
  16601. newVertices[i].position = newPos;
  16602. }
  16603. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  16604. newGeometry.vertices = newVertices;
  16605. newGeometry.faces = newFaces;
  16606. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  16607. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  16608. newGeometry.computeCentroids();
  16609. newGeometry.computeFaceNormals();
  16610. newGeometry.computeVertexNormals();
  16611. };
  16612. /**
  16613. * @author alteredq / http://alteredqualia.com/
  16614. */
  16615. THREE.Loader = function ( showStatus ) {
  16616. this.showStatus = showStatus;
  16617. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  16618. this.onLoadStart = function () {};
  16619. this.onLoadProgress = function() {};
  16620. this.onLoadComplete = function () {};
  16621. };
  16622. THREE.Loader.prototype = {
  16623. constructor: THREE.Loader,
  16624. crossOrigin: 'anonymous',
  16625. addStatusElement: function () {
  16626. var e = document.createElement( "div" );
  16627. e.style.position = "absolute";
  16628. e.style.right = "0px";
  16629. e.style.top = "0px";
  16630. e.style.fontSize = "0.8em";
  16631. e.style.textAlign = "left";
  16632. e.style.background = "rgba(0,0,0,0.25)";
  16633. e.style.color = "#fff";
  16634. e.style.width = "120px";
  16635. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  16636. e.style.zIndex = 1000;
  16637. e.innerHTML = "Loading ...";
  16638. return e;
  16639. },
  16640. updateProgress: function ( progress ) {
  16641. var message = "Loaded ";
  16642. if ( progress.total ) {
  16643. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  16644. } else {
  16645. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  16646. }
  16647. this.statusDomElement.innerHTML = message;
  16648. },
  16649. extractUrlBase: function ( url ) {
  16650. var parts = url.split( '/' );
  16651. parts.pop();
  16652. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  16653. },
  16654. initMaterials: function ( scope, materials, texturePath ) {
  16655. scope.materials = [];
  16656. for ( var i = 0; i < materials.length; ++ i ) {
  16657. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  16658. }
  16659. },
  16660. hasNormals: function ( scope ) {
  16661. var m, i, il = scope.materials.length;
  16662. for( i = 0; i < il; i ++ ) {
  16663. m = scope.materials[ i ];
  16664. if ( m instanceof THREE.ShaderMaterial ) return true;
  16665. }
  16666. return false;
  16667. },
  16668. createMaterial: function ( m, texturePath ) {
  16669. var _this = this;
  16670. function is_pow2( n ) {
  16671. var l = Math.log( n ) / Math.LN2;
  16672. return Math.floor( l ) == l;
  16673. }
  16674. function nearest_pow2( n ) {
  16675. var l = Math.log( n ) / Math.LN2;
  16676. return Math.pow( 2, Math.round( l ) );
  16677. }
  16678. function load_image( where, url ) {
  16679. var image = new Image();
  16680. image.onload = function () {
  16681. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  16682. var width = nearest_pow2( this.width );
  16683. var height = nearest_pow2( this.height );
  16684. where.image.width = width;
  16685. where.image.height = height;
  16686. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  16687. } else {
  16688. where.image = this;
  16689. }
  16690. where.needsUpdate = true;
  16691. };
  16692. image.crossOrigin = _this.crossOrigin;
  16693. image.src = url;
  16694. }
  16695. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  16696. var texture = document.createElement( 'canvas' );
  16697. where[ name ] = new THREE.Texture( texture );
  16698. where[ name ].sourceFile = sourceFile;
  16699. if( repeat ) {
  16700. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  16701. if ( repeat[ 0 ] != 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  16702. if ( repeat[ 1 ] != 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  16703. }
  16704. if ( offset ) {
  16705. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  16706. }
  16707. if ( wrap ) {
  16708. var wrapMap = {
  16709. "repeat" : THREE.RepeatWrapping,
  16710. "mirror" : THREE.MirroredRepeatWrapping
  16711. }
  16712. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  16713. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  16714. }
  16715. load_image( where[ name ], texturePath + "/" + sourceFile );
  16716. }
  16717. function rgb2hex( rgb ) {
  16718. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  16719. }
  16720. // defaults
  16721. var mtype = "MeshLambertMaterial";
  16722. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, wireframe: m.wireframe };
  16723. // parameters from model file
  16724. if ( m.shading ) {
  16725. var shading = m.shading.toLowerCase();
  16726. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  16727. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  16728. }
  16729. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  16730. mpars.blending = THREE[ m.blending ];
  16731. }
  16732. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  16733. mpars.transparent = m.transparent;
  16734. }
  16735. if ( m.depthTest !== undefined ) {
  16736. mpars.depthTest = m.depthTest;
  16737. }
  16738. if ( m.depthWrite !== undefined ) {
  16739. mpars.depthWrite = m.depthWrite;
  16740. }
  16741. if ( m.vertexColors !== undefined ) {
  16742. if ( m.vertexColors == "face" ) {
  16743. mpars.vertexColors = THREE.FaceColors;
  16744. } else if ( m.vertexColors ) {
  16745. mpars.vertexColors = THREE.VertexColors;
  16746. }
  16747. }
  16748. // colors
  16749. if ( m.colorDiffuse ) {
  16750. mpars.color = rgb2hex( m.colorDiffuse );
  16751. } else if ( m.DbgColor ) {
  16752. mpars.color = m.DbgColor;
  16753. }
  16754. if ( m.colorSpecular ) {
  16755. mpars.specular = rgb2hex( m.colorSpecular );
  16756. }
  16757. if ( m.colorAmbient ) {
  16758. mpars.ambient = rgb2hex( m.colorAmbient );
  16759. }
  16760. // modifiers
  16761. if ( m.transparency ) {
  16762. mpars.opacity = m.transparency;
  16763. }
  16764. if ( m.specularCoef ) {
  16765. mpars.shininess = m.specularCoef;
  16766. }
  16767. // textures
  16768. if ( m.mapDiffuse && texturePath ) {
  16769. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  16770. }
  16771. if ( m.mapLight && texturePath ) {
  16772. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  16773. }
  16774. if ( m.mapNormal && texturePath ) {
  16775. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  16776. }
  16777. if ( m.mapSpecular && texturePath ) {
  16778. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  16779. }
  16780. // special case for normal mapped material
  16781. if ( m.mapNormal ) {
  16782. var shader = THREE.ShaderUtils.lib[ "normal" ];
  16783. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  16784. uniforms[ "tNormal" ].texture = mpars.normalMap;
  16785. if ( m.mapNormalFactor ) {
  16786. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  16787. }
  16788. if ( mpars.map ) {
  16789. uniforms[ "tDiffuse" ].texture = mpars.map;
  16790. uniforms[ "enableDiffuse" ].value = true;
  16791. }
  16792. if ( mpars.specularMap ) {
  16793. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  16794. uniforms[ "enableSpecular" ].value = true;
  16795. }
  16796. if ( mpars.lightMap ) {
  16797. uniforms[ "tAO" ].texture = mpars.lightMap;
  16798. uniforms[ "enableAO" ].value = true;
  16799. }
  16800. // for the moment don't handle displacement texture
  16801. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  16802. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  16803. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  16804. uniforms[ "uShininess" ].value = mpars.shininess;
  16805. if ( mpars.opacity !== undefined ) {
  16806. uniforms[ "uOpacity" ].value = mpars.opacity;
  16807. }
  16808. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  16809. var material = new THREE.ShaderMaterial( parameters );
  16810. } else {
  16811. var material = new THREE[ mtype ]( mpars );
  16812. }
  16813. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  16814. return material;
  16815. }
  16816. };
  16817. /**
  16818. * @author alteredq / http://alteredqualia.com/
  16819. */
  16820. THREE.BinaryLoader = function ( showStatus ) {
  16821. THREE.Loader.call( this, showStatus );
  16822. };
  16823. THREE.BinaryLoader.prototype = new THREE.Loader();
  16824. THREE.BinaryLoader.prototype.constructor = THREE.BinaryLoader;
  16825. THREE.BinaryLoader.prototype.supr = THREE.Loader.prototype;
  16826. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  16827. // - binary models consist of two files: JS and BIN
  16828. // - parameters
  16829. // - url (required)
  16830. // - callback (required)
  16831. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  16832. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  16833. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  16834. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  16835. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  16836. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  16837. this.onLoadStart();
  16838. // #1 load JS part via web worker
  16839. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  16840. };
  16841. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  16842. var xhr = new XMLHttpRequest();
  16843. xhr.onreadystatechange = function () {
  16844. if ( xhr.readyState == 4 ) {
  16845. if ( xhr.status == 200 || xhr.status == 0 ) {
  16846. var json = JSON.parse( xhr.responseText );
  16847. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  16848. } else {
  16849. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  16850. }
  16851. }
  16852. };
  16853. xhr.open( "GET", url, true );
  16854. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  16855. xhr.setRequestHeader( "Content-Type", "text/plain" );
  16856. xhr.send( null );
  16857. };
  16858. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  16859. var xhr = new XMLHttpRequest(),
  16860. url = binaryPath + "/" + json.buffers;
  16861. var length = 0;
  16862. xhr.onreadystatechange = function () {
  16863. if ( xhr.readyState == 4 ) {
  16864. if ( xhr.status == 200 || xhr.status == 0 ) {
  16865. THREE.BinaryLoader.prototype.createBinModel( xhr.response, callback, texturePath, json.materials );
  16866. } else {
  16867. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  16868. }
  16869. } else if ( xhr.readyState == 3 ) {
  16870. if ( callbackProgress ) {
  16871. if ( length == 0 ) {
  16872. length = xhr.getResponseHeader( "Content-Length" );
  16873. }
  16874. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  16875. }
  16876. } else if ( xhr.readyState == 2 ) {
  16877. length = xhr.getResponseHeader( "Content-Length" );
  16878. }
  16879. };
  16880. xhr.open( "GET", url, true );
  16881. xhr.responseType = "arraybuffer";
  16882. xhr.send( null );
  16883. };
  16884. // Binary AJAX parser
  16885. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  16886. var Model = function ( texturePath ) {
  16887. var scope = this,
  16888. currentOffset = 0,
  16889. md,
  16890. normals = [],
  16891. uvs = [],
  16892. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  16893. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  16894. tri_size, quad_size,
  16895. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  16896. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  16897. THREE.Geometry.call( this );
  16898. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  16899. md = parseMetaData( data, currentOffset );
  16900. currentOffset += md.header_bytes;
  16901. /*
  16902. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16903. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  16904. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16905. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  16906. */
  16907. // buffers sizes
  16908. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  16909. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  16910. len_tri_flat = md.ntri_flat * ( tri_size );
  16911. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  16912. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  16913. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  16914. len_quad_flat = md.nquad_flat * ( quad_size );
  16915. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  16916. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  16917. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  16918. // read buffers
  16919. currentOffset += init_vertices( currentOffset );
  16920. currentOffset += init_normals( currentOffset );
  16921. currentOffset += handlePadding( md.nnormals * 3 );
  16922. currentOffset += init_uvs( currentOffset );
  16923. start_tri_flat = currentOffset;
  16924. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  16925. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  16926. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  16927. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  16928. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  16929. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  16930. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  16931. // have to first process faces with uvs
  16932. // so that face and uv indices match
  16933. init_triangles_flat_uv( start_tri_flat_uv );
  16934. init_triangles_smooth_uv( start_tri_smooth_uv );
  16935. init_quads_flat_uv( start_quad_flat_uv );
  16936. init_quads_smooth_uv( start_quad_smooth_uv );
  16937. // now we can process untextured faces
  16938. init_triangles_flat( start_tri_flat );
  16939. init_triangles_smooth( start_tri_smooth );
  16940. init_quads_flat( start_quad_flat );
  16941. init_quads_smooth( start_quad_smooth );
  16942. this.computeCentroids();
  16943. this.computeFaceNormals();
  16944. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  16945. function handlePadding( n ) {
  16946. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  16947. };
  16948. function parseMetaData( data, offset ) {
  16949. var metaData = {
  16950. 'signature' :parseString( data, offset, 12 ),
  16951. 'header_bytes' :parseUChar8( data, offset + 12 ),
  16952. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  16953. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  16954. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  16955. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  16956. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  16957. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  16958. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  16959. 'nvertices' :parseUInt32( data, offset + 20 ),
  16960. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  16961. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  16962. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  16963. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  16964. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  16965. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  16966. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  16967. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  16968. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  16969. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  16970. };
  16971. /*
  16972. console.log( "signature: " + metaData.signature );
  16973. console.log( "header_bytes: " + metaData.header_bytes );
  16974. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  16975. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  16976. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  16977. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  16978. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  16979. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  16980. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  16981. console.log( "nvertices: " + metaData.nvertices );
  16982. console.log( "nnormals: " + metaData.nnormals );
  16983. console.log( "nuvs: " + metaData.nuvs );
  16984. console.log( "ntri_flat: " + metaData.ntri_flat );
  16985. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  16986. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  16987. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  16988. console.log( "nquad_flat: " + metaData.nquad_flat );
  16989. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  16990. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  16991. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  16992. var total = metaData.header_bytes
  16993. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  16994. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  16995. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  16996. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  16997. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  16998. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  16999. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  17000. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  17001. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  17002. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  17003. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  17004. console.log( "total bytes: " + total );
  17005. */
  17006. return metaData;
  17007. };
  17008. function parseString( data, offset, length ) {
  17009. var charArray = new Uint8Array( data, offset, length );
  17010. var text = "";
  17011. for ( var i = 0; i < length; i ++ ) {
  17012. text += String.fromCharCode( charArray[ offset + i ] );
  17013. }
  17014. return text;
  17015. };
  17016. function parseUChar8( data, offset ) {
  17017. var charArray = new Uint8Array( data, offset, 1 );
  17018. return charArray[ 0 ];
  17019. };
  17020. function parseUInt32( data, offset ) {
  17021. var intArray = new Uint32Array( data, offset, 1 );
  17022. return intArray[ 0 ];
  17023. };
  17024. function init_vertices( start ) {
  17025. var nElements = md.nvertices;
  17026. var coordArray = new Float32Array( data, start, nElements * 3 );
  17027. var i, x, y, z;
  17028. for( i = 0; i < nElements; i ++ ) {
  17029. x = coordArray[ i * 3 ];
  17030. y = coordArray[ i * 3 + 1 ];
  17031. z = coordArray[ i * 3 + 2 ];
  17032. vertex( scope, x, y, z );
  17033. }
  17034. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  17035. };
  17036. function init_normals( start ) {
  17037. var nElements = md.nnormals;
  17038. if ( nElements ) {
  17039. var normalArray = new Int8Array( data, start, nElements * 3 );
  17040. var i, x, y, z;
  17041. for( i = 0; i < nElements; i ++ ) {
  17042. x = normalArray[ i * 3 ];
  17043. y = normalArray[ i * 3 + 1 ];
  17044. z = normalArray[ i * 3 + 2 ];
  17045. normals.push( x/127, y/127, z/127 );
  17046. }
  17047. }
  17048. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  17049. };
  17050. function init_uvs( start ) {
  17051. var nElements = md.nuvs;
  17052. if ( nElements ) {
  17053. var uvArray = new Float32Array( data, start, nElements * 2 );
  17054. var i, u, v;
  17055. for( i = 0; i < nElements; i ++ ) {
  17056. u = uvArray[ i * 2 ];
  17057. v = uvArray[ i * 2 + 1 ];
  17058. uvs.push( u, v );
  17059. }
  17060. }
  17061. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  17062. };
  17063. function init_uvs3( nElements, offset ) {
  17064. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  17065. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  17066. for( i = 0; i < nElements; i ++ ) {
  17067. uva = uvIndexBuffer[ i * 3 ];
  17068. uvb = uvIndexBuffer[ i * 3 + 1 ];
  17069. uvc = uvIndexBuffer[ i * 3 + 2 ];
  17070. u1 = uvs[ uva*2 ];
  17071. v1 = uvs[ uva*2 + 1 ];
  17072. u2 = uvs[ uvb*2 ];
  17073. v2 = uvs[ uvb*2 + 1 ];
  17074. u3 = uvs[ uvc*2 ];
  17075. v3 = uvs[ uvc*2 + 1 ];
  17076. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  17077. }
  17078. };
  17079. function init_uvs4( nElements, offset ) {
  17080. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  17081. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  17082. for( i = 0; i < nElements; i ++ ) {
  17083. uva = uvIndexBuffer[ i * 4 ];
  17084. uvb = uvIndexBuffer[ i * 4 + 1 ];
  17085. uvc = uvIndexBuffer[ i * 4 + 2 ];
  17086. uvd = uvIndexBuffer[ i * 4 + 3 ];
  17087. u1 = uvs[ uva*2 ];
  17088. v1 = uvs[ uva*2 + 1 ];
  17089. u2 = uvs[ uvb*2 ];
  17090. v2 = uvs[ uvb*2 + 1 ];
  17091. u3 = uvs[ uvc*2 ];
  17092. v3 = uvs[ uvc*2 + 1 ];
  17093. u4 = uvs[ uvd*2 ];
  17094. v4 = uvs[ uvd*2 + 1 ];
  17095. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  17096. }
  17097. };
  17098. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  17099. var i, a, b, c, m;
  17100. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  17101. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17102. for( i = 0; i < nElements; i ++ ) {
  17103. a = vertexIndexBuffer[ i * 3 ];
  17104. b = vertexIndexBuffer[ i * 3 + 1 ];
  17105. c = vertexIndexBuffer[ i * 3 + 2 ];
  17106. m = materialIndexBuffer[ i ];
  17107. f3( scope, a, b, c, m );
  17108. }
  17109. };
  17110. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  17111. var i, a, b, c, d, m;
  17112. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  17113. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17114. for( i = 0; i < nElements; i ++ ) {
  17115. a = vertexIndexBuffer[ i * 4 ];
  17116. b = vertexIndexBuffer[ i * 4 + 1 ];
  17117. c = vertexIndexBuffer[ i * 4 + 2 ];
  17118. d = vertexIndexBuffer[ i * 4 + 3 ];
  17119. m = materialIndexBuffer[ i ];
  17120. f4( scope, a, b, c, d, m );
  17121. }
  17122. };
  17123. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  17124. var i, a, b, c, m;
  17125. var na, nb, nc;
  17126. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  17127. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  17128. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17129. for( i = 0; i < nElements; i ++ ) {
  17130. a = vertexIndexBuffer[ i * 3 ];
  17131. b = vertexIndexBuffer[ i * 3 + 1 ];
  17132. c = vertexIndexBuffer[ i * 3 + 2 ];
  17133. na = normalIndexBuffer[ i * 3 ];
  17134. nb = normalIndexBuffer[ i * 3 + 1 ];
  17135. nc = normalIndexBuffer[ i * 3 + 2 ];
  17136. m = materialIndexBuffer[ i ];
  17137. f3n( scope, normals, a, b, c, m, na, nb, nc );
  17138. }
  17139. };
  17140. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  17141. var i, a, b, c, d, m;
  17142. var na, nb, nc, nd;
  17143. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  17144. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  17145. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  17146. for( i = 0; i < nElements; i ++ ) {
  17147. a = vertexIndexBuffer[ i * 4 ];
  17148. b = vertexIndexBuffer[ i * 4 + 1 ];
  17149. c = vertexIndexBuffer[ i * 4 + 2 ];
  17150. d = vertexIndexBuffer[ i * 4 + 3 ];
  17151. na = normalIndexBuffer[ i * 4 ];
  17152. nb = normalIndexBuffer[ i * 4 + 1 ];
  17153. nc = normalIndexBuffer[ i * 4 + 2 ];
  17154. nd = normalIndexBuffer[ i * 4 + 3 ];
  17155. m = materialIndexBuffer[ i ];
  17156. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  17157. }
  17158. };
  17159. function init_triangles_flat( start ) {
  17160. var nElements = md.ntri_flat;
  17161. if ( nElements ) {
  17162. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17163. init_faces3_flat( nElements, start, offsetMaterials );
  17164. }
  17165. };
  17166. function init_triangles_flat_uv( start ) {
  17167. var nElements = md.ntri_flat_uv;
  17168. if ( nElements ) {
  17169. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17170. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17171. init_faces3_flat( nElements, start, offsetMaterials );
  17172. init_uvs3( nElements, offsetUvs );
  17173. }
  17174. };
  17175. function init_triangles_smooth( start ) {
  17176. var nElements = md.ntri_smooth;
  17177. if ( nElements ) {
  17178. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17179. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17180. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  17181. }
  17182. };
  17183. function init_triangles_smooth_uv( start ) {
  17184. var nElements = md.ntri_smooth_uv;
  17185. if ( nElements ) {
  17186. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17187. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17188. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  17189. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  17190. init_uvs3( nElements, offsetUvs );
  17191. }
  17192. };
  17193. function init_quads_flat( start ) {
  17194. var nElements = md.nquad_flat;
  17195. if ( nElements ) {
  17196. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17197. init_faces4_flat( nElements, start, offsetMaterials );
  17198. }
  17199. };
  17200. function init_quads_flat_uv( start ) {
  17201. var nElements = md.nquad_flat_uv;
  17202. if ( nElements ) {
  17203. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17204. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17205. init_faces4_flat( nElements, start, offsetMaterials );
  17206. init_uvs4( nElements, offsetUvs );
  17207. }
  17208. };
  17209. function init_quads_smooth( start ) {
  17210. var nElements = md.nquad_smooth;
  17211. if ( nElements ) {
  17212. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17213. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17214. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  17215. }
  17216. };
  17217. function init_quads_smooth_uv( start ) {
  17218. var nElements = md.nquad_smooth_uv;
  17219. if ( nElements ) {
  17220. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17221. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17222. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  17223. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  17224. init_uvs4( nElements, offsetUvs );
  17225. }
  17226. };
  17227. };
  17228. function vertex ( scope, x, y, z ) {
  17229. scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  17230. };
  17231. function f3 ( scope, a, b, c, mi ) {
  17232. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  17233. };
  17234. function f4 ( scope, a, b, c, d, mi ) {
  17235. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  17236. };
  17237. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  17238. var nax = normals[ na*3 ],
  17239. nay = normals[ na*3 + 1 ],
  17240. naz = normals[ na*3 + 2 ],
  17241. nbx = normals[ nb*3 ],
  17242. nby = normals[ nb*3 + 1 ],
  17243. nbz = normals[ nb*3 + 2 ],
  17244. ncx = normals[ nc*3 ],
  17245. ncy = normals[ nc*3 + 1 ],
  17246. ncz = normals[ nc*3 + 2 ];
  17247. scope.faces.push( new THREE.Face3( a, b, c,
  17248. [new THREE.Vector3( nax, nay, naz ),
  17249. new THREE.Vector3( nbx, nby, nbz ),
  17250. new THREE.Vector3( ncx, ncy, ncz )],
  17251. null,
  17252. mi ) );
  17253. };
  17254. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  17255. var nax = normals[ na*3 ],
  17256. nay = normals[ na*3 + 1 ],
  17257. naz = normals[ na*3 + 2 ],
  17258. nbx = normals[ nb*3 ],
  17259. nby = normals[ nb*3 + 1 ],
  17260. nbz = normals[ nb*3 + 2 ],
  17261. ncx = normals[ nc*3 ],
  17262. ncy = normals[ nc*3 + 1 ],
  17263. ncz = normals[ nc*3 + 2 ],
  17264. ndx = normals[ nd*3 ],
  17265. ndy = normals[ nd*3 + 1 ],
  17266. ndz = normals[ nd*3 + 2 ];
  17267. scope.faces.push( new THREE.Face4( a, b, c, d,
  17268. [new THREE.Vector3( nax, nay, naz ),
  17269. new THREE.Vector3( nbx, nby, nbz ),
  17270. new THREE.Vector3( ncx, ncy, ncz ),
  17271. new THREE.Vector3( ndx, ndy, ndz )],
  17272. null,
  17273. mi ) );
  17274. };
  17275. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  17276. var uv = [];
  17277. uv.push( new THREE.UV( u1, v1 ) );
  17278. uv.push( new THREE.UV( u2, v2 ) );
  17279. uv.push( new THREE.UV( u3, v3 ) );
  17280. where.push( uv );
  17281. };
  17282. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  17283. var uv = [];
  17284. uv.push( new THREE.UV( u1, v1 ) );
  17285. uv.push( new THREE.UV( u2, v2 ) );
  17286. uv.push( new THREE.UV( u3, v3 ) );
  17287. uv.push( new THREE.UV( u4, v4 ) );
  17288. where.push( uv );
  17289. };
  17290. Model.prototype = new THREE.Geometry();
  17291. Model.prototype.constructor = Model;
  17292. callback( new Model( texturePath ) );
  17293. };
  17294. /**
  17295. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  17296. */
  17297. THREE.ColladaLoader = function () {
  17298. var COLLADA = null;
  17299. var scene = null;
  17300. var daeScene;
  17301. var readyCallbackFunc = null;
  17302. var sources = {};
  17303. var images = {};
  17304. var animations = {};
  17305. var controllers = {};
  17306. var geometries = {};
  17307. var materials = {};
  17308. var effects = {};
  17309. var cameras = {};
  17310. var animData;
  17311. var visualScenes;
  17312. var baseUrl;
  17313. var morphs;
  17314. var skins;
  17315. var flip_uv = true;
  17316. var preferredShading = THREE.SmoothShading;
  17317. var options = {
  17318. // Force Geometry to always be centered at the local origin of the
  17319. // containing Mesh.
  17320. centerGeometry: false,
  17321. // Axis conversion is done for geometries, animations, and controllers.
  17322. // If we ever pull cameras or lights out of the COLLADA file, they'll
  17323. // need extra work.
  17324. convertUpAxis: false,
  17325. subdivideFaces: true,
  17326. upAxis: 'Y'
  17327. };
  17328. // TODO: support unit conversion as well
  17329. var colladaUnit = 1.0;
  17330. var colladaUp = 'Y';
  17331. var upConversion = null;
  17332. var TO_RADIANS = Math.PI / 180;
  17333. function load ( url, readyCallback, progressCallback ) {
  17334. var length = 0;
  17335. if ( document.implementation && document.implementation.createDocument ) {
  17336. var req = new XMLHttpRequest();
  17337. if ( req.overrideMimeType ) req.overrideMimeType( "text/xml" );
  17338. req.onreadystatechange = function() {
  17339. if( req.readyState == 4 ) {
  17340. if( req.status == 0 || req.status == 200 ) {
  17341. if ( req.responseXML ) {
  17342. readyCallbackFunc = readyCallback;
  17343. parse( req.responseXML, undefined, url );
  17344. } else {
  17345. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  17346. }
  17347. }
  17348. } else if ( req.readyState == 3 ) {
  17349. if ( progressCallback ) {
  17350. if ( length == 0 ) {
  17351. length = req.getResponseHeader( "Content-Length" );
  17352. }
  17353. progressCallback( { total: length, loaded: req.responseText.length } );
  17354. }
  17355. }
  17356. }
  17357. req.open( "GET", url, true );
  17358. req.send( null );
  17359. } else {
  17360. alert( "Don't know how to parse XML!" );
  17361. }
  17362. };
  17363. function parse( doc, callBack, url ) {
  17364. COLLADA = doc;
  17365. callBack = callBack || readyCallbackFunc;
  17366. if ( url !== undefined ) {
  17367. var parts = url.split( '/' );
  17368. parts.pop();
  17369. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  17370. }
  17371. parseAsset();
  17372. setUpConversion();
  17373. images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
  17374. materials = parseLib( "//dae:library_materials/dae:material", Material, "material") ;
  17375. effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
  17376. geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
  17377. cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
  17378. controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
  17379. animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
  17380. visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
  17381. morphs = [];
  17382. skins = [];
  17383. daeScene = parseScene();
  17384. scene = new THREE.Object3D();
  17385. for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
  17386. scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
  17387. }
  17388. createAnimations();
  17389. var result = {
  17390. scene: scene,
  17391. morphs: morphs,
  17392. skins: skins,
  17393. animations: animData,
  17394. dae: {
  17395. images: images,
  17396. materials: materials,
  17397. cameras: cameras,
  17398. effects: effects,
  17399. geometries: geometries,
  17400. controllers: controllers,
  17401. animations: animations,
  17402. visualScenes: visualScenes,
  17403. scene: daeScene
  17404. }
  17405. };
  17406. if ( callBack ) {
  17407. callBack( result );
  17408. }
  17409. return result;
  17410. };
  17411. function setPreferredShading ( shading ) {
  17412. preferredShading = shading;
  17413. };
  17414. function parseAsset () {
  17415. var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  17416. var element = elements.iterateNext();
  17417. if ( element && element.childNodes ) {
  17418. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  17419. var child = element.childNodes[ i ];
  17420. switch ( child.nodeName ) {
  17421. case 'unit':
  17422. var meter = child.getAttribute( 'meter' );
  17423. if ( meter ) {
  17424. colladaUnit = parseFloat( meter );
  17425. }
  17426. break;
  17427. case 'up_axis':
  17428. colladaUp = child.textContent.charAt(0);
  17429. break;
  17430. }
  17431. }
  17432. }
  17433. };
  17434. function parseLib ( q, classSpec, prefix ) {
  17435. var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
  17436. var lib = {};
  17437. var element = elements.iterateNext();
  17438. var i = 0;
  17439. while ( element ) {
  17440. var daeElement = ( new classSpec() ).parse( element );
  17441. if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
  17442. lib[ daeElement.id ] = daeElement;
  17443. element = elements.iterateNext();
  17444. }
  17445. return lib;
  17446. };
  17447. function parseScene() {
  17448. var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  17449. if ( sceneElement ) {
  17450. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  17451. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  17452. } else {
  17453. return null;
  17454. }
  17455. };
  17456. function createAnimations() {
  17457. animData = [];
  17458. // fill in the keys
  17459. recurseHierarchy( scene );
  17460. };
  17461. function recurseHierarchy( node ) {
  17462. var n = daeScene.getChildById( node.name, true ),
  17463. newData = null;
  17464. if ( n && n.keys ) {
  17465. newData = {
  17466. fps: 60,
  17467. hierarchy: [ {
  17468. node: n,
  17469. keys: n.keys,
  17470. sids: n.sids
  17471. } ],
  17472. node: node,
  17473. name: 'animation_' + node.name,
  17474. length: 0
  17475. };
  17476. animData.push(newData);
  17477. for ( var i = 0, il = n.keys.length; i < il; i++ ) {
  17478. newData.length = Math.max( newData.length, n.keys[i].time );
  17479. }
  17480. } else {
  17481. newData = {
  17482. hierarchy: [ {
  17483. keys: [],
  17484. sids: []
  17485. } ]
  17486. }
  17487. }
  17488. for ( var i = 0, il = node.children.length; i < il; i++ ) {
  17489. var d = recurseHierarchy( node.children[i] );
  17490. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  17491. newData.hierarchy.push( {
  17492. keys: [],
  17493. sids: []
  17494. } );
  17495. }
  17496. }
  17497. return newData;
  17498. };
  17499. function calcAnimationBounds () {
  17500. var start = 1000000;
  17501. var end = -start;
  17502. var frames = 0;
  17503. for ( var id in animations ) {
  17504. var animation = animations[ id ];
  17505. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  17506. var sampler = animation.sampler[ i ];
  17507. sampler.create();
  17508. start = Math.min( start, sampler.startTime );
  17509. end = Math.max( end, sampler.endTime );
  17510. frames = Math.max( frames, sampler.input.length );
  17511. }
  17512. }
  17513. return { start:start, end:end, frames:frames };
  17514. };
  17515. function createMorph ( geometry, ctrl ) {
  17516. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  17517. if ( !morphCtrl || !morphCtrl.morph ) {
  17518. console.log("could not find morph controller!");
  17519. return;
  17520. }
  17521. var morph = morphCtrl.morph;
  17522. for ( var i = 0; i < morph.targets.length; i ++ ) {
  17523. var target_id = morph.targets[ i ];
  17524. var daeGeometry = geometries[ target_id ];
  17525. if ( !daeGeometry.mesh ||
  17526. !daeGeometry.mesh.primitives ||
  17527. !daeGeometry.mesh.primitives.length ) {
  17528. continue;
  17529. }
  17530. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  17531. if ( target.vertices.length === geometry.vertices.length ) {
  17532. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  17533. }
  17534. }
  17535. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  17536. };
  17537. function createSkin ( geometry, ctrl, applyBindShape ) {
  17538. var skinCtrl = controllers[ ctrl.url ];
  17539. if ( !skinCtrl || !skinCtrl.skin ) {
  17540. console.log( "could not find skin controller!" );
  17541. return;
  17542. }
  17543. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  17544. console.log( "could not find the skeleton for the skin!" );
  17545. return;
  17546. }
  17547. var skin = skinCtrl.skin;
  17548. var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
  17549. var hierarchy = [];
  17550. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  17551. var bones = [];
  17552. geometry.skinWeights = [];
  17553. geometry.skinIndices = [];
  17554. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  17555. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  17556. /*
  17557. geometry.animation = {
  17558. name: 'take_001',
  17559. fps: 30,
  17560. length: 2,
  17561. JIT: true,
  17562. hierarchy: hierarchy
  17563. };
  17564. */
  17565. if ( applyBindShape ) {
  17566. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  17567. skin.bindShapeMatrix.multiplyVector3( geometry.vertices[ i ].position );
  17568. }
  17569. }
  17570. };
  17571. function setupSkeleton ( node, bones, frame, parent ) {
  17572. node.world = node.world || new THREE.Matrix4();
  17573. node.world.copy( node.matrix );
  17574. if ( node.channels && node.channels.length ) {
  17575. var channel = node.channels[ 0 ];
  17576. var m = channel.sampler.output[ frame ];
  17577. if ( m instanceof THREE.Matrix4 ) {
  17578. node.world.copy( m );
  17579. }
  17580. }
  17581. if ( parent ) {
  17582. node.world.multiply( parent, node.world );
  17583. }
  17584. bones.push( node );
  17585. for ( var i = 0; i < node.nodes.length; i ++ ) {
  17586. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  17587. }
  17588. };
  17589. function setupSkinningMatrices ( bones, skin ) {
  17590. // FIXME: this is dumb...
  17591. for ( var i = 0; i < bones.length; i ++ ) {
  17592. var bone = bones[ i ];
  17593. var found = -1;
  17594. if ( bone.type != 'JOINT' ) continue;
  17595. for ( var j = 0; j < skin.joints.length; j ++ ) {
  17596. if ( bone.sid == skin.joints[ j ] ) {
  17597. found = j;
  17598. break;
  17599. }
  17600. }
  17601. if ( found >= 0 ) {
  17602. var inv = skin.invBindMatrices[ found ];
  17603. bone.invBindMatrix = inv;
  17604. bone.skinningMatrix = new THREE.Matrix4();
  17605. bone.skinningMatrix.multiply(bone.world, inv); // (IBMi * JMi)
  17606. bone.weights = [];
  17607. for ( var j = 0; j < skin.weights.length; j ++ ) {
  17608. for (var k = 0; k < skin.weights[ j ].length; k ++) {
  17609. var w = skin.weights[ j ][ k ];
  17610. if ( w.joint == found ) {
  17611. bone.weights.push( w );
  17612. }
  17613. }
  17614. }
  17615. } else {
  17616. throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
  17617. }
  17618. }
  17619. };
  17620. function applySkin ( geometry, instanceCtrl, frame ) {
  17621. var skinController = controllers[ instanceCtrl.url ];
  17622. frame = frame !== undefined ? frame : 40;
  17623. if ( !skinController || !skinController.skin ) {
  17624. console.log( 'ColladaLoader: Could not find skin controller.' );
  17625. return;
  17626. }
  17627. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  17628. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  17629. return;
  17630. }
  17631. var animationBounds = calcAnimationBounds();
  17632. var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
  17633. daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
  17634. var i, j, w, vidx, weight;
  17635. var v = new THREE.Vector3(), o, s;
  17636. // move vertices to bind shape
  17637. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  17638. skinController.skin.bindShapeMatrix.multiplyVector3( geometry.vertices[i].position );
  17639. }
  17640. // process animation, or simply pose the rig if no animation
  17641. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  17642. var bones = [];
  17643. var skinned = [];
  17644. // zero skinned vertices
  17645. for ( i = 0; i < geometry.vertices.length; i++ ) {
  17646. skinned.push( new THREE.Vertex( new THREE.Vector3() ) );
  17647. }
  17648. // process the frame and setup the rig with a fresh
  17649. // transform, possibly from the bone's animation channel(s)
  17650. setupSkeleton( skeleton, bones, frame );
  17651. setupSkinningMatrices( bones, skinController.skin );
  17652. // skin 'm
  17653. for ( i = 0; i < bones.length; i ++ ) {
  17654. if ( bones[ i ].type != 'JOINT' ) continue;
  17655. for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
  17656. w = bones[ i ].weights[ j ];
  17657. vidx = w.index;
  17658. weight = w.weight;
  17659. o = geometry.vertices[vidx];
  17660. s = skinned[vidx];
  17661. v.x = o.position.x;
  17662. v.y = o.position.y;
  17663. v.z = o.position.z;
  17664. bones[i].skinningMatrix.multiplyVector3(v);
  17665. s.position.x += (v.x * weight);
  17666. s.position.y += (v.y * weight);
  17667. s.position.z += (v.z * weight);
  17668. }
  17669. }
  17670. geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
  17671. }
  17672. };
  17673. function createSceneGraph ( node, parent ) {
  17674. var obj = new THREE.Object3D();
  17675. var skinned = false;
  17676. var skinController;
  17677. var morphController;
  17678. var i, j;
  17679. // FIXME: controllers
  17680. for ( i = 0; i < node.controllers.length; i ++ ) {
  17681. var controller = controllers[ node.controllers[ i ].url ];
  17682. switch ( controller.type ) {
  17683. case 'skin':
  17684. if ( geometries[ controller.skin.source ] ) {
  17685. var inst_geom = new InstanceGeometry();
  17686. inst_geom.url = controller.skin.source;
  17687. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17688. node.geometries.push( inst_geom );
  17689. skinned = true;
  17690. skinController = node.controllers[ i ];
  17691. } else if ( controllers[ controller.skin.source ] ) {
  17692. // urgh: controller can be chained
  17693. // handle the most basic case...
  17694. var second = controllers[ controller.skin.source ];
  17695. morphController = second;
  17696. // skinController = node.controllers[i];
  17697. if ( second.morph && geometries[ second.morph.source ] ) {
  17698. var inst_geom = new InstanceGeometry();
  17699. inst_geom.url = second.morph.source;
  17700. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17701. node.geometries.push( inst_geom );
  17702. }
  17703. }
  17704. break;
  17705. case 'morph':
  17706. if ( geometries[ controller.morph.source ] ) {
  17707. var inst_geom = new InstanceGeometry();
  17708. inst_geom.url = controller.morph.source;
  17709. inst_geom.instance_material = node.controllers[ i ].instance_material;
  17710. node.geometries.push( inst_geom );
  17711. morphController = node.controllers[ i ];
  17712. }
  17713. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  17714. default:
  17715. break;
  17716. }
  17717. }
  17718. // FIXME: multi-material mesh?
  17719. // geometries
  17720. for ( i = 0; i < node.geometries.length; i ++ ) {
  17721. var instance_geometry = node.geometries[i];
  17722. var instance_materials = instance_geometry.instance_material;
  17723. var geometry = geometries[instance_geometry.url];
  17724. var used_materials = {};
  17725. var used_materials_array = [];
  17726. var num_materials = 0;
  17727. var first_material;
  17728. if ( geometry ) {
  17729. if ( !geometry.mesh || !geometry.mesh.primitives )
  17730. continue;
  17731. if ( obj.name.length == 0 ) {
  17732. obj.name = geometry.id;
  17733. }
  17734. // collect used fx for this geometry-instance
  17735. if ( instance_materials ) {
  17736. for ( j = 0; j < instance_materials.length; j ++ ) {
  17737. var instance_material = instance_materials[ j ];
  17738. var mat = materials[ instance_material.target ];
  17739. var effect_id = mat.instance_effect.url;
  17740. var shader = effects[ effect_id ].shader;
  17741. shader.material.opacity = !shader.material.opacity ? 1 : shader.material.opacity;
  17742. used_materials[ instance_material.symbol ] = num_materials;
  17743. used_materials_array.push( shader.material )
  17744. first_material = shader.material;
  17745. first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
  17746. num_materials ++;
  17747. }
  17748. }
  17749. var mesh;
  17750. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading } );
  17751. var geom = geometry.mesh.geometry3js;
  17752. if ( num_materials > 1 ) {
  17753. material = new THREE.MeshFaceMaterial();
  17754. geom.materials = used_materials_array;
  17755. for ( j = 0; j < geom.faces.length; j ++ ) {
  17756. var face = geom.faces[ j ];
  17757. face.materialIndex = used_materials[ face.daeMaterial ]
  17758. }
  17759. }
  17760. if ( skinController !== undefined) {
  17761. applySkin( geom, skinController );
  17762. material.morphTargets = true;
  17763. mesh = new THREE.SkinnedMesh( geom, material );
  17764. mesh.skeleton = skinController.skeleton;
  17765. mesh.skinController = controllers[ skinController.url ];
  17766. mesh.skinInstanceController = skinController;
  17767. mesh.name = 'skin_' + skins.length;
  17768. skins.push( mesh );
  17769. } else if ( morphController !== undefined ) {
  17770. createMorph( geom, morphController );
  17771. material.morphTargets = true;
  17772. mesh = new THREE.Mesh( geom, material );
  17773. mesh.name = 'morph_' + morphs.length;
  17774. morphs.push( mesh );
  17775. } else {
  17776. mesh = new THREE.Mesh( geom, material );
  17777. // mesh.geom.name = geometry.id;
  17778. }
  17779. node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
  17780. }
  17781. }
  17782. for ( i = 0; i < node.cameras.length; i ++ ) {
  17783. var instance_camera = node.cameras[i];
  17784. var cparams = cameras[instance_camera.url];
  17785. obj = new THREE.PerspectiveCamera(cparams.fov, cparams.aspect_ratio, cparams.znear, cparams.zfar);
  17786. }
  17787. obj.name = node.id || "";
  17788. obj.matrix = node.matrix;
  17789. var props = node.matrix.decompose();
  17790. obj.position = props[ 0 ];
  17791. obj.quaternion = props[ 1 ];
  17792. obj.useQuaternion = true;
  17793. obj.scale = props[ 2 ];
  17794. if ( options.centerGeometry && obj.geometry ) {
  17795. var delta = THREE.GeometryUtils.center( obj.geometry );
  17796. obj.quaternion.multiplyVector3( delta.multiplySelf( obj.scale ) );
  17797. obj.position.subSelf( delta );
  17798. }
  17799. for ( i = 0; i < node.nodes.length; i ++ ) {
  17800. obj.add( createSceneGraph( node.nodes[i], node ) );
  17801. }
  17802. return obj;
  17803. };
  17804. function getJointId( skin, id ) {
  17805. for ( var i = 0; i < skin.joints.length; i ++ ) {
  17806. if ( skin.joints[ i ] == id ) {
  17807. return i;
  17808. }
  17809. }
  17810. };
  17811. function getLibraryNode( id ) {
  17812. return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  17813. };
  17814. function getChannelsForNode (node ) {
  17815. var channels = [];
  17816. var startTime = 1000000;
  17817. var endTime = -1000000;
  17818. for ( var id in animations ) {
  17819. var animation = animations[id];
  17820. for ( var i = 0; i < animation.channel.length; i ++ ) {
  17821. var channel = animation.channel[i];
  17822. var sampler = animation.sampler[i];
  17823. var id = channel.target.split('/')[0];
  17824. if ( id == node.id ) {
  17825. sampler.create();
  17826. channel.sampler = sampler;
  17827. startTime = Math.min(startTime, sampler.startTime);
  17828. endTime = Math.max(endTime, sampler.endTime);
  17829. channels.push(channel);
  17830. }
  17831. }
  17832. }
  17833. if ( channels.length ) {
  17834. node.startTime = startTime;
  17835. node.endTime = endTime;
  17836. }
  17837. return channels;
  17838. };
  17839. function calcFrameDuration( node ) {
  17840. var minT = 10000000;
  17841. for ( var i = 0; i < node.channels.length; i ++ ) {
  17842. var sampler = node.channels[i].sampler;
  17843. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  17844. var t0 = sampler.input[ j ];
  17845. var t1 = sampler.input[ j + 1 ];
  17846. minT = Math.min( minT, t1 - t0 );
  17847. }
  17848. }
  17849. return minT;
  17850. };
  17851. function calcMatrixAt( node, t ) {
  17852. var animated = {};
  17853. var i, j;
  17854. for ( i = 0; i < node.channels.length; i ++ ) {
  17855. var channel = node.channels[ i ];
  17856. animated[ channel.sid ] = channel;
  17857. }
  17858. var matrix = new THREE.Matrix4();
  17859. for ( i = 0; i < node.transforms.length; i ++ ) {
  17860. var transform = node.transforms[ i ];
  17861. var channel = animated[ transform.sid ];
  17862. if ( channel !== undefined ) {
  17863. var sampler = channel.sampler;
  17864. var value;
  17865. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  17866. if ( sampler.input[ j + 1 ] > t ) {
  17867. value = sampler.output[ j ];
  17868. //console.log(value.flatten)
  17869. break;
  17870. }
  17871. }
  17872. if ( value !== undefined ) {
  17873. if ( value instanceof THREE.Matrix4 ) {
  17874. matrix = matrix.multiply( matrix, value );
  17875. } else {
  17876. // FIXME: handle other types
  17877. matrix = matrix.multiply( matrix, transform.matrix );
  17878. }
  17879. } else {
  17880. matrix = matrix.multiply( matrix, transform.matrix );
  17881. }
  17882. } else {
  17883. matrix = matrix.multiply( matrix, transform.matrix );
  17884. }
  17885. }
  17886. return matrix;
  17887. };
  17888. function bakeAnimations ( node ) {
  17889. if ( node.channels && node.channels.length ) {
  17890. var keys = [],
  17891. sids = [];
  17892. for ( var i = 0, il = node.channels.length; i < il; i++ ) {
  17893. var channel = node.channels[i],
  17894. fullSid = channel.fullSid,
  17895. member = getConvertedMember( channel.member ),
  17896. sampler = channel.sampler,
  17897. input = sampler.input,
  17898. transform = node.getTransformBySid( channel.sid );
  17899. if ( transform ) {
  17900. if ( sids.indexOf( fullSid ) === -1 ) {
  17901. sids.push( fullSid );
  17902. }
  17903. for ( var j = 0, jl = input.length; j < jl; j++ ) {
  17904. var time = input[j],
  17905. data = sampler.getData( transform.type, j ),
  17906. key = findKey( keys, time );
  17907. if ( !key ) {
  17908. key = new Key( time );
  17909. var timeNdx = findTimeNdx( keys, time );
  17910. keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
  17911. }
  17912. key.addTarget( fullSid, transform, member, data );
  17913. }
  17914. } else {
  17915. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  17916. }
  17917. }
  17918. // post process
  17919. for ( var i = 0; i < sids.length; i++ ) {
  17920. var sid = sids[ i ];
  17921. for ( var j = 0; j < keys.length; j++ ) {
  17922. var key = keys[ j ];
  17923. if ( !key.hasTarget( sid ) ) {
  17924. interpolateKeys( keys, key, j, sid );
  17925. }
  17926. }
  17927. }
  17928. node.keys = keys;
  17929. node.sids = sids;
  17930. }
  17931. };
  17932. function findKey ( keys, time) {
  17933. var retVal = null;
  17934. for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
  17935. var key = keys[i];
  17936. if ( key.time === time ) {
  17937. retVal = key;
  17938. } else if ( key.time > time ) {
  17939. break;
  17940. }
  17941. }
  17942. return retVal;
  17943. };
  17944. function findTimeNdx ( keys, time) {
  17945. var ndx = -1;
  17946. for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
  17947. var key = keys[i];
  17948. if ( key.time >= time ) {
  17949. ndx = i;
  17950. }
  17951. }
  17952. return ndx;
  17953. };
  17954. function interpolateKeys ( keys, key, ndx, fullSid ) {
  17955. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
  17956. nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
  17957. if ( prevKey && nextKey ) {
  17958. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  17959. prevTarget = prevKey.getTarget( fullSid ),
  17960. nextData = nextKey.getTarget( fullSid ).data,
  17961. prevData = prevTarget.data,
  17962. data;
  17963. if ( prevData.length ) {
  17964. data = [];
  17965. for ( var i = 0; i < prevData.length; ++i ) {
  17966. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  17967. }
  17968. } else {
  17969. data = prevData + ( nextData - prevData ) * scale;
  17970. }
  17971. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  17972. }
  17973. };
  17974. // Get next key with given sid
  17975. function getNextKeyWith( keys, fullSid, ndx ) {
  17976. for ( ; ndx < keys.length; ndx++ ) {
  17977. var key = keys[ ndx ];
  17978. if ( key.hasTarget( fullSid ) ) {
  17979. return key;
  17980. }
  17981. }
  17982. return null;
  17983. };
  17984. // Get previous key with given sid
  17985. function getPrevKeyWith( keys, fullSid, ndx ) {
  17986. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  17987. for ( ; ndx >= 0; ndx-- ) {
  17988. var key = keys[ ndx ];
  17989. if ( key.hasTarget( fullSid ) ) {
  17990. return key;
  17991. }
  17992. }
  17993. return null;
  17994. };
  17995. function _Image() {
  17996. this.id = "";
  17997. this.init_from = "";
  17998. };
  17999. _Image.prototype.parse = function(element) {
  18000. this.id = element.getAttribute('id');
  18001. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18002. var child = element.childNodes[ i ];
  18003. if ( child.nodeName == 'init_from' ) {
  18004. this.init_from = child.textContent;
  18005. }
  18006. }
  18007. return this;
  18008. };
  18009. function Controller() {
  18010. this.id = "";
  18011. this.name = "";
  18012. this.type = "";
  18013. this.skin = null;
  18014. this.morph = null;
  18015. };
  18016. Controller.prototype.parse = function( element ) {
  18017. this.id = element.getAttribute('id');
  18018. this.name = element.getAttribute('name');
  18019. this.type = "none";
  18020. for ( var i = 0; i < element.childNodes.length; i++ ) {
  18021. var child = element.childNodes[ i ];
  18022. switch ( child.nodeName ) {
  18023. case 'skin':
  18024. this.skin = (new Skin()).parse(child);
  18025. this.type = child.nodeName;
  18026. break;
  18027. case 'morph':
  18028. this.morph = (new Morph()).parse(child);
  18029. this.type = child.nodeName;
  18030. break;
  18031. default:
  18032. break;
  18033. }
  18034. }
  18035. return this;
  18036. };
  18037. function Morph() {
  18038. this.method = null;
  18039. this.source = null;
  18040. this.targets = null;
  18041. this.weights = null;
  18042. };
  18043. Morph.prototype.parse = function( element ) {
  18044. var sources = {};
  18045. var inputs = [];
  18046. var i;
  18047. this.method = element.getAttribute( 'method' );
  18048. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  18049. for ( i = 0; i < element.childNodes.length; i ++ ) {
  18050. var child = element.childNodes[ i ];
  18051. if ( child.nodeType != 1 ) continue;
  18052. switch ( child.nodeName ) {
  18053. case 'source':
  18054. var source = ( new Source() ).parse( child );
  18055. sources[ source.id ] = source;
  18056. break;
  18057. case 'targets':
  18058. inputs = this.parseInputs( child );
  18059. break;
  18060. default:
  18061. console.log( child.nodeName );
  18062. break;
  18063. }
  18064. }
  18065. for ( i = 0; i < inputs.length; i ++ ) {
  18066. var input = inputs[ i ];
  18067. var source = sources[ input.source ];
  18068. switch ( input.semantic ) {
  18069. case 'MORPH_TARGET':
  18070. this.targets = source.read();
  18071. break;
  18072. case 'MORPH_WEIGHT':
  18073. this.weights = source.read();
  18074. break;
  18075. default:
  18076. break;
  18077. }
  18078. }
  18079. return this;
  18080. };
  18081. Morph.prototype.parseInputs = function(element) {
  18082. var inputs = [];
  18083. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18084. var child = element.childNodes[i];
  18085. if ( child.nodeType != 1) continue;
  18086. switch ( child.nodeName ) {
  18087. case 'input':
  18088. inputs.push( (new Input()).parse(child) );
  18089. break;
  18090. default:
  18091. break;
  18092. }
  18093. }
  18094. return inputs;
  18095. };
  18096. function Skin() {
  18097. this.source = "";
  18098. this.bindShapeMatrix = null;
  18099. this.invBindMatrices = [];
  18100. this.joints = [];
  18101. this.weights = [];
  18102. };
  18103. Skin.prototype.parse = function( element ) {
  18104. var sources = {};
  18105. var joints, weights;
  18106. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  18107. this.invBindMatrices = [];
  18108. this.joints = [];
  18109. this.weights = [];
  18110. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18111. var child = element.childNodes[i];
  18112. if ( child.nodeType != 1 ) continue;
  18113. switch ( child.nodeName ) {
  18114. case 'bind_shape_matrix':
  18115. var f = _floats(child.textContent);
  18116. this.bindShapeMatrix = getConvertedMat4( f );
  18117. break;
  18118. case 'source':
  18119. var src = new Source().parse(child);
  18120. sources[ src.id ] = src;
  18121. break;
  18122. case 'joints':
  18123. joints = child;
  18124. break;
  18125. case 'vertex_weights':
  18126. weights = child;
  18127. break;
  18128. default:
  18129. console.log( child.nodeName );
  18130. break;
  18131. }
  18132. }
  18133. this.parseJoints( joints, sources );
  18134. this.parseWeights( weights, sources );
  18135. return this;
  18136. };
  18137. Skin.prototype.parseJoints = function ( element, sources ) {
  18138. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18139. var child = element.childNodes[ i ];
  18140. if ( child.nodeType != 1 ) continue;
  18141. switch ( child.nodeName ) {
  18142. case 'input':
  18143. var input = ( new Input() ).parse( child );
  18144. var source = sources[ input.source ];
  18145. if ( input.semantic == 'JOINT' ) {
  18146. this.joints = source.read();
  18147. } else if ( input.semantic == 'INV_BIND_MATRIX' ) {
  18148. this.invBindMatrices = source.read();
  18149. }
  18150. break;
  18151. default:
  18152. break;
  18153. }
  18154. }
  18155. };
  18156. Skin.prototype.parseWeights = function ( element, sources ) {
  18157. var v, vcount, inputs = [];
  18158. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18159. var child = element.childNodes[ i ];
  18160. if ( child.nodeType != 1 ) continue;
  18161. switch ( child.nodeName ) {
  18162. case 'input':
  18163. inputs.push( ( new Input() ).parse( child ) );
  18164. break;
  18165. case 'v':
  18166. v = _ints( child.textContent );
  18167. break;
  18168. case 'vcount':
  18169. vcount = _ints( child.textContent );
  18170. break;
  18171. default:
  18172. break;
  18173. }
  18174. }
  18175. var index = 0;
  18176. for ( var i = 0; i < vcount.length; i ++ ) {
  18177. var numBones = vcount[i];
  18178. var vertex_weights = [];
  18179. for ( var j = 0; j < numBones; j++ ) {
  18180. var influence = {};
  18181. for ( var k = 0; k < inputs.length; k ++ ) {
  18182. var input = inputs[ k ];
  18183. var value = v[ index + input.offset ];
  18184. switch ( input.semantic ) {
  18185. case 'JOINT':
  18186. influence.joint = value;//this.joints[value];
  18187. break;
  18188. case 'WEIGHT':
  18189. influence.weight = sources[ input.source ].data[ value ];
  18190. break;
  18191. default:
  18192. break;
  18193. }
  18194. }
  18195. vertex_weights.push( influence );
  18196. index += inputs.length;
  18197. }
  18198. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  18199. vertex_weights[ j ].index = i;
  18200. }
  18201. this.weights.push( vertex_weights );
  18202. }
  18203. };
  18204. function VisualScene () {
  18205. this.id = "";
  18206. this.name = "";
  18207. this.nodes = [];
  18208. this.scene = new THREE.Object3D();
  18209. };
  18210. VisualScene.prototype.getChildById = function( id, recursive ) {
  18211. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18212. var node = this.nodes[ i ].getChildById( id, recursive );
  18213. if ( node ) {
  18214. return node;
  18215. }
  18216. }
  18217. return null;
  18218. };
  18219. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  18220. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18221. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  18222. if ( node ) {
  18223. return node;
  18224. }
  18225. }
  18226. return null;
  18227. };
  18228. VisualScene.prototype.parse = function( element ) {
  18229. this.id = element.getAttribute( 'id' );
  18230. this.name = element.getAttribute( 'name' );
  18231. this.nodes = [];
  18232. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18233. var child = element.childNodes[ i ];
  18234. if ( child.nodeType != 1 ) continue;
  18235. switch ( child.nodeName ) {
  18236. case 'node':
  18237. this.nodes.push( ( new Node() ).parse( child ) );
  18238. break;
  18239. default:
  18240. break;
  18241. }
  18242. }
  18243. return this;
  18244. };
  18245. function Node() {
  18246. this.id = "";
  18247. this.name = "";
  18248. this.sid = "";
  18249. this.nodes = [];
  18250. this.controllers = [];
  18251. this.transforms = [];
  18252. this.geometries = [];
  18253. this.channels = [];
  18254. this.matrix = new THREE.Matrix4();
  18255. };
  18256. Node.prototype.getChannelForTransform = function( transformSid ) {
  18257. for ( var i = 0; i < this.channels.length; i ++ ) {
  18258. var channel = this.channels[i];
  18259. var parts = channel.target.split('/');
  18260. var id = parts.shift();
  18261. var sid = parts.shift();
  18262. var dotSyntax = (sid.indexOf(".") >= 0);
  18263. var arrSyntax = (sid.indexOf("(") >= 0);
  18264. var arrIndices;
  18265. var member;
  18266. if ( dotSyntax ) {
  18267. parts = sid.split(".");
  18268. sid = parts.shift();
  18269. member = parts.shift();
  18270. } else if ( arrSyntax ) {
  18271. arrIndices = sid.split("(");
  18272. sid = arrIndices.shift();
  18273. for ( var j = 0; j < arrIndices.length; j ++ ) {
  18274. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  18275. }
  18276. }
  18277. if ( sid == transformSid ) {
  18278. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  18279. return channel;
  18280. }
  18281. }
  18282. return null;
  18283. };
  18284. Node.prototype.getChildById = function ( id, recursive ) {
  18285. if ( this.id == id ) {
  18286. return this;
  18287. }
  18288. if ( recursive ) {
  18289. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18290. var n = this.nodes[ i ].getChildById( id, recursive );
  18291. if ( n ) {
  18292. return n;
  18293. }
  18294. }
  18295. }
  18296. return null;
  18297. };
  18298. Node.prototype.getChildBySid = function ( sid, recursive ) {
  18299. if ( this.sid == sid ) {
  18300. return this;
  18301. }
  18302. if ( recursive ) {
  18303. for ( var i = 0; i < this.nodes.length; i ++ ) {
  18304. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  18305. if ( n ) {
  18306. return n;
  18307. }
  18308. }
  18309. }
  18310. return null;
  18311. };
  18312. Node.prototype.getTransformBySid = function ( sid ) {
  18313. for ( var i = 0; i < this.transforms.length; i ++ ) {
  18314. if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
  18315. }
  18316. return null;
  18317. };
  18318. Node.prototype.parse = function( element ) {
  18319. var url;
  18320. this.id = element.getAttribute('id');
  18321. this.sid = element.getAttribute('sid');
  18322. this.name = element.getAttribute('name');
  18323. this.type = element.getAttribute('type');
  18324. this.type = this.type == 'JOINT' ? this.type : 'NODE';
  18325. this.nodes = [];
  18326. this.transforms = [];
  18327. this.geometries = [];
  18328. this.cameras = [];
  18329. this.controllers = [];
  18330. this.matrix = new THREE.Matrix4();
  18331. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18332. var child = element.childNodes[ i ];
  18333. if ( child.nodeType != 1 ) continue;
  18334. switch ( child.nodeName ) {
  18335. case 'node':
  18336. this.nodes.push( ( new Node() ).parse( child ) );
  18337. break;
  18338. case 'instance_camera':
  18339. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  18340. break;
  18341. case 'instance_controller':
  18342. this.controllers.push( ( new InstanceController() ).parse( child ) );
  18343. break;
  18344. case 'instance_geometry':
  18345. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  18346. break;
  18347. case 'instance_light':
  18348. break;
  18349. case 'instance_node':
  18350. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  18351. var iNode = getLibraryNode( url );
  18352. if ( iNode ) {
  18353. this.nodes.push( ( new Node() ).parse( iNode )) ;
  18354. }
  18355. break;
  18356. case 'rotate':
  18357. case 'translate':
  18358. case 'scale':
  18359. case 'matrix':
  18360. case 'lookat':
  18361. case 'skew':
  18362. this.transforms.push( ( new Transform() ).parse( child ) );
  18363. break;
  18364. case 'extra':
  18365. break;
  18366. default:
  18367. console.log( child.nodeName );
  18368. break;
  18369. }
  18370. }
  18371. this.channels = getChannelsForNode( this );
  18372. bakeAnimations( this );
  18373. this.updateMatrix();
  18374. return this;
  18375. };
  18376. Node.prototype.updateMatrix = function () {
  18377. this.matrix.identity();
  18378. for ( var i = 0; i < this.transforms.length; i ++ ) {
  18379. this.transforms[ i ].apply( this.matrix );
  18380. }
  18381. };
  18382. function Transform () {
  18383. this.sid = "";
  18384. this.type = "";
  18385. this.data = [];
  18386. this.obj = null;
  18387. };
  18388. Transform.prototype.parse = function ( element ) {
  18389. this.sid = element.getAttribute( 'sid' );
  18390. this.type = element.nodeName;
  18391. this.data = _floats( element.textContent );
  18392. this.convert();
  18393. return this;
  18394. };
  18395. Transform.prototype.convert = function () {
  18396. switch ( this.type ) {
  18397. case 'matrix':
  18398. this.obj = getConvertedMat4( this.data );
  18399. break;
  18400. case 'rotate':
  18401. this.angle = this.data[3] * TO_RADIANS;
  18402. case 'translate':
  18403. fixCoords( this.data, -1 );
  18404. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  18405. break;
  18406. case 'scale':
  18407. fixCoords( this.data, 1 );
  18408. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  18409. break;
  18410. default:
  18411. console.log( 'Can not convert Transform of type ' + this.type );
  18412. break;
  18413. }
  18414. };
  18415. Transform.prototype.apply = function ( matrix ) {
  18416. switch ( this.type ) {
  18417. case 'matrix':
  18418. matrix.multiplySelf( this.obj );
  18419. break;
  18420. case 'translate':
  18421. matrix.translate( this.obj );
  18422. break;
  18423. case 'rotate':
  18424. matrix.rotateByAxis( this.obj, this.angle );
  18425. break;
  18426. case 'scale':
  18427. matrix.scale( this.obj );
  18428. break;
  18429. }
  18430. };
  18431. Transform.prototype.update = function ( data, member ) {
  18432. switch ( this.type ) {
  18433. case 'matrix':
  18434. console.log( 'Currently not handling matrix transform updates' );
  18435. break;
  18436. case 'translate':
  18437. case 'scale':
  18438. switch ( member ) {
  18439. case 'X':
  18440. this.obj.x = data;
  18441. break;
  18442. case 'Y':
  18443. this.obj.y = data;
  18444. break;
  18445. case 'Z':
  18446. this.obj.z = data;
  18447. break;
  18448. default:
  18449. this.obj.x = data[ 0 ];
  18450. this.obj.y = data[ 1 ];
  18451. this.obj.z = data[ 2 ];
  18452. break;
  18453. }
  18454. break;
  18455. case 'rotate':
  18456. switch ( member ) {
  18457. case 'X':
  18458. this.obj.x = data;
  18459. break;
  18460. case 'Y':
  18461. this.obj.y = data;
  18462. break;
  18463. case 'Z':
  18464. this.obj.z = data;
  18465. break;
  18466. case 'ANGLE':
  18467. this.angle = data * TO_RADIANS;
  18468. break;
  18469. default:
  18470. this.obj.x = data[ 0 ];
  18471. this.obj.y = data[ 1 ];
  18472. this.obj.z = data[ 2 ];
  18473. this.angle = data[ 3 ] * TO_RADIANS;
  18474. break;
  18475. }
  18476. break;
  18477. }
  18478. };
  18479. function InstanceController() {
  18480. this.url = "";
  18481. this.skeleton = [];
  18482. this.instance_material = [];
  18483. };
  18484. InstanceController.prototype.parse = function ( element ) {
  18485. this.url = element.getAttribute('url').replace(/^#/, '');
  18486. this.skeleton = [];
  18487. this.instance_material = [];
  18488. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18489. var child = element.childNodes[i];
  18490. if (child.nodeType != 1) continue;
  18491. switch ( child.nodeName ) {
  18492. case 'skeleton':
  18493. this.skeleton.push( child.textContent.replace(/^#/, '') );
  18494. break;
  18495. case 'bind_material':
  18496. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  18497. if ( instances ) {
  18498. var instance = instances.iterateNext();
  18499. while ( instance ) {
  18500. this.instance_material.push((new InstanceMaterial()).parse(instance));
  18501. instance = instances.iterateNext();
  18502. }
  18503. }
  18504. break;
  18505. case 'extra':
  18506. break;
  18507. default:
  18508. break;
  18509. }
  18510. }
  18511. return this;
  18512. };
  18513. function InstanceMaterial () {
  18514. this.symbol = "";
  18515. this.target = "";
  18516. };
  18517. InstanceMaterial.prototype.parse = function ( element ) {
  18518. this.symbol = element.getAttribute('symbol');
  18519. this.target = element.getAttribute('target').replace(/^#/, '');
  18520. return this;
  18521. };
  18522. function InstanceGeometry() {
  18523. this.url = "";
  18524. this.instance_material = [];
  18525. };
  18526. InstanceGeometry.prototype.parse = function ( element ) {
  18527. this.url = element.getAttribute('url').replace(/^#/, '');
  18528. this.instance_material = [];
  18529. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18530. var child = element.childNodes[i];
  18531. if ( child.nodeType != 1 ) continue;
  18532. if ( child.nodeName == 'bind_material' ) {
  18533. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  18534. if ( instances ) {
  18535. var instance = instances.iterateNext();
  18536. while ( instance ) {
  18537. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  18538. instance = instances.iterateNext();
  18539. }
  18540. }
  18541. break;
  18542. }
  18543. }
  18544. return this;
  18545. };
  18546. function Geometry() {
  18547. this.id = "";
  18548. this.mesh = null;
  18549. };
  18550. Geometry.prototype.parse = function ( element ) {
  18551. this.id = element.getAttribute('id');
  18552. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18553. var child = element.childNodes[i];
  18554. switch ( child.nodeName ) {
  18555. case 'mesh':
  18556. this.mesh = (new Mesh(this)).parse(child);
  18557. break;
  18558. case 'extra':
  18559. // console.log( child );
  18560. break;
  18561. default:
  18562. break;
  18563. }
  18564. }
  18565. return this;
  18566. };
  18567. function Mesh( geometry ) {
  18568. this.geometry = geometry.id;
  18569. this.primitives = [];
  18570. this.vertices = null;
  18571. this.geometry3js = null;
  18572. };
  18573. Mesh.prototype.parse = function( element ) {
  18574. this.primitives = [];
  18575. var i, j;
  18576. for ( i = 0; i < element.childNodes.length; i ++ ) {
  18577. var child = element.childNodes[ i ];
  18578. switch ( child.nodeName ) {
  18579. case 'source':
  18580. _source( child );
  18581. break;
  18582. case 'vertices':
  18583. this.vertices = ( new Vertices() ).parse( child );
  18584. break;
  18585. case 'triangles':
  18586. this.primitives.push( ( new Triangles().parse( child ) ) );
  18587. break;
  18588. case 'polygons':
  18589. this.primitives.push( ( new Polygons().parse( child ) ) );
  18590. break;
  18591. case 'polylist':
  18592. this.primitives.push( ( new Polylist().parse( child ) ) );
  18593. break;
  18594. default:
  18595. break;
  18596. }
  18597. }
  18598. this.geometry3js = new THREE.Geometry();
  18599. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  18600. for ( i = 0; i < vertexData.length; i += 3 ) {
  18601. var v = new THREE.Vertex( getConvertedVec3( vertexData, i ) );
  18602. this.geometry3js.vertices.push( v );
  18603. }
  18604. for ( i = 0; i < this.primitives.length; i ++ ) {
  18605. var primitive = this.primitives[ i ];
  18606. primitive.setVertices( this.vertices );
  18607. this.handlePrimitive( primitive, this.geometry3js );
  18608. }
  18609. this.geometry3js.computeCentroids();
  18610. this.geometry3js.computeFaceNormals();
  18611. if ( this.geometry3js.calcNormals ) {
  18612. this.geometry3js.computeVertexNormals();
  18613. delete this.geometry3js.calcNormals;
  18614. }
  18615. this.geometry3js.computeBoundingBox();
  18616. return this;
  18617. };
  18618. Mesh.prototype.handlePrimitive = function( primitive, geom ) {
  18619. var j, k, pList = primitive.p, inputs = primitive.inputs;
  18620. var input, index, idx32;
  18621. var source, numParams;
  18622. var vcIndex = 0, vcount = 3, maxOffset = 0;
  18623. var texture_sets = [];
  18624. for ( j = 0; j < inputs.length; j ++ ) {
  18625. input = inputs[ j ];
  18626. var offset = input.offset + 1;
  18627. maxOffset = (maxOffset < offset)? offset : maxOffset;
  18628. switch ( input.semantic ) {
  18629. case 'TEXCOORD':
  18630. texture_sets.push( input.set );
  18631. break;
  18632. }
  18633. }
  18634. for ( var pCount = 0; pCount < pList.length; ++pCount ) {
  18635. var p = pList[pCount], i = 0;
  18636. while ( i < p.length ) {
  18637. var vs = [];
  18638. var ns = [];
  18639. var ts = {};
  18640. var cs = [];
  18641. if ( primitive.vcount ) {
  18642. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  18643. } else {
  18644. vcount = p.length / maxOffset;
  18645. }
  18646. for ( j = 0; j < vcount; j ++ ) {
  18647. for ( k = 0; k < inputs.length; k ++ ) {
  18648. input = inputs[ k ];
  18649. source = sources[ input.source ];
  18650. index = p[ i + ( j * maxOffset ) + input.offset ];
  18651. numParams = source.accessor.params.length;
  18652. idx32 = index * numParams;
  18653. switch ( input.semantic ) {
  18654. case 'VERTEX':
  18655. vs.push( index );
  18656. break;
  18657. case 'NORMAL':
  18658. ns.push( getConvertedVec3( source.data, idx32 ) );
  18659. break;
  18660. case 'TEXCOORD':
  18661. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  18662. // invert the V
  18663. ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  18664. break;
  18665. case 'COLOR':
  18666. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  18667. break;
  18668. default:
  18669. break;
  18670. }
  18671. }
  18672. }
  18673. var face = null, faces = [], uv, uvArr;
  18674. if ( ns.length == 0 ) {
  18675. // check the vertices source
  18676. input = this.vertices.input.NORMAL;
  18677. if ( input ) {
  18678. source = sources[ input.source ];
  18679. numParams = source.accessor.params.length;
  18680. for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
  18681. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  18682. }
  18683. }
  18684. else {
  18685. geom.calcNormals = true;
  18686. }
  18687. }
  18688. if ( vcount === 3 ) {
  18689. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  18690. } else if ( vcount === 4 ) {
  18691. faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
  18692. } else if ( vcount > 4 && options.subdivideFaces ) {
  18693. var clr = cs.length ? cs : new THREE.Color(),
  18694. vec1, vec2, vec3, v1, v2, norm;
  18695. // subdivide into multiple Face3s
  18696. for ( k = 1; k < vcount-1; ) {
  18697. // FIXME: normals don't seem to be quite right
  18698. faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
  18699. }
  18700. }
  18701. if ( faces.length ) {
  18702. for (var ndx = 0, len = faces.length; ndx < len; ndx++) {
  18703. face = faces[ndx];
  18704. face.daeMaterial = primitive.material;
  18705. geom.faces.push( face );
  18706. for ( k = 0; k < texture_sets.length; k++ ) {
  18707. uv = ts[ texture_sets[k] ];
  18708. if ( vcount > 4 ) {
  18709. // Grab the right UVs for the vertices in this face
  18710. uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
  18711. } else if ( vcount === 4 ) {
  18712. uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
  18713. } else {
  18714. uvArr = [ uv[0], uv[1], uv[2] ];
  18715. }
  18716. if ( !geom.faceVertexUvs[k] ) {
  18717. geom.faceVertexUvs[k] = [];
  18718. }
  18719. geom.faceVertexUvs[k].push( uvArr );
  18720. }
  18721. }
  18722. } else {
  18723. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  18724. }
  18725. i += maxOffset * vcount;
  18726. }
  18727. }
  18728. };
  18729. function Polygons () {
  18730. this.material = "";
  18731. this.count = 0;
  18732. this.inputs = [];
  18733. this.vcount = null;
  18734. this.p = [];
  18735. this.geometry = new THREE.Geometry();
  18736. };
  18737. Polygons.prototype.setVertices = function ( vertices ) {
  18738. for ( var i = 0; i < this.inputs.length; i ++ ) {
  18739. if ( this.inputs[ i ].source == vertices.id ) {
  18740. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  18741. }
  18742. }
  18743. };
  18744. Polygons.prototype.parse = function ( element ) {
  18745. this.material = element.getAttribute( 'material' );
  18746. this.count = _attr_as_int( element, 'count', 0 );
  18747. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18748. var child = element.childNodes[ i ];
  18749. switch ( child.nodeName ) {
  18750. case 'input':
  18751. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  18752. break;
  18753. case 'vcount':
  18754. this.vcount = _ints( child.textContent );
  18755. break;
  18756. case 'p':
  18757. this.p.push( _ints( child.textContent ) );
  18758. break;
  18759. case 'ph':
  18760. console.warn( 'polygon holes not yet supported!' );
  18761. break;
  18762. default:
  18763. break;
  18764. }
  18765. }
  18766. return this;
  18767. };
  18768. function Polylist () {
  18769. Polygons.call( this );
  18770. this.vcount = [];
  18771. };
  18772. Polylist.prototype = new Polygons();
  18773. Polylist.prototype.constructor = Polylist;
  18774. function Triangles () {
  18775. Polygons.call( this );
  18776. this.vcount = 3;
  18777. };
  18778. Triangles.prototype = new Polygons();
  18779. Triangles.prototype.constructor = Triangles;
  18780. function Accessor() {
  18781. this.source = "";
  18782. this.count = 0;
  18783. this.stride = 0;
  18784. this.params = [];
  18785. };
  18786. Accessor.prototype.parse = function ( element ) {
  18787. this.params = [];
  18788. this.source = element.getAttribute( 'source' );
  18789. this.count = _attr_as_int( element, 'count', 0 );
  18790. this.stride = _attr_as_int( element, 'stride', 0 );
  18791. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18792. var child = element.childNodes[ i ];
  18793. if ( child.nodeName == 'param' ) {
  18794. var param = {};
  18795. param[ 'name' ] = child.getAttribute( 'name' );
  18796. param[ 'type' ] = child.getAttribute( 'type' );
  18797. this.params.push( param );
  18798. }
  18799. }
  18800. return this;
  18801. };
  18802. function Vertices() {
  18803. this.input = {};
  18804. };
  18805. Vertices.prototype.parse = function ( element ) {
  18806. this.id = element.getAttribute('id');
  18807. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18808. if ( element.childNodes[i].nodeName == 'input' ) {
  18809. var input = ( new Input() ).parse( element.childNodes[ i ] );
  18810. this.input[ input.semantic ] = input;
  18811. }
  18812. }
  18813. return this;
  18814. };
  18815. function Input () {
  18816. this.semantic = "";
  18817. this.offset = 0;
  18818. this.source = "";
  18819. this.set = 0;
  18820. };
  18821. Input.prototype.parse = function ( element ) {
  18822. this.semantic = element.getAttribute('semantic');
  18823. this.source = element.getAttribute('source').replace(/^#/, '');
  18824. this.set = _attr_as_int(element, 'set', -1);
  18825. this.offset = _attr_as_int(element, 'offset', 0);
  18826. if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
  18827. this.set = 0;
  18828. }
  18829. return this;
  18830. };
  18831. function Source ( id ) {
  18832. this.id = id;
  18833. this.type = null;
  18834. };
  18835. Source.prototype.parse = function ( element ) {
  18836. this.id = element.getAttribute( 'id' );
  18837. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18838. var child = element.childNodes[i];
  18839. switch ( child.nodeName ) {
  18840. case 'bool_array':
  18841. this.data = _bools( child.textContent );
  18842. this.type = child.nodeName;
  18843. break;
  18844. case 'float_array':
  18845. this.data = _floats( child.textContent );
  18846. this.type = child.nodeName;
  18847. break;
  18848. case 'int_array':
  18849. this.data = _ints( child.textContent );
  18850. this.type = child.nodeName;
  18851. break;
  18852. case 'IDREF_array':
  18853. case 'Name_array':
  18854. this.data = _strings( child.textContent );
  18855. this.type = child.nodeName;
  18856. break;
  18857. case 'technique_common':
  18858. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  18859. if ( child.childNodes[ j ].nodeName == 'accessor' ) {
  18860. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  18861. break;
  18862. }
  18863. }
  18864. break;
  18865. default:
  18866. // console.log(child.nodeName);
  18867. break;
  18868. }
  18869. }
  18870. return this;
  18871. };
  18872. Source.prototype.read = function () {
  18873. var result = [];
  18874. //for (var i = 0; i < this.accessor.params.length; i++) {
  18875. var param = this.accessor.params[ 0 ];
  18876. //console.log(param.name + " " + param.type);
  18877. switch ( param.type ) {
  18878. case 'IDREF':
  18879. case 'Name': case 'name':
  18880. case 'float':
  18881. return this.data;
  18882. case 'float4x4':
  18883. for ( var j = 0; j < this.data.length; j += 16 ) {
  18884. var s = this.data.slice( j, j + 16 );
  18885. var m = getConvertedMat4( s );
  18886. result.push( m );
  18887. }
  18888. break;
  18889. default:
  18890. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  18891. break;
  18892. }
  18893. //}
  18894. return result;
  18895. };
  18896. function Material () {
  18897. this.id = "";
  18898. this.name = "";
  18899. this.instance_effect = null;
  18900. };
  18901. Material.prototype.parse = function ( element ) {
  18902. this.id = element.getAttribute( 'id' );
  18903. this.name = element.getAttribute( 'name' );
  18904. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18905. if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
  18906. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  18907. break;
  18908. }
  18909. }
  18910. return this;
  18911. };
  18912. function ColorOrTexture () {
  18913. this.color = new THREE.Color( 0 );
  18914. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  18915. this.color.a = 1.0;
  18916. this.texture = null;
  18917. this.texcoord = null;
  18918. this.texOpts = null;
  18919. };
  18920. ColorOrTexture.prototype.isColor = function () {
  18921. return ( this.texture == null );
  18922. };
  18923. ColorOrTexture.prototype.isTexture = function () {
  18924. return ( this.texture != null );
  18925. };
  18926. ColorOrTexture.prototype.parse = function ( element ) {
  18927. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18928. var child = element.childNodes[ i ];
  18929. if ( child.nodeType != 1 ) continue;
  18930. switch ( child.nodeName ) {
  18931. case 'color':
  18932. var rgba = _floats( child.textContent );
  18933. this.color = new THREE.Color(0);
  18934. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  18935. this.color.a = rgba[3];
  18936. break;
  18937. case 'texture':
  18938. this.texture = child.getAttribute('texture');
  18939. this.texcoord = child.getAttribute('texcoord');
  18940. // Defaults from:
  18941. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  18942. this.texOpts = {
  18943. offsetU: 0,
  18944. offsetV: 0,
  18945. repeatU: 1,
  18946. repeatV: 1,
  18947. wrapU: 1,
  18948. wrapV: 1,
  18949. };
  18950. this.parseTexture( child );
  18951. break;
  18952. default:
  18953. break;
  18954. }
  18955. }
  18956. return this;
  18957. };
  18958. ColorOrTexture.prototype.parseTexture = function ( element ) {
  18959. if ( ! element.childNodes ) return this;
  18960. // This should be supported by Maya, 3dsMax, and MotionBuilder
  18961. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  18962. element = element.childNodes[1];
  18963. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  18964. element = element.childNodes[1];
  18965. }
  18966. }
  18967. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18968. var child = element.childNodes[ i ];
  18969. switch ( child.nodeName ) {
  18970. case 'offsetU':
  18971. case 'offsetV':
  18972. case 'repeatU':
  18973. case 'repeatV':
  18974. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  18975. break;
  18976. case 'wrapU':
  18977. case 'wrapV':
  18978. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  18979. break;
  18980. default:
  18981. this.texOpts[ child.nodeName ] = child.textContent;
  18982. break;
  18983. }
  18984. }
  18985. return this;
  18986. };
  18987. function Shader ( type, effect ) {
  18988. this.type = type;
  18989. this.effect = effect;
  18990. this.material = null;
  18991. };
  18992. Shader.prototype.parse = function ( element ) {
  18993. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  18994. var child = element.childNodes[ i ];
  18995. if ( child.nodeType != 1 ) continue;
  18996. switch ( child.nodeName ) {
  18997. case 'ambient':
  18998. case 'emission':
  18999. case 'diffuse':
  19000. case 'specular':
  19001. case 'transparent':
  19002. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  19003. break;
  19004. case 'shininess':
  19005. case 'reflectivity':
  19006. case 'transparency':
  19007. var f = evaluateXPath( child, './/dae:float' );
  19008. if ( f.length > 0 )
  19009. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  19010. break;
  19011. default:
  19012. break;
  19013. }
  19014. }
  19015. this.create();
  19016. return this;
  19017. };
  19018. Shader.prototype.create = function() {
  19019. var props = {};
  19020. var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
  19021. for ( var prop in this ) {
  19022. switch ( prop ) {
  19023. case 'ambient':
  19024. case 'emission':
  19025. case 'diffuse':
  19026. case 'specular':
  19027. var cot = this[prop];
  19028. if ( cot instanceof ColorOrTexture ) {
  19029. if ( cot.isTexture() ) {
  19030. if ( this.effect.sampler && this.effect.surface ) {
  19031. if ( this.effect.sampler.source == this.effect.surface.sid ) {
  19032. var image = images[this.effect.surface.init_from];
  19033. if ( image ) {
  19034. var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
  19035. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  19036. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  19037. texture.offset.x = cot.texOpts.offsetU;
  19038. texture.offset.y = cot.texOpts.offsetV;
  19039. texture.repeat.x = cot.texOpts.repeatU;
  19040. texture.repeat.y = cot.texOpts.repeatV;
  19041. props['map'] = texture;
  19042. }
  19043. }
  19044. }
  19045. } else if ( prop == 'diffuse' || !transparent ) {
  19046. props[ prop ] = cot.color.getHex();
  19047. }
  19048. }
  19049. break;
  19050. case 'shininess':
  19051. case 'reflectivity':
  19052. props[ prop ] = this[ prop ];
  19053. break;
  19054. case 'transparency':
  19055. if ( transparent ) {
  19056. props[ 'transparent' ] = true;
  19057. props[ 'opacity' ] = this[ prop ];
  19058. transparent = true;
  19059. }
  19060. break;
  19061. default:
  19062. break;
  19063. }
  19064. }
  19065. props[ 'shading' ] = preferredShading;
  19066. switch ( this.type ) {
  19067. case 'constant':
  19068. props.color = props.emission;
  19069. this.material = new THREE.MeshBasicMaterial( props );
  19070. break;
  19071. case 'phong':
  19072. case 'blinn':
  19073. props.color = props.diffuse;
  19074. this.material = new THREE.MeshPhongMaterial( props );
  19075. break;
  19076. case 'lambert':
  19077. default:
  19078. props.color = props.diffuse;
  19079. this.material = new THREE.MeshLambertMaterial( props );
  19080. break;
  19081. }
  19082. return this.material;
  19083. };
  19084. function Surface ( effect ) {
  19085. this.effect = effect;
  19086. this.init_from = null;
  19087. this.format = null;
  19088. };
  19089. Surface.prototype.parse = function ( element ) {
  19090. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19091. var child = element.childNodes[ i ];
  19092. if ( child.nodeType != 1 ) continue;
  19093. switch ( child.nodeName ) {
  19094. case 'init_from':
  19095. this.init_from = child.textContent;
  19096. break;
  19097. case 'format':
  19098. this.format = child.textContent;
  19099. break;
  19100. default:
  19101. console.log( "unhandled Surface prop: " + child.nodeName );
  19102. break;
  19103. }
  19104. }
  19105. return this;
  19106. };
  19107. function Sampler2D ( effect ) {
  19108. this.effect = effect;
  19109. this.source = null;
  19110. this.wrap_s = null;
  19111. this.wrap_t = null;
  19112. this.minfilter = null;
  19113. this.magfilter = null;
  19114. this.mipfilter = null;
  19115. };
  19116. Sampler2D.prototype.parse = function ( element ) {
  19117. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19118. var child = element.childNodes[ i ];
  19119. if ( child.nodeType != 1 ) continue;
  19120. switch ( child.nodeName ) {
  19121. case 'source':
  19122. this.source = child.textContent;
  19123. break;
  19124. case 'minfilter':
  19125. this.minfilter = child.textContent;
  19126. break;
  19127. case 'magfilter':
  19128. this.magfilter = child.textContent;
  19129. break;
  19130. case 'mipfilter':
  19131. this.mipfilter = child.textContent;
  19132. break;
  19133. case 'wrap_s':
  19134. this.wrap_s = child.textContent;
  19135. break;
  19136. case 'wrap_t':
  19137. this.wrap_t = child.textContent;
  19138. break;
  19139. default:
  19140. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  19141. break;
  19142. }
  19143. }
  19144. return this;
  19145. };
  19146. function Effect () {
  19147. this.id = "";
  19148. this.name = "";
  19149. this.shader = null;
  19150. this.surface = null;
  19151. this.sampler = null;
  19152. };
  19153. Effect.prototype.create = function () {
  19154. if ( this.shader == null ) {
  19155. return null;
  19156. }
  19157. };
  19158. Effect.prototype.parse = function ( element ) {
  19159. this.id = element.getAttribute( 'id' );
  19160. this.name = element.getAttribute( 'name' );
  19161. this.shader = null;
  19162. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19163. var child = element.childNodes[ i ];
  19164. if ( child.nodeType != 1 ) continue;
  19165. switch ( child.nodeName ) {
  19166. case 'profile_COMMON':
  19167. this.parseTechnique( this.parseProfileCOMMON( child ) );
  19168. break;
  19169. default:
  19170. break;
  19171. }
  19172. }
  19173. return this;
  19174. };
  19175. Effect.prototype.parseNewparam = function ( element ) {
  19176. var sid = element.getAttribute( 'sid' );
  19177. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19178. var child = element.childNodes[ i ];
  19179. if ( child.nodeType != 1 ) continue;
  19180. switch ( child.nodeName ) {
  19181. case 'surface':
  19182. this.surface = ( new Surface( this ) ).parse( child );
  19183. this.surface.sid = sid;
  19184. break;
  19185. case 'sampler2D':
  19186. this.sampler = ( new Sampler2D( this ) ).parse( child );
  19187. this.sampler.sid = sid;
  19188. break;
  19189. case 'extra':
  19190. break;
  19191. default:
  19192. console.log( child.nodeName );
  19193. break;
  19194. }
  19195. }
  19196. };
  19197. Effect.prototype.parseProfileCOMMON = function ( element ) {
  19198. var technique;
  19199. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19200. var child = element.childNodes[ i ];
  19201. if ( child.nodeType != 1 ) continue;
  19202. switch ( child.nodeName ) {
  19203. case 'profile_COMMON':
  19204. this.parseProfileCOMMON( child );
  19205. break;
  19206. case 'technique':
  19207. technique = child;
  19208. break;
  19209. case 'newparam':
  19210. this.parseNewparam( child );
  19211. break;
  19212. case 'image':
  19213. var _image = ( new _Image() ).parse( child );
  19214. images[ _image.id ] = _image;
  19215. break;
  19216. case 'extra':
  19217. break;
  19218. default:
  19219. console.log( child.nodeName );
  19220. break;
  19221. }
  19222. }
  19223. return technique;
  19224. };
  19225. Effect.prototype.parseTechnique= function ( element ) {
  19226. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19227. var child = element.childNodes[i];
  19228. if ( child.nodeType != 1 ) continue;
  19229. switch ( child.nodeName ) {
  19230. case 'constant':
  19231. case 'lambert':
  19232. case 'blinn':
  19233. case 'phong':
  19234. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  19235. break;
  19236. default:
  19237. break;
  19238. }
  19239. }
  19240. };
  19241. function InstanceEffect () {
  19242. this.url = "";
  19243. };
  19244. InstanceEffect.prototype.parse = function ( element ) {
  19245. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  19246. return this;
  19247. };
  19248. function Animation() {
  19249. this.id = "";
  19250. this.name = "";
  19251. this.source = {};
  19252. this.sampler = [];
  19253. this.channel = [];
  19254. };
  19255. Animation.prototype.parse = function ( element ) {
  19256. this.id = element.getAttribute( 'id' );
  19257. this.name = element.getAttribute( 'name' );
  19258. this.source = {};
  19259. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19260. var child = element.childNodes[ i ];
  19261. if ( child.nodeType != 1 ) continue;
  19262. switch ( child.nodeName ) {
  19263. case 'source':
  19264. var src = ( new Source() ).parse( child );
  19265. this.source[ src.id ] = src;
  19266. break;
  19267. case 'sampler':
  19268. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  19269. break;
  19270. case 'channel':
  19271. this.channel.push( ( new Channel( this ) ).parse( child ) );
  19272. break;
  19273. default:
  19274. break;
  19275. }
  19276. }
  19277. return this;
  19278. };
  19279. function Channel( animation ) {
  19280. this.animation = animation;
  19281. this.source = "";
  19282. this.target = "";
  19283. this.fullSid = null;
  19284. this.sid = null;
  19285. this.dotSyntax = null;
  19286. this.arrSyntax = null;
  19287. this.arrIndices = null;
  19288. this.member = null;
  19289. };
  19290. Channel.prototype.parse = function ( element ) {
  19291. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  19292. this.target = element.getAttribute( 'target' );
  19293. var parts = this.target.split( '/' );
  19294. var id = parts.shift();
  19295. var sid = parts.shift();
  19296. var dotSyntax = ( sid.indexOf(".") >= 0 );
  19297. var arrSyntax = ( sid.indexOf("(") >= 0 );
  19298. if ( dotSyntax ) {
  19299. parts = sid.split(".");
  19300. this.sid = parts.shift();
  19301. this.member = parts.shift();
  19302. } else if ( arrSyntax ) {
  19303. var arrIndices = sid.split("(");
  19304. this.sid = arrIndices.shift();
  19305. for (var j = 0; j < arrIndices.length; j ++ ) {
  19306. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  19307. }
  19308. this.arrIndices = arrIndices;
  19309. } else {
  19310. this.sid = sid;
  19311. }
  19312. this.fullSid = sid;
  19313. this.dotSyntax = dotSyntax;
  19314. this.arrSyntax = arrSyntax;
  19315. return this;
  19316. };
  19317. function Sampler ( animation ) {
  19318. this.id = "";
  19319. this.animation = animation;
  19320. this.inputs = [];
  19321. this.input = null;
  19322. this.output = null;
  19323. this.strideOut = null;
  19324. this.interpolation = null;
  19325. this.startTime = null;
  19326. this.endTime = null;
  19327. this.duration = 0;
  19328. };
  19329. Sampler.prototype.parse = function ( element ) {
  19330. this.id = element.getAttribute( 'id' );
  19331. this.inputs = [];
  19332. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19333. var child = element.childNodes[ i ];
  19334. if ( child.nodeType != 1 ) continue;
  19335. switch ( child.nodeName ) {
  19336. case 'input':
  19337. this.inputs.push( (new Input()).parse( child ) );
  19338. break;
  19339. default:
  19340. break;
  19341. }
  19342. }
  19343. return this;
  19344. };
  19345. Sampler.prototype.create = function () {
  19346. for ( var i = 0; i < this.inputs.length; i ++ ) {
  19347. var input = this.inputs[ i ];
  19348. var source = this.animation.source[ input.source ];
  19349. switch ( input.semantic ) {
  19350. case 'INPUT':
  19351. this.input = source.read();
  19352. break;
  19353. case 'OUTPUT':
  19354. this.output = source.read();
  19355. this.strideOut = source.accessor.stride;
  19356. break;
  19357. case 'INTERPOLATION':
  19358. this.interpolation = source.read();
  19359. break;
  19360. case 'IN_TANGENT':
  19361. break;
  19362. case 'OUT_TANGENT':
  19363. break;
  19364. default:
  19365. console.log(input.semantic);
  19366. break;
  19367. }
  19368. }
  19369. this.startTime = 0;
  19370. this.endTime = 0;
  19371. this.duration = 0;
  19372. if ( this.input.length ) {
  19373. this.startTime = 100000000;
  19374. this.endTime = -100000000;
  19375. for ( var i = 0; i < this.input.length; i ++ ) {
  19376. this.startTime = Math.min( this.startTime, this.input[ i ] );
  19377. this.endTime = Math.max( this.endTime, this.input[ i ] );
  19378. }
  19379. this.duration = this.endTime - this.startTime;
  19380. }
  19381. };
  19382. Sampler.prototype.getData = function ( type, ndx ) {
  19383. var data;
  19384. if ( this.strideOut > 1 ) {
  19385. data = [];
  19386. ndx *= this.strideOut;
  19387. for ( var i = 0; i < this.strideOut; ++i ) {
  19388. data[ i ] = this.output[ ndx + i ];
  19389. }
  19390. if ( this.strideOut === 3 ) {
  19391. switch ( type ) {
  19392. case 'rotate':
  19393. case 'translate':
  19394. fixCoords( data, -1 );
  19395. break;
  19396. case 'scale':
  19397. fixCoords( data, 1 );
  19398. break;
  19399. }
  19400. }
  19401. } else {
  19402. data = this.output[ ndx ];
  19403. }
  19404. return data;
  19405. };
  19406. function Key ( time ) {
  19407. this.targets = [];
  19408. this.time = time;
  19409. };
  19410. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  19411. this.targets.push( {
  19412. sid: fullSid,
  19413. member: member,
  19414. transform: transform,
  19415. data: data
  19416. } );
  19417. };
  19418. Key.prototype.apply = function ( opt_sid ) {
  19419. for ( var i = 0; i < this.targets.length; ++i ) {
  19420. var target = this.targets[ i ];
  19421. if ( !opt_sid || target.sid === opt_sid ) {
  19422. target.transform.update( target.data, target.member );
  19423. }
  19424. }
  19425. };
  19426. Key.prototype.getTarget = function ( fullSid ) {
  19427. for ( var i = 0; i < this.targets.length; ++i ) {
  19428. if ( this.targets[ i ].sid === fullSid ) {
  19429. return this.targets[ i ];
  19430. }
  19431. }
  19432. return null;
  19433. };
  19434. Key.prototype.hasTarget = function ( fullSid ) {
  19435. for ( var i = 0; i < this.targets.length; ++i ) {
  19436. if ( this.targets[ i ].sid === fullSid ) {
  19437. return true;
  19438. }
  19439. }
  19440. return false;
  19441. };
  19442. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  19443. Key.prototype.interpolate = function ( nextKey, time ) {
  19444. for ( var i = 0; i < this.targets.length; ++i ) {
  19445. var target = this.targets[ i ],
  19446. nextTarget = nextKey.getTarget( target.sid ),
  19447. data;
  19448. if ( nextTarget ) {
  19449. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  19450. nextData = nextTarget.data,
  19451. prevData = target.data;
  19452. // check scale error
  19453. if ( scale < 0 || scale > 1 ) {
  19454. console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
  19455. scale = scale < 0 ? 0 : 1;
  19456. }
  19457. if ( prevData.length ) {
  19458. data = [];
  19459. for ( var j = 0; j < prevData.length; ++j ) {
  19460. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  19461. }
  19462. } else {
  19463. data = prevData + ( nextData - prevData ) * scale;
  19464. }
  19465. } else {
  19466. data = target.data;
  19467. }
  19468. target.transform.update( data, target.member );
  19469. }
  19470. };
  19471. function Camera() {
  19472. this.id = "";
  19473. this.name = "";
  19474. this.technique = "";
  19475. };
  19476. Camera.prototype.parse = function ( element ) {
  19477. this.id = element.getAttribute( 'id' );
  19478. this.name = element.getAttribute( 'name' );
  19479. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19480. var child = element.childNodes[ i ];
  19481. if ( child.nodeType != 1 ) continue;
  19482. switch ( child.nodeName ) {
  19483. case 'optics':
  19484. this.parseOptics( child );
  19485. break;
  19486. default:
  19487. break;
  19488. }
  19489. }
  19490. return this;
  19491. };
  19492. Camera.prototype.parseOptics = function ( element ) {
  19493. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  19494. if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
  19495. var technique = element.childNodes[ i ];
  19496. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  19497. this.technique = technique.childNodes[ j ].nodeName;
  19498. if ( this.technique == 'perspective' ) {
  19499. var perspective = technique.childNodes[ j ];
  19500. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  19501. var param = perspective.childNodes[ k ];
  19502. switch ( param.nodeName ) {
  19503. case 'yfov':
  19504. this.yfov = param.textContent;
  19505. break;
  19506. case 'xfov':
  19507. this.xfov = param.textContent;
  19508. break;
  19509. case 'znear':
  19510. this.znear = param.textContent;
  19511. break;
  19512. case 'zfar':
  19513. this.zfar = param.textContent;
  19514. break;
  19515. case 'aspect_ratio':
  19516. this.aspect_ratio = param.textContent;
  19517. break;
  19518. }
  19519. }
  19520. } else if ( this.technique == 'orthographic' ) {
  19521. var orthographic = technique.childNodes[ j ];
  19522. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  19523. var param = orthographic.childNodes[ k ];
  19524. switch ( param.nodeName ) {
  19525. case 'xmag':
  19526. this.xmag = param.textContent;
  19527. break;
  19528. case 'ymag':
  19529. this.ymag = param.textContent;
  19530. break;
  19531. case 'znear':
  19532. this.znear = param.textContent;
  19533. break;
  19534. case 'zfar':
  19535. this.zfar = param.textContent;
  19536. break;
  19537. case 'aspect_ratio':
  19538. this.aspect_ratio = param.textContent;
  19539. break;
  19540. }
  19541. }
  19542. }
  19543. }
  19544. }
  19545. }
  19546. return this;
  19547. };
  19548. function InstanceCamera() {
  19549. this.url = "";
  19550. };
  19551. InstanceCamera.prototype.parse = function ( element ) {
  19552. this.url = element.getAttribute('url').replace(/^#/, '');
  19553. return this;
  19554. };
  19555. function _source( element ) {
  19556. var id = element.getAttribute( 'id' );
  19557. if ( sources[ id ] != undefined ) {
  19558. return sources[ id ];
  19559. }
  19560. sources[ id ] = ( new Source(id )).parse( element );
  19561. return sources[ id ];
  19562. };
  19563. function _nsResolver( nsPrefix ) {
  19564. if ( nsPrefix == "dae" ) {
  19565. return "http://www.collada.org/2005/11/COLLADASchema";
  19566. }
  19567. return null;
  19568. };
  19569. function _bools( str ) {
  19570. var raw = _strings( str );
  19571. var data = [];
  19572. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19573. data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
  19574. }
  19575. return data;
  19576. };
  19577. function _floats( str ) {
  19578. var raw = _strings(str);
  19579. var data = [];
  19580. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19581. data.push( parseFloat( raw[ i ] ) );
  19582. }
  19583. return data;
  19584. };
  19585. function _ints( str ) {
  19586. var raw = _strings( str );
  19587. var data = [];
  19588. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  19589. data.push( parseInt( raw[ i ], 10 ) );
  19590. }
  19591. return data;
  19592. };
  19593. function _strings( str ) {
  19594. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  19595. };
  19596. function _trimString( str ) {
  19597. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  19598. };
  19599. function _attr_as_float( element, name, defaultValue ) {
  19600. if ( element.hasAttribute( name ) ) {
  19601. return parseFloat( element.getAttribute( name ) );
  19602. } else {
  19603. return defaultValue;
  19604. }
  19605. };
  19606. function _attr_as_int( element, name, defaultValue ) {
  19607. if ( element.hasAttribute( name ) ) {
  19608. return parseInt( element.getAttribute( name ), 10) ;
  19609. } else {
  19610. return defaultValue;
  19611. }
  19612. };
  19613. function _attr_as_string( element, name, defaultValue ) {
  19614. if ( element.hasAttribute( name ) ) {
  19615. return element.getAttribute( name );
  19616. } else {
  19617. return defaultValue;
  19618. }
  19619. };
  19620. function _format_float( f, num ) {
  19621. if ( f === undefined ) {
  19622. var s = '0.';
  19623. while ( s.length < num + 2 ) {
  19624. s += '0';
  19625. }
  19626. return s;
  19627. }
  19628. num = num || 2;
  19629. var parts = f.toString().split( '.' );
  19630. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  19631. while( parts[ 1 ].length < num ) {
  19632. parts[ 1 ] += '0';
  19633. }
  19634. return parts.join( '.' );
  19635. };
  19636. function evaluateXPath( node, query ) {
  19637. var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  19638. var inst = instances.iterateNext();
  19639. var result = [];
  19640. while ( inst ) {
  19641. result.push( inst );
  19642. inst = instances.iterateNext();
  19643. }
  19644. return result;
  19645. };
  19646. // Up axis conversion
  19647. function setUpConversion() {
  19648. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  19649. upConversion = null;
  19650. } else {
  19651. switch ( colladaUp ) {
  19652. case 'X':
  19653. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  19654. break;
  19655. case 'Y':
  19656. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  19657. break;
  19658. case 'Z':
  19659. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  19660. break;
  19661. }
  19662. }
  19663. };
  19664. function fixCoords( data, sign ) {
  19665. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  19666. return;
  19667. }
  19668. switch ( upConversion ) {
  19669. case 'XtoY':
  19670. var tmp = data[ 0 ];
  19671. data[ 0 ] = sign * data[ 1 ];
  19672. data[ 1 ] = tmp;
  19673. break;
  19674. case 'XtoZ':
  19675. var tmp = data[ 2 ];
  19676. data[ 2 ] = data[ 1 ];
  19677. data[ 1 ] = data[ 0 ];
  19678. data[ 0 ] = tmp;
  19679. break;
  19680. case 'YtoX':
  19681. var tmp = data[ 0 ];
  19682. data[ 0 ] = data[ 1 ];
  19683. data[ 1 ] = sign * tmp;
  19684. break;
  19685. case 'YtoZ':
  19686. var tmp = data[ 1 ];
  19687. data[ 1 ] = sign * data[ 2 ];
  19688. data[ 2 ] = tmp;
  19689. break;
  19690. case 'ZtoX':
  19691. var tmp = data[ 0 ];
  19692. data[ 0 ] = data[ 1 ];
  19693. data[ 1 ] = data[ 2 ];
  19694. data[ 2 ] = tmp;
  19695. break;
  19696. case 'ZtoY':
  19697. var tmp = data[ 1 ];
  19698. data[ 1 ] = data[ 2 ];
  19699. data[ 2 ] = sign * tmp;
  19700. break;
  19701. }
  19702. };
  19703. function getConvertedVec3( data, offset ) {
  19704. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  19705. fixCoords( arr, -1 );
  19706. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  19707. };
  19708. function getConvertedMat4( data ) {
  19709. if ( options.convertUpAxis ) {
  19710. // First fix rotation and scale
  19711. // Columns first
  19712. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  19713. fixCoords( arr, -1 );
  19714. data[ 0 ] = arr[ 0 ];
  19715. data[ 4 ] = arr[ 1 ];
  19716. data[ 8 ] = arr[ 2 ];
  19717. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  19718. fixCoords( arr, -1 );
  19719. data[ 1 ] = arr[ 0 ];
  19720. data[ 5 ] = arr[ 1 ];
  19721. data[ 9 ] = arr[ 2 ];
  19722. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  19723. fixCoords( arr, -1 );
  19724. data[ 2 ] = arr[ 0 ];
  19725. data[ 6 ] = arr[ 1 ];
  19726. data[ 10 ] = arr[ 2 ];
  19727. // Rows second
  19728. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  19729. fixCoords( arr, -1 );
  19730. data[ 0 ] = arr[ 0 ];
  19731. data[ 1 ] = arr[ 1 ];
  19732. data[ 2 ] = arr[ 2 ];
  19733. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  19734. fixCoords( arr, -1 );
  19735. data[ 4 ] = arr[ 0 ];
  19736. data[ 5 ] = arr[ 1 ];
  19737. data[ 6 ] = arr[ 2 ];
  19738. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  19739. fixCoords( arr, -1 );
  19740. data[ 8 ] = arr[ 0 ];
  19741. data[ 9 ] = arr[ 1 ];
  19742. data[ 10 ] = arr[ 2 ];
  19743. // Now fix translation
  19744. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  19745. fixCoords( arr, -1 );
  19746. data[ 3 ] = arr[ 0 ];
  19747. data[ 7 ] = arr[ 1 ];
  19748. data[ 11 ] = arr[ 2 ];
  19749. }
  19750. return new THREE.Matrix4(
  19751. data[0], data[1], data[2], data[3],
  19752. data[4], data[5], data[6], data[7],
  19753. data[8], data[9], data[10], data[11],
  19754. data[12], data[13], data[14], data[15]
  19755. );
  19756. };
  19757. function getConvertedMember( member ) {
  19758. if ( options.convertUpAxis ) {
  19759. switch ( member ) {
  19760. case 'X':
  19761. switch ( upConversion ) {
  19762. case 'XtoY':
  19763. case 'XtoZ':
  19764. case 'YtoX':
  19765. member = 'Y';
  19766. break;
  19767. case 'ZtoX':
  19768. member = 'Z';
  19769. break;
  19770. }
  19771. break;
  19772. case 'Y':
  19773. switch ( upConversion ) {
  19774. case 'XtoY':
  19775. case 'YtoX':
  19776. case 'ZtoX':
  19777. member = 'X';
  19778. break;
  19779. case 'XtoZ':
  19780. case 'YtoZ':
  19781. case 'ZtoY':
  19782. member = 'Z';
  19783. break;
  19784. }
  19785. break;
  19786. case 'Z':
  19787. switch ( upConversion ) {
  19788. case 'XtoZ':
  19789. member = 'X';
  19790. break;
  19791. case 'YtoZ':
  19792. case 'ZtoX':
  19793. case 'ZtoY':
  19794. member = 'Y';
  19795. break;
  19796. }
  19797. break;
  19798. }
  19799. }
  19800. return member;
  19801. };
  19802. return {
  19803. load: load,
  19804. parse: parse,
  19805. setPreferredShading: setPreferredShading,
  19806. applySkin: applySkin,
  19807. geometries : geometries,
  19808. options: options
  19809. };
  19810. };
  19811. /**
  19812. * @author mrdoob / http://mrdoob.com/
  19813. * @author alteredq / http://alteredqualia.com/
  19814. */
  19815. THREE.JSONLoader = function ( showStatus ) {
  19816. THREE.Loader.call( this, showStatus );
  19817. };
  19818. THREE.JSONLoader.prototype = new THREE.Loader();
  19819. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  19820. THREE.JSONLoader.prototype.supr = THREE.Loader.prototype;
  19821. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  19822. var worker, scope = this;
  19823. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  19824. this.onLoadStart();
  19825. this.loadAjaxJSON( this, url, callback, texturePath );
  19826. };
  19827. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  19828. var xhr = new XMLHttpRequest();
  19829. var length = 0;
  19830. xhr.onreadystatechange = function () {
  19831. if ( xhr.readyState === xhr.DONE ) {
  19832. if ( xhr.status === 200 || xhr.status === 0 ) {
  19833. if ( xhr.responseText ) {
  19834. var json = JSON.parse( xhr.responseText );
  19835. context.createModel( json, callback, texturePath );
  19836. } else {
  19837. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  19838. }
  19839. // in context of more complex asset initialization
  19840. // do not block on single failed file
  19841. // maybe should go even one more level up
  19842. context.onLoadComplete();
  19843. } else {
  19844. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  19845. }
  19846. } else if ( xhr.readyState === xhr.LOADING ) {
  19847. if ( callbackProgress ) {
  19848. if ( length === 0 ) {
  19849. length = xhr.getResponseHeader( "Content-Length" );
  19850. }
  19851. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  19852. }
  19853. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  19854. length = xhr.getResponseHeader( "Content-Length" );
  19855. }
  19856. };
  19857. xhr.open( "GET", url, true );
  19858. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  19859. xhr.setRequestHeader( "Content-Type", "text/plain" );
  19860. xhr.send( null );
  19861. };
  19862. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  19863. var scope = this,
  19864. geometry = new THREE.Geometry(),
  19865. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  19866. this.initMaterials( geometry, json.materials, texturePath );
  19867. parseModel( scale );
  19868. parseSkin();
  19869. parseMorphing( scale );
  19870. geometry.computeCentroids();
  19871. geometry.computeFaceNormals();
  19872. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  19873. function parseModel( scale ) {
  19874. function isBitSet( value, position ) {
  19875. return value & ( 1 << position );
  19876. }
  19877. var i, j, fi,
  19878. offset, zLength, nVertices,
  19879. colorIndex, normalIndex, uvIndex, materialIndex,
  19880. type,
  19881. isQuad,
  19882. hasMaterial,
  19883. hasFaceUv, hasFaceVertexUv,
  19884. hasFaceNormal, hasFaceVertexNormal,
  19885. hasFaceColor, hasFaceVertexColor,
  19886. vertex, face, color, normal,
  19887. uvLayer, uvs, u, v,
  19888. faces = json.faces,
  19889. vertices = json.vertices,
  19890. normals = json.normals,
  19891. colors = json.colors,
  19892. nUvLayers = 0;
  19893. // disregard empty arrays
  19894. for ( i = 0; i < json.uvs.length; i++ ) {
  19895. if ( json.uvs[ i ].length ) nUvLayers ++;
  19896. }
  19897. for ( i = 0; i < nUvLayers; i++ ) {
  19898. geometry.faceUvs[ i ] = [];
  19899. geometry.faceVertexUvs[ i ] = [];
  19900. }
  19901. offset = 0;
  19902. zLength = vertices.length;
  19903. while ( offset < zLength ) {
  19904. vertex = new THREE.Vertex();
  19905. vertex.position.x = vertices[ offset ++ ] * scale;
  19906. vertex.position.y = vertices[ offset ++ ] * scale;
  19907. vertex.position.z = vertices[ offset ++ ] * scale;
  19908. geometry.vertices.push( vertex );
  19909. }
  19910. offset = 0;
  19911. zLength = faces.length;
  19912. while ( offset < zLength ) {
  19913. type = faces[ offset ++ ];
  19914. isQuad = isBitSet( type, 0 );
  19915. hasMaterial = isBitSet( type, 1 );
  19916. hasFaceUv = isBitSet( type, 2 );
  19917. hasFaceVertexUv = isBitSet( type, 3 );
  19918. hasFaceNormal = isBitSet( type, 4 );
  19919. hasFaceVertexNormal = isBitSet( type, 5 );
  19920. hasFaceColor = isBitSet( type, 6 );
  19921. hasFaceVertexColor = isBitSet( type, 7 );
  19922. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  19923. if ( isQuad ) {
  19924. face = new THREE.Face4();
  19925. face.a = faces[ offset ++ ];
  19926. face.b = faces[ offset ++ ];
  19927. face.c = faces[ offset ++ ];
  19928. face.d = faces[ offset ++ ];
  19929. nVertices = 4;
  19930. } else {
  19931. face = new THREE.Face3();
  19932. face.a = faces[ offset ++ ];
  19933. face.b = faces[ offset ++ ];
  19934. face.c = faces[ offset ++ ];
  19935. nVertices = 3;
  19936. }
  19937. if ( hasMaterial ) {
  19938. materialIndex = faces[ offset ++ ];
  19939. face.materialIndex = materialIndex;
  19940. }
  19941. // to get face <=> uv index correspondence
  19942. fi = geometry.faces.length;
  19943. if ( hasFaceUv ) {
  19944. for ( i = 0; i < nUvLayers; i++ ) {
  19945. uvLayer = json.uvs[ i ];
  19946. uvIndex = faces[ offset ++ ];
  19947. u = uvLayer[ uvIndex * 2 ];
  19948. v = uvLayer[ uvIndex * 2 + 1 ];
  19949. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  19950. }
  19951. }
  19952. if ( hasFaceVertexUv ) {
  19953. for ( i = 0; i < nUvLayers; i++ ) {
  19954. uvLayer = json.uvs[ i ];
  19955. uvs = [];
  19956. for ( j = 0; j < nVertices; j ++ ) {
  19957. uvIndex = faces[ offset ++ ];
  19958. u = uvLayer[ uvIndex * 2 ];
  19959. v = uvLayer[ uvIndex * 2 + 1 ];
  19960. uvs[ j ] = new THREE.UV( u, v );
  19961. }
  19962. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  19963. }
  19964. }
  19965. if ( hasFaceNormal ) {
  19966. normalIndex = faces[ offset ++ ] * 3;
  19967. normal = new THREE.Vector3();
  19968. normal.x = normals[ normalIndex ++ ];
  19969. normal.y = normals[ normalIndex ++ ];
  19970. normal.z = normals[ normalIndex ];
  19971. face.normal = normal;
  19972. }
  19973. if ( hasFaceVertexNormal ) {
  19974. for ( i = 0; i < nVertices; i++ ) {
  19975. normalIndex = faces[ offset ++ ] * 3;
  19976. normal = new THREE.Vector3();
  19977. normal.x = normals[ normalIndex ++ ];
  19978. normal.y = normals[ normalIndex ++ ];
  19979. normal.z = normals[ normalIndex ];
  19980. face.vertexNormals.push( normal );
  19981. }
  19982. }
  19983. if ( hasFaceColor ) {
  19984. colorIndex = faces[ offset ++ ];
  19985. color = new THREE.Color( colors[ colorIndex ] );
  19986. face.color = color;
  19987. }
  19988. if ( hasFaceVertexColor ) {
  19989. for ( i = 0; i < nVertices; i++ ) {
  19990. colorIndex = faces[ offset ++ ];
  19991. color = new THREE.Color( colors[ colorIndex ] );
  19992. face.vertexColors.push( color );
  19993. }
  19994. }
  19995. geometry.faces.push( face );
  19996. }
  19997. };
  19998. function parseSkin() {
  19999. var i, l, x, y, z, w, a, b, c, d;
  20000. if ( json.skinWeights ) {
  20001. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  20002. x = json.skinWeights[ i ];
  20003. y = json.skinWeights[ i + 1 ];
  20004. z = 0;
  20005. w = 0;
  20006. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  20007. }
  20008. }
  20009. if ( json.skinIndices ) {
  20010. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  20011. a = json.skinIndices[ i ];
  20012. b = json.skinIndices[ i + 1 ];
  20013. c = 0;
  20014. d = 0;
  20015. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  20016. }
  20017. }
  20018. geometry.bones = json.bones;
  20019. geometry.animation = json.animation;
  20020. };
  20021. function parseMorphing( scale ) {
  20022. if ( json.morphTargets !== undefined ) {
  20023. var i, l, v, vl, x, y, z, dstVertices, srcVertices;
  20024. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  20025. geometry.morphTargets[ i ] = {};
  20026. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  20027. geometry.morphTargets[ i ].vertices = [];
  20028. dstVertices = geometry.morphTargets[ i ].vertices;
  20029. srcVertices = json.morphTargets [ i ].vertices;
  20030. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  20031. x = srcVertices[ v ] * scale;
  20032. y = srcVertices[ v + 1 ] * scale;
  20033. z = srcVertices[ v + 2 ] * scale;
  20034. dstVertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  20035. }
  20036. }
  20037. }
  20038. if ( json.morphColors !== undefined ) {
  20039. var i, l, c, cl, dstColors, srcColors, color;
  20040. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  20041. geometry.morphColors[ i ] = {};
  20042. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  20043. geometry.morphColors[ i ].colors = [];
  20044. dstColors = geometry.morphColors[ i ].colors;
  20045. srcColors = json.morphColors [ i ].colors;
  20046. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  20047. color = new THREE.Color( 0xffaa00 );
  20048. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  20049. dstColors.push( color );
  20050. }
  20051. }
  20052. }
  20053. };
  20054. callback( geometry );
  20055. };
  20056. /**
  20057. * @author alteredq / http://alteredqualia.com/
  20058. */
  20059. THREE.SceneLoader = function () {
  20060. this.onLoadStart = function () {};
  20061. this.onLoadProgress = function() {};
  20062. this.onLoadComplete = function () {};
  20063. this.callbackSync = function () {};
  20064. this.callbackProgress = function () {};
  20065. };
  20066. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  20067. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  20068. var context = this;
  20069. var xhr = new XMLHttpRequest();
  20070. xhr.onreadystatechange = function () {
  20071. if ( xhr.readyState == 4 ) {
  20072. if ( xhr.status == 200 || xhr.status == 0 ) {
  20073. var json = JSON.parse( xhr.responseText );
  20074. context.createScene( json, callbackFinished, url );
  20075. } else {
  20076. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  20077. }
  20078. }
  20079. };
  20080. xhr.open( "GET", url, true );
  20081. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  20082. xhr.setRequestHeader( "Content-Type", "text/plain" );
  20083. xhr.send( null );
  20084. };
  20085. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  20086. var scope = this;
  20087. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  20088. var dg, dm, dd, dl, dc, df, dt,
  20089. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  20090. geometry, material, camera, fog,
  20091. texture, images,
  20092. light,
  20093. data, binLoader, jsonLoader,
  20094. counter_models, counter_textures,
  20095. total_models, total_textures,
  20096. result;
  20097. data = json;
  20098. binLoader = new THREE.BinaryLoader();
  20099. jsonLoader = new THREE.JSONLoader();
  20100. counter_models = 0;
  20101. counter_textures = 0;
  20102. result = {
  20103. scene: new THREE.Scene(),
  20104. geometries: {},
  20105. materials: {},
  20106. textures: {},
  20107. objects: {},
  20108. cameras: {},
  20109. lights: {},
  20110. fogs: {},
  20111. empties: {}
  20112. };
  20113. if ( data.transform ) {
  20114. var position = data.transform.position,
  20115. rotation = data.transform.rotation,
  20116. scale = data.transform.scale;
  20117. if ( position )
  20118. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  20119. if ( rotation )
  20120. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  20121. if ( scale )
  20122. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  20123. if ( position || rotation || scale ) {
  20124. result.scene.updateMatrix();
  20125. result.scene.updateMatrixWorld();
  20126. }
  20127. }
  20128. function get_url( source_url, url_type ) {
  20129. if ( url_type == "relativeToHTML" ) {
  20130. return source_url;
  20131. } else {
  20132. return urlBase + "/" + source_url;
  20133. }
  20134. };
  20135. function handle_objects() {
  20136. var object;
  20137. for( dd in data.objects ) {
  20138. if ( !result.objects[ dd ] ) {
  20139. o = data.objects[ dd ];
  20140. if ( o.geometry !== undefined ) {
  20141. geometry = result.geometries[ o.geometry ];
  20142. // geometry already loaded
  20143. if ( geometry ) {
  20144. var hasNormals = false;
  20145. // not anymore support for multiple materials
  20146. // shouldn't really be array
  20147. material = result.materials[ o.materials[ 0 ] ];
  20148. hasNormals = material instanceof THREE.ShaderMaterial;
  20149. if ( hasNormals ) {
  20150. geometry.computeTangents();
  20151. }
  20152. p = o.position;
  20153. r = o.rotation;
  20154. q = o.quaternion;
  20155. s = o.scale;
  20156. // turn off quaternions, for the moment
  20157. q = 0;
  20158. if ( o.materials.length == 0 ) {
  20159. material = new THREE.MeshFaceMaterial();
  20160. }
  20161. // dirty hack to handle meshes with multiple materials
  20162. // just use face materials defined in model
  20163. if ( o.materials.length > 1 ) {
  20164. material = new THREE.MeshFaceMaterial();
  20165. }
  20166. object = new THREE.Mesh( geometry, material );
  20167. object.name = dd;
  20168. object.position.set( p[0], p[1], p[2] );
  20169. if ( q ) {
  20170. object.quaternion.set( q[0], q[1], q[2], q[3] );
  20171. object.useQuaternion = true;
  20172. } else {
  20173. object.rotation.set( r[0], r[1], r[2] );
  20174. }
  20175. object.scale.set( s[0], s[1], s[2] );
  20176. object.visible = o.visible;
  20177. object.doubleSided = o.doubleSided;
  20178. object.castShadow = o.castShadow;
  20179. object.receiveShadow = o.receiveShadow;
  20180. result.scene.add( object );
  20181. result.objects[ dd ] = object;
  20182. }
  20183. // pure Object3D
  20184. } else {
  20185. p = o.position;
  20186. r = o.rotation;
  20187. q = o.quaternion;
  20188. s = o.scale;
  20189. // turn off quaternions, for the moment
  20190. q = 0;
  20191. object = new THREE.Object3D();
  20192. object.name = dd;
  20193. object.position.set( p[0], p[1], p[2] );
  20194. if ( q ) {
  20195. object.quaternion.set( q[0], q[1], q[2], q[3] );
  20196. object.useQuaternion = true;
  20197. } else {
  20198. object.rotation.set( r[0], r[1], r[2] );
  20199. }
  20200. object.scale.set( s[0], s[1], s[2] );
  20201. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  20202. result.scene.add( object );
  20203. result.objects[ dd ] = object;
  20204. result.empties[ dd ] = object;
  20205. }
  20206. }
  20207. }
  20208. };
  20209. function handle_mesh( geo, id ) {
  20210. result.geometries[ id ] = geo;
  20211. handle_objects();
  20212. };
  20213. function create_callback( id ) {
  20214. return function( geo ) {
  20215. handle_mesh( geo, id );
  20216. counter_models -= 1;
  20217. scope.onLoadComplete();
  20218. async_callback_gate();
  20219. }
  20220. };
  20221. function create_callback_embed( id ) {
  20222. return function( geo ) {
  20223. result.geometries[ id ] = geo;
  20224. }
  20225. };
  20226. function async_callback_gate() {
  20227. var progress = {
  20228. totalModels : total_models,
  20229. totalTextures : total_textures,
  20230. loadedModels : total_models - counter_models,
  20231. loadedTextures : total_textures - counter_textures
  20232. };
  20233. scope.callbackProgress( progress, result );
  20234. scope.onLoadProgress();
  20235. if( counter_models == 0 && counter_textures == 0 ) {
  20236. callbackFinished( result );
  20237. }
  20238. };
  20239. var callbackTexture = function( images ) {
  20240. counter_textures -= 1;
  20241. async_callback_gate();
  20242. scope.onLoadComplete();
  20243. };
  20244. // first go synchronous elements
  20245. // cameras
  20246. for( dc in data.cameras ) {
  20247. c = data.cameras[ dc ];
  20248. if ( c.type == "perspective" ) {
  20249. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  20250. } else if ( c.type == "ortho" ) {
  20251. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  20252. }
  20253. p = c.position;
  20254. t = c.target;
  20255. u = c.up;
  20256. camera.position.set( p[0], p[1], p[2] );
  20257. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  20258. if ( u ) camera.up.set( u[0], u[1], u[2] );
  20259. result.cameras[ dc ] = camera;
  20260. }
  20261. // lights
  20262. var hex, intensity;
  20263. for ( dl in data.lights ) {
  20264. l = data.lights[ dl ];
  20265. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  20266. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  20267. if ( l.type == "directional" ) {
  20268. p = l.direction;
  20269. light = new THREE.DirectionalLight( hex, intensity );
  20270. light.position.set( p[0], p[1], p[2] );
  20271. light.position.normalize();
  20272. } else if ( l.type == "point" ) {
  20273. p = l.position;
  20274. d = l.distance;
  20275. light = new THREE.PointLight( hex, intensity, d );
  20276. light.position.set( p[0], p[1], p[2] );
  20277. } else if ( l.type == "ambient" ) {
  20278. light = new THREE.AmbientLight( hex );
  20279. }
  20280. result.scene.add( light );
  20281. result.lights[ dl ] = light;
  20282. }
  20283. // fogs
  20284. for( df in data.fogs ) {
  20285. f = data.fogs[ df ];
  20286. if ( f.type == "linear" ) {
  20287. fog = new THREE.Fog( 0x000000, f.near, f.far );
  20288. } else if ( f.type == "exp2" ) {
  20289. fog = new THREE.FogExp2( 0x000000, f.density );
  20290. }
  20291. c = f.color;
  20292. fog.color.setRGB( c[0], c[1], c[2] );
  20293. result.fogs[ df ] = fog;
  20294. }
  20295. // defaults
  20296. if ( result.cameras && data.defaults.camera ) {
  20297. result.currentCamera = result.cameras[ data.defaults.camera ];
  20298. }
  20299. if ( result.fogs && data.defaults.fog ) {
  20300. result.scene.fog = result.fogs[ data.defaults.fog ];
  20301. }
  20302. c = data.defaults.bgcolor;
  20303. result.bgColor = new THREE.Color();
  20304. result.bgColor.setRGB( c[0], c[1], c[2] );
  20305. result.bgColorAlpha = data.defaults.bgalpha;
  20306. // now come potentially asynchronous elements
  20307. // geometries
  20308. // count how many models will be loaded asynchronously
  20309. for( dg in data.geometries ) {
  20310. g = data.geometries[ dg ];
  20311. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  20312. counter_models += 1;
  20313. scope.onLoadStart();
  20314. }
  20315. }
  20316. total_models = counter_models;
  20317. for ( dg in data.geometries ) {
  20318. g = data.geometries[ dg ];
  20319. if ( g.type == "cube" ) {
  20320. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  20321. result.geometries[ dg ] = geometry;
  20322. } else if ( g.type == "plane" ) {
  20323. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  20324. result.geometries[ dg ] = geometry;
  20325. } else if ( g.type == "sphere" ) {
  20326. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  20327. result.geometries[ dg ] = geometry;
  20328. } else if ( g.type == "cylinder" ) {
  20329. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  20330. result.geometries[ dg ] = geometry;
  20331. } else if ( g.type == "torus" ) {
  20332. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  20333. result.geometries[ dg ] = geometry;
  20334. } else if ( g.type == "icosahedron" ) {
  20335. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  20336. result.geometries[ dg ] = geometry;
  20337. } else if ( g.type == "bin_mesh" ) {
  20338. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  20339. } else if ( g.type == "ascii_mesh" ) {
  20340. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  20341. } else if ( g.type == "embedded_mesh" ) {
  20342. var modelJson = data.embeds[ g.id ],
  20343. texture_path = "";
  20344. // Pass metadata along to jsonLoader so it knows the format version.
  20345. modelJson.metadata = data.metadata;
  20346. if ( modelJson ) {
  20347. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  20348. }
  20349. }
  20350. }
  20351. // textures
  20352. // count how many textures will be loaded asynchronously
  20353. for( dt in data.textures ) {
  20354. tt = data.textures[ dt ];
  20355. if( tt.url instanceof Array ) {
  20356. counter_textures += tt.url.length;
  20357. for( var n = 0; n < tt.url.length; n ++ ) {
  20358. scope.onLoadStart();
  20359. }
  20360. } else {
  20361. counter_textures += 1;
  20362. scope.onLoadStart();
  20363. }
  20364. }
  20365. total_textures = counter_textures;
  20366. for( dt in data.textures ) {
  20367. tt = data.textures[ dt ];
  20368. if ( tt.mapping != undefined && THREE[ tt.mapping ] != undefined ) {
  20369. tt.mapping = new THREE[ tt.mapping ]();
  20370. }
  20371. if( tt.url instanceof Array ) {
  20372. var url_array = [];
  20373. for( var i = 0; i < tt.url.length; i ++ ) {
  20374. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  20375. }
  20376. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, callbackTexture );
  20377. } else {
  20378. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, callbackTexture );
  20379. if ( THREE[ tt.minFilter ] != undefined )
  20380. texture.minFilter = THREE[ tt.minFilter ];
  20381. if ( THREE[ tt.magFilter ] != undefined )
  20382. texture.magFilter = THREE[ tt.magFilter ];
  20383. if ( tt.repeat ) {
  20384. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  20385. if ( tt.repeat[ 0 ] != 1 ) texture.wrapS = THREE.RepeatWrapping;
  20386. if ( tt.repeat[ 1 ] != 1 ) texture.wrapT = THREE.RepeatWrapping;
  20387. }
  20388. if ( tt.offset ) {
  20389. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  20390. }
  20391. // handle wrap after repeat so that default repeat can be overriden
  20392. if ( tt.wrap ) {
  20393. var wrapMap = {
  20394. "repeat" : THREE.RepeatWrapping,
  20395. "mirror" : THREE.MirroredRepeatWrapping
  20396. }
  20397. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  20398. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  20399. }
  20400. }
  20401. result.textures[ dt ] = texture;
  20402. }
  20403. // materials
  20404. for ( dm in data.materials ) {
  20405. m = data.materials[ dm ];
  20406. for ( pp in m.parameters ) {
  20407. if ( pp == "envMap" || pp == "map" || pp == "lightMap" ) {
  20408. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  20409. } else if ( pp == "shading" ) {
  20410. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  20411. } else if ( pp == "blending" ) {
  20412. m.parameters[ pp ] = THREE[ m.parameters[ pp ] ] ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  20413. } else if ( pp == "combine" ) {
  20414. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  20415. } else if ( pp == "vertexColors" ) {
  20416. if ( m.parameters[ pp ] == "face" ) {
  20417. m.parameters[ pp ] = THREE.FaceColors;
  20418. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  20419. } else if ( m.parameters[ pp ] ) {
  20420. m.parameters[ pp ] = THREE.VertexColors;
  20421. }
  20422. }
  20423. }
  20424. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  20425. m.parameters.transparent = true;
  20426. }
  20427. if ( m.parameters.normalMap ) {
  20428. var shader = THREE.ShaderUtils.lib[ "normal" ];
  20429. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  20430. var diffuse = m.parameters.color;
  20431. var specular = m.parameters.specular;
  20432. var ambient = m.parameters.ambient;
  20433. var shininess = m.parameters.shininess;
  20434. uniforms[ "tNormal" ].texture = result.textures[ m.parameters.normalMap ];
  20435. if ( m.parameters.normalMapFactor ) {
  20436. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  20437. }
  20438. if ( m.parameters.map ) {
  20439. uniforms[ "tDiffuse" ].texture = m.parameters.map;
  20440. uniforms[ "enableDiffuse" ].value = true;
  20441. }
  20442. if ( m.parameters.lightMap ) {
  20443. uniforms[ "tAO" ].texture = m.parameters.lightMap;
  20444. uniforms[ "enableAO" ].value = true;
  20445. }
  20446. if ( m.parameters.specularMap ) {
  20447. uniforms[ "tSpecular" ].texture = result.textures[ m.parameters.specularMap ];
  20448. uniforms[ "enableSpecular" ].value = true;
  20449. }
  20450. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  20451. uniforms[ "uSpecularColor" ].value.setHex( specular );
  20452. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  20453. uniforms[ "uShininess" ].value = shininess;
  20454. if ( m.parameters.opacity ) {
  20455. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  20456. }
  20457. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  20458. material = new THREE.ShaderMaterial( parameters );
  20459. } else {
  20460. material = new THREE[ m.type ]( m.parameters );
  20461. }
  20462. result.materials[ dm ] = material;
  20463. }
  20464. // objects ( synchronous init of procedural primitives )
  20465. handle_objects();
  20466. // synchronous callback
  20467. scope.callbackSync( result );
  20468. // just in case there are no async elements:
  20469. async_callback_gate();
  20470. };
  20471. /**
  20472. * Loader for UTF8 encoded models generated by:
  20473. * http://code.google.com/p/webgl-loader/
  20474. *
  20475. * Limitations:
  20476. * - number of vertices < 65536 (this is after optimizations in compressor, input OBJ may have even less)
  20477. * - models must have normals and texture coordinates
  20478. * - texture coordinates must be only from <0,1>
  20479. * - no materials support yet
  20480. * - models are scaled and offset (copy numbers from compressor and use them as parameters in UTF8Loader.load() )
  20481. *
  20482. * @author alteredq / http://alteredqualia.com/
  20483. * @author won3d / http://twitter.com/won3d
  20484. */
  20485. THREE.UTF8Loader = function () {};
  20486. THREE.UTF8Loader.prototype.load = function ( url, callback, metadata ) {
  20487. var xhr = new XMLHttpRequest(),
  20488. callbackProgress = null,
  20489. scale = metadata.scale !== undefined ? metadata.scale : 1,
  20490. offsetX = metadata.offsetX !== undefined ? metadata.offsetX : 0,
  20491. offsetY = metadata.offsetY !== undefined ? metadata.offsetY : 0,
  20492. offsetZ = metadata.offsetZ !== undefined ? metadata.offsetZ : 0;
  20493. var length = 0;
  20494. xhr.onreadystatechange = function() {
  20495. if ( xhr.readyState == 4 ) {
  20496. if ( xhr.status == 200 || xhr.status == 0 ) {
  20497. THREE.UTF8Loader.prototype.createModel( xhr.responseText, callback, scale, offsetX, offsetY, offsetZ );
  20498. } else {
  20499. console.error( "THREE.UTF8Loader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  20500. }
  20501. } else if ( xhr.readyState == 3 ) {
  20502. if ( callbackProgress ) {
  20503. if ( length == 0 ) {
  20504. length = xhr.getResponseHeader( "Content-Length" );
  20505. }
  20506. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  20507. }
  20508. } else if ( xhr.readyState == 2 ) {
  20509. length = xhr.getResponseHeader( "Content-Length" );
  20510. }
  20511. }
  20512. xhr.open( "GET", url, true );
  20513. xhr.send( null );
  20514. };
  20515. // UTF-8 decoder from webgl-loader
  20516. // http://code.google.com/p/webgl-loader/
  20517. // Copyright 2011 Google Inc. All Rights Reserved.
  20518. //
  20519. // Licensed under the Apache License, Version 2.0 (the "License"); you
  20520. // may not use this file except in compliance with the License. You
  20521. // may obtain a copy of the License at
  20522. //
  20523. // http://www.apache.org/licenses/LICENSE-2.0
  20524. //
  20525. // Unless required by applicable law or agreed to in writing, software
  20526. // distributed under the License is distributed on an "AS IS" BASIS,
  20527. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  20528. // implied. See the License for the specific language governing
  20529. // permissions and limitations under the License.
  20530. THREE.UTF8Loader.prototype.decompressMesh = function ( str ) {
  20531. var num_verts = str.charCodeAt( 0 );
  20532. if ( num_verts >= 0xE000 ) {
  20533. num_verts -= 0x0800;
  20534. }
  20535. num_verts ++;
  20536. var attribs_out = new Float32Array( 8 * num_verts );
  20537. var offset = 1;
  20538. for ( var i = 0; i < 8; i ++ ) {
  20539. var prev_attrib = 0;
  20540. for ( var j = 0; j < num_verts; ++ j ) {
  20541. var code = str.charCodeAt( j + offset );
  20542. prev_attrib += ( code >> 1 ) ^ ( - ( code & 1 ) );
  20543. attribs_out[ 8 * j + i ] = prev_attrib;
  20544. }
  20545. offset += num_verts;
  20546. }
  20547. var num_indices = str.length - offset;
  20548. var indices_out = new Uint16Array( num_indices );
  20549. var index_high_water_mark = 0;
  20550. for ( var i = 0; i < num_indices; i ++ ) {
  20551. var code = str.charCodeAt( i + offset );
  20552. indices_out[ i ] = index_high_water_mark - code;
  20553. if ( code == 0 ) {
  20554. index_high_water_mark ++;
  20555. }
  20556. }
  20557. return [ attribs_out, indices_out ];
  20558. };
  20559. THREE.UTF8Loader.prototype.createModel = function ( data, callback, scale, offsetX, offsetY, offsetZ ) {
  20560. var Model = function ( texture_path ) {
  20561. //var s = (new Date).getTime();
  20562. var scope = this;
  20563. scope.materials = [];
  20564. THREE.Geometry.call( this );
  20565. var buffers = THREE.UTF8Loader.prototype.decompressMesh( data );
  20566. var normals = [],
  20567. uvs = [];
  20568. init_vertices( buffers[ 0 ], 8, 0 );
  20569. init_uvs( buffers[ 0 ], 8, 3 );
  20570. init_normals( buffers[ 0 ], 8, 5 );
  20571. init_faces( buffers[ 1 ] );
  20572. this.computeCentroids();
  20573. this.computeFaceNormals();
  20574. //this.computeTangents();
  20575. //var e = (new Date).getTime();
  20576. //console.log( "utf8 data parse time: " + (e-s) + " ms" );
  20577. function init_vertices( data, stride, offset ) {
  20578. var i, x, y, z,
  20579. end = data.length;
  20580. for( i = offset; i < end; i += stride ) {
  20581. x = data[ i ];
  20582. y = data[ i + 1 ];
  20583. z = data[ i + 2 ];
  20584. // fix scale and offsets
  20585. x = ( x / 16383 ) * scale;
  20586. y = ( y / 16383 ) * scale;
  20587. z = ( z / 16383 ) * scale;
  20588. x += offsetX;
  20589. y += offsetY;
  20590. z += offsetZ;
  20591. vertex( scope, x, y, z );
  20592. }
  20593. };
  20594. function init_normals( data, stride, offset ) {
  20595. var i, x, y, z,
  20596. end = data.length;
  20597. for( i = offset; i < end; i += stride ) {
  20598. x = data[ i ];
  20599. y = data[ i + 1 ];
  20600. z = data[ i + 2 ];
  20601. // normalize to <-1,1>
  20602. x = ( x - 512 ) / 511;
  20603. y = ( y - 512 ) / 511;
  20604. z = ( z - 512 ) / 511;
  20605. normals.push( x, y, z );
  20606. }
  20607. };
  20608. function init_uvs( data, stride, offset ) {
  20609. var i, u, v,
  20610. end = data.length;
  20611. for( i = offset; i < end; i += stride ) {
  20612. u = data[ i ];
  20613. v = data[ i + 1 ];
  20614. // normalize to <0,1>
  20615. u /= 1023;
  20616. v /= 1023;
  20617. uvs.push( u, 1 - v );
  20618. }
  20619. };
  20620. function init_faces( indices ) {
  20621. var i,
  20622. a, b, c,
  20623. u1, v1, u2, v2, u3, v3,
  20624. m,
  20625. end = indices.length;
  20626. m = 0; // all faces defaulting to material 0
  20627. for( i = 0; i < end; i += 3 ) {
  20628. a = indices[ i ];
  20629. b = indices[ i + 1 ];
  20630. c = indices[ i + 2 ];
  20631. f3n( scope, normals, a, b, c, m, a, b, c );
  20632. u1 = uvs[ a * 2 ];
  20633. v1 = uvs[ a * 2 + 1 ];
  20634. u2 = uvs[ b * 2 ];
  20635. v2 = uvs[ b * 2 + 1 ];
  20636. u3 = uvs[ c * 2 ];
  20637. v3 = uvs[ c * 2 + 1 ];
  20638. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  20639. }
  20640. }
  20641. };
  20642. function vertex ( scope, x, y, z ) {
  20643. scope.vertices.push( new THREE.Vertex( new THREE.Vector3( x, y, z ) ) );
  20644. };
  20645. function f3n ( scope, normals, a, b, c, mi, nai, nbi, nci ) {
  20646. var nax = normals[ nai * 3 ],
  20647. nay = normals[ nai * 3 + 1 ],
  20648. naz = normals[ nai * 3 + 2 ],
  20649. nbx = normals[ nbi * 3 ],
  20650. nby = normals[ nbi * 3 + 1 ],
  20651. nbz = normals[ nbi * 3 + 2 ],
  20652. ncx = normals[ nci * 3 ],
  20653. ncy = normals[ nci * 3 + 1 ],
  20654. ncz = normals[ nci * 3 + 2 ];
  20655. var na = new THREE.Vector3( nax, nay, naz ),
  20656. nb = new THREE.Vector3( nbx, nby, nbz ),
  20657. nc = new THREE.Vector3( ncx, ncy, ncz );
  20658. scope.faces.push( new THREE.Face3( a, b, c, [ na, nb, nc ], null, mi ) );
  20659. };
  20660. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  20661. var uv = [];
  20662. uv.push( new THREE.UV( u1, v1 ) );
  20663. uv.push( new THREE.UV( u2, v2 ) );
  20664. uv.push( new THREE.UV( u3, v3 ) );
  20665. where.push( uv );
  20666. };
  20667. Model.prototype = new THREE.Geometry();
  20668. Model.prototype.constructor = Model;
  20669. callback( new Model() );
  20670. };
  20671. /**
  20672. * @author alteredq / http://alteredqualia.com/
  20673. */
  20674. THREE.ImmediateRenderObject = function ( ) {
  20675. THREE.Object3D.call( this );
  20676. this.render = function( renderCallback ) {
  20677. };
  20678. };
  20679. THREE.ImmediateRenderObject.prototype = new THREE.Object3D();
  20680. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  20681. /**
  20682. * @author mikael emtinger / http://gomo.se/
  20683. * @author alteredq / http://alteredqualia.com/
  20684. */
  20685. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  20686. THREE.Object3D.call( this );
  20687. this.lensFlares = [];
  20688. this.positionScreen = new THREE.Vector3();
  20689. this.customUpdateCallback = undefined;
  20690. if( texture !== undefined ) {
  20691. this.add( texture, size, distance, blending, color );
  20692. }
  20693. };
  20694. THREE.LensFlare.prototype = new THREE.Object3D();
  20695. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  20696. THREE.LensFlare.prototype.supr = THREE.Object3D.prototype;
  20697. /*
  20698. * Add: adds another flare
  20699. */
  20700. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  20701. if( size === undefined ) size = -1;
  20702. if( distance === undefined ) distance = 0;
  20703. if( opacity === undefined ) opacity = 1;
  20704. if( color === undefined ) color = new THREE.Color( 0xffffff );
  20705. if( blending === undefined ) blending = THREE.NormalBlending;
  20706. distance = Math.min( distance, Math.max( 0, distance ) );
  20707. this.lensFlares.push( { texture: texture, // THREE.Texture
  20708. size: size, // size in pixels (-1 = use texture.width)
  20709. distance: distance, // distance (0-1) from light source (0=at light source)
  20710. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  20711. scale: 1, // scale
  20712. rotation: 1, // rotation
  20713. opacity: opacity, // opacity
  20714. color: color, // color
  20715. blending: blending } ); // blending
  20716. };
  20717. /*
  20718. * Update lens flares update positions on all flares based on the screen position
  20719. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  20720. */
  20721. THREE.LensFlare.prototype.updateLensFlares = function () {
  20722. var f, fl = this.lensFlares.length;
  20723. var flare;
  20724. var vecX = -this.positionScreen.x * 2;
  20725. var vecY = -this.positionScreen.y * 2;
  20726. for( f = 0; f < fl; f ++ ) {
  20727. flare = this.lensFlares[ f ];
  20728. flare.x = this.positionScreen.x + vecX * flare.distance;
  20729. flare.y = this.positionScreen.y + vecY * flare.distance;
  20730. flare.wantedRotation = flare.x * Math.PI * 0.25;
  20731. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  20732. }
  20733. };
  20734. /**
  20735. * @author alteredq / http://alteredqualia.com/
  20736. */
  20737. THREE.MorphBlendMesh = function( geometry, material ) {
  20738. THREE.Mesh.call( this, geometry, material );
  20739. this.animationsMap = {};
  20740. this.animationsList = [];
  20741. // prepare default animation
  20742. // (all frames played together in 1 second)
  20743. var numFrames = this.geometry.morphTargets.length;
  20744. var name = "__default";
  20745. var startFrame = 0;
  20746. var endFrame = numFrames - 1;
  20747. var fps = numFrames / 1;
  20748. this.createAnimation( name, startFrame, endFrame, fps );
  20749. this.setAnimationWeight( name, 1 );
  20750. };
  20751. THREE.MorphBlendMesh.prototype = new THREE.Mesh();
  20752. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  20753. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  20754. var animation = {
  20755. startFrame: start,
  20756. endFrame: end,
  20757. length: end - start + 1,
  20758. fps: fps,
  20759. duration: ( end - start ) / fps,
  20760. lastFrame: 0,
  20761. currentFrame: 0,
  20762. active: false,
  20763. time: 0,
  20764. direction: 1,
  20765. weight: 1,
  20766. directionBackwards: false,
  20767. mirroredLoop: false
  20768. };
  20769. this.animationsMap[ name ] = animation;
  20770. this.animationsList.push( animation );
  20771. };
  20772. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  20773. var pattern = /([a-z]+)(\d+)/;
  20774. var firstAnimation, frameRanges = {};
  20775. var geometry = this.geometry;
  20776. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  20777. var morph = geometry.morphTargets[ i ];
  20778. var chunks = morph.name.match( pattern );
  20779. if ( chunks && chunks.length > 1 ) {
  20780. var name = chunks[ 1 ];
  20781. var num = chunks[ 2 ];
  20782. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  20783. var range = frameRanges[ name ];
  20784. if ( i < range.start ) range.start = i;
  20785. if ( i > range.end ) range.end = i;
  20786. if ( ! firstAnimation ) firstAnimation = name;
  20787. }
  20788. }
  20789. for ( var name in frameRanges ) {
  20790. var range = frameRanges[ name ];
  20791. this.createAnimation( name, range.start, range.end, fps );
  20792. }
  20793. this.firstAnimation = firstAnimation;
  20794. };
  20795. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  20796. var animation = this.animationsMap[ name ];
  20797. if ( animation ) {
  20798. animation.direction = 1;
  20799. animation.directionBackwards = false;
  20800. }
  20801. };
  20802. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  20803. var animation = this.animationsMap[ name ];
  20804. if ( animation ) {
  20805. animation.direction = -1;
  20806. animation.directionBackwards = true;
  20807. }
  20808. };
  20809. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  20810. var animation = this.animationsMap[ name ];
  20811. if ( animation ) {
  20812. animation.fps = fps;
  20813. animation.duration = ( animation.end - animation.start ) / animation.fps;
  20814. }
  20815. };
  20816. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  20817. var animation = this.animationsMap[ name ];
  20818. if ( animation ) {
  20819. animation.duration = duration;
  20820. animation.fps = ( animation.end - animation.start ) / animation.duration;
  20821. }
  20822. };
  20823. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  20824. var animation = this.animationsMap[ name ];
  20825. if ( animation ) {
  20826. animation.weight = weight;
  20827. }
  20828. };
  20829. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  20830. var animation = this.animationsMap[ name ];
  20831. if ( animation ) {
  20832. animation.time = time;
  20833. }
  20834. };
  20835. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  20836. var time = 0;
  20837. var animation = this.animationsMap[ name ];
  20838. if ( animation ) {
  20839. time = animation.time;
  20840. }
  20841. return time;
  20842. };
  20843. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  20844. var duration = -1;
  20845. var animation = this.animationsMap[ name ];
  20846. if ( animation ) {
  20847. duration = animation.duration;
  20848. }
  20849. return duration;
  20850. };
  20851. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  20852. var animation = this.animationsMap[ name ];
  20853. if ( animation ) {
  20854. animation.time = 0;
  20855. animation.active = true;
  20856. } else {
  20857. console.warn( "animation[" + name + "] undefined" );
  20858. }
  20859. };
  20860. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  20861. var animation = this.animationsMap[ name ];
  20862. if ( animation ) {
  20863. animation.active = false;
  20864. }
  20865. };
  20866. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  20867. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  20868. var animation = this.animationsList[ i ];
  20869. if ( ! animation.active ) continue;
  20870. var frameTime = animation.duration / animation.length;
  20871. animation.time += animation.direction * delta;
  20872. if ( animation.mirroredLoop ) {
  20873. if ( animation.time > animation.duration || animation.time < 0 ) {
  20874. animation.direction *= -1;
  20875. if ( animation.time > animation.duration ) {
  20876. animation.time = animation.duration;
  20877. animation.directionBackwards = true;
  20878. }
  20879. if ( animation.time < 0 ) {
  20880. animation.time = 0;
  20881. animation.directionBackwards = false;
  20882. }
  20883. }
  20884. } else {
  20885. animation.time = animation.time % animation.duration;
  20886. if ( animation.time < 0 ) animation.time += animation.duration;
  20887. }
  20888. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  20889. var weight = animation.weight;
  20890. if ( keyframe !== animation.currentFrame ) {
  20891. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  20892. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  20893. this.morphTargetInfluences[ keyframe ] = 0;
  20894. animation.lastFrame = animation.currentFrame;
  20895. animation.currentFrame = keyframe;
  20896. }
  20897. var mix = ( animation.time % frameTime ) / frameTime;
  20898. if ( animation.directionBackwards ) mix = 1 - mix;
  20899. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  20900. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  20901. }
  20902. };
  20903. /**
  20904. * @author mikael emtinger / http://gomo.se/
  20905. * @author alteredq / http://alteredqualia.com/
  20906. */
  20907. THREE.LensFlarePlugin = function ( ) {
  20908. var _gl, _renderer, _lensFlare = {};
  20909. this.init = function ( renderer ) {
  20910. _gl = renderer.context;
  20911. _renderer = renderer;
  20912. _lensFlare.vertices = new Float32Array( 8 + 8 );
  20913. _lensFlare.faces = new Uint16Array( 6 );
  20914. var i = 0;
  20915. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  20916. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  20917. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  20918. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  20919. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20920. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  20921. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  20922. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  20923. i = 0;
  20924. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  20925. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  20926. // buffers
  20927. _lensFlare.vertexBuffer = _gl.createBuffer();
  20928. _lensFlare.elementBuffer = _gl.createBuffer();
  20929. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  20930. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  20931. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  20932. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  20933. // textures
  20934. _lensFlare.tempTexture = _gl.createTexture();
  20935. _lensFlare.occlusionTexture = _gl.createTexture();
  20936. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  20937. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  20938. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20939. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20940. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20941. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20942. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  20943. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  20944. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  20945. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  20946. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  20947. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  20948. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  20949. _lensFlare.hasVertexTexture = false;
  20950. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  20951. } else {
  20952. _lensFlare.hasVertexTexture = true;
  20953. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  20954. }
  20955. _lensFlare.attributes = {};
  20956. _lensFlare.uniforms = {};
  20957. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  20958. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  20959. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  20960. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  20961. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  20962. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  20963. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  20964. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  20965. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  20966. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  20967. _lensFlare.attributesEnabled = false;
  20968. };
  20969. /*
  20970. * Render lens flares
  20971. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  20972. * reads these back and calculates occlusion.
  20973. * Then _lensFlare.update_lensFlares() is called to re-position and
  20974. * update transparency of flares. Then they are rendered.
  20975. *
  20976. */
  20977. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  20978. var flares = scene.__webglFlares,
  20979. nFlares = flares.length;
  20980. if ( ! nFlares ) return;
  20981. var tempPosition = new THREE.Vector3();
  20982. var invAspect = viewportHeight / viewportWidth,
  20983. halfViewportWidth = viewportWidth * 0.5,
  20984. halfViewportHeight = viewportHeight * 0.5;
  20985. var size = 16 / viewportHeight,
  20986. scale = new THREE.Vector2( size * invAspect, size );
  20987. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  20988. screenPositionPixels = new THREE.Vector2( 1, 1 );
  20989. var uniforms = _lensFlare.uniforms,
  20990. attributes = _lensFlare.attributes;
  20991. // set _lensFlare program and reset blending
  20992. _gl.useProgram( _lensFlare.program );
  20993. if ( ! _lensFlare.attributesEnabled ) {
  20994. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  20995. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  20996. _lensFlare.attributesEnabled = true;
  20997. }
  20998. // loop through all lens flares to update their occlusion and positions
  20999. // setup gl and common used attribs/unforms
  21000. _gl.uniform1i( uniforms.occlusionMap, 0 );
  21001. _gl.uniform1i( uniforms.map, 1 );
  21002. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  21003. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21004. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21005. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  21006. _gl.disable( _gl.CULL_FACE );
  21007. _gl.depthMask( false );
  21008. var i, j, jl, flare, sprite;
  21009. for ( i = 0; i < nFlares; i ++ ) {
  21010. size = 16 / viewportHeight;
  21011. scale.set( size * invAspect, size );
  21012. // calc object screen position
  21013. flare = flares[ i ];
  21014. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  21015. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  21016. camera.projectionMatrix.multiplyVector3( tempPosition );
  21017. // setup arrays for gl programs
  21018. screenPosition.copy( tempPosition )
  21019. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  21020. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  21021. // screen cull
  21022. if ( _lensFlare.hasVertexTexture || (
  21023. screenPositionPixels.x > 0 &&
  21024. screenPositionPixels.x < viewportWidth &&
  21025. screenPositionPixels.y > 0 &&
  21026. screenPositionPixels.y < viewportHeight ) ) {
  21027. // save current RGB to temp texture
  21028. _gl.activeTexture( _gl.TEXTURE1 );
  21029. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21030. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21031. // render pink quad
  21032. _gl.uniform1i( uniforms.renderType, 0 );
  21033. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21034. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21035. _gl.disable( _gl.BLEND );
  21036. _gl.enable( _gl.DEPTH_TEST );
  21037. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21038. // copy result to occlusionMap
  21039. _gl.activeTexture( _gl.TEXTURE0 );
  21040. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  21041. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  21042. // restore graphics
  21043. _gl.uniform1i( uniforms.renderType, 1 );
  21044. _gl.disable( _gl.DEPTH_TEST );
  21045. _gl.activeTexture( _gl.TEXTURE1 );
  21046. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  21047. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21048. // update object positions
  21049. flare.positionScreen.copy( screenPosition )
  21050. if ( flare.customUpdateCallback ) {
  21051. flare.customUpdateCallback( flare );
  21052. } else {
  21053. flare.updateLensFlares();
  21054. }
  21055. // render flares
  21056. _gl.uniform1i( uniforms.renderType, 2 );
  21057. _gl.enable( _gl.BLEND );
  21058. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  21059. sprite = flare.lensFlares[ j ];
  21060. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  21061. screenPosition.x = sprite.x;
  21062. screenPosition.y = sprite.y;
  21063. screenPosition.z = sprite.z;
  21064. size = sprite.size * sprite.scale / viewportHeight;
  21065. scale.x = size * invAspect;
  21066. scale.y = size;
  21067. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  21068. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  21069. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21070. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21071. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21072. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21073. _renderer.setTexture( sprite.texture, 1 );
  21074. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21075. }
  21076. }
  21077. }
  21078. }
  21079. // restore gl
  21080. _gl.enable( _gl.CULL_FACE );
  21081. _gl.enable( _gl.DEPTH_TEST );
  21082. _gl.depthMask( true );
  21083. };
  21084. function createProgram ( shader ) {
  21085. var program = _gl.createProgram();
  21086. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21087. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21088. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21089. _gl.shaderSource( vertexShader, shader.vertexShader );
  21090. _gl.compileShader( fragmentShader );
  21091. _gl.compileShader( vertexShader );
  21092. _gl.attachShader( program, fragmentShader );
  21093. _gl.attachShader( program, vertexShader );
  21094. _gl.linkProgram( program );
  21095. return program;
  21096. };
  21097. };/**
  21098. * @author alteredq / http://alteredqualia.com/
  21099. */
  21100. THREE.ShadowMapPlugin = function ( ) {
  21101. var _gl,
  21102. _renderer,
  21103. _depthMaterial, _depthMaterialMorph,
  21104. _frustum = new THREE.Frustum(),
  21105. _projScreenMatrix = new THREE.Matrix4(),
  21106. _min = new THREE.Vector3(),
  21107. _max = new THREE.Vector3();
  21108. this.init = function ( renderer ) {
  21109. _gl = renderer.context;
  21110. _renderer = renderer;
  21111. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21112. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21113. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21114. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21115. _depthMaterial._shadowPass = true;
  21116. _depthMaterialMorph._shadowPass = true;
  21117. };
  21118. this.render = function ( scene, camera ) {
  21119. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  21120. this.update( scene, camera );
  21121. };
  21122. this.update = function ( scene, camera ) {
  21123. var i, il, j, jl, n,
  21124. shadowMap, shadowMatrix, shadowCamera,
  21125. program, buffer, material,
  21126. webglObject, object, light,
  21127. renderList,
  21128. lights = [],
  21129. k = 0,
  21130. fog = null;
  21131. // set GL state for depth map
  21132. _gl.clearColor( 1, 1, 1, 1 );
  21133. _gl.disable( _gl.BLEND );
  21134. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.FRONT );
  21135. _renderer.setDepthTest( true );
  21136. // preprocess lights
  21137. // - skip lights that are not casting shadows
  21138. // - create virtual lights for cascaded shadow maps
  21139. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  21140. light = scene.__lights[ i ];
  21141. if ( ! light.castShadow ) continue;
  21142. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  21143. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  21144. var virtualLight;
  21145. if ( ! light.shadowCascadeArray[ n ] ) {
  21146. virtualLight = createVirtualLight( light, n );
  21147. virtualLight.originalCamera = camera;
  21148. var gyro = new THREE.Gyroscope();
  21149. gyro.position = light.shadowCascadeOffset;
  21150. gyro.add( virtualLight );
  21151. gyro.add( virtualLight.target );
  21152. camera.add( gyro );
  21153. light.shadowCascadeArray[ n ] = virtualLight;
  21154. console.log( "Created virtualLight", virtualLight );
  21155. } else {
  21156. virtualLight = light.shadowCascadeArray[ n ];
  21157. }
  21158. updateVirtualLight( light, n );
  21159. lights[ k ] = virtualLight;
  21160. k ++;
  21161. }
  21162. } else {
  21163. lights[ k ] = light;
  21164. k ++;
  21165. }
  21166. }
  21167. // render depth map
  21168. for ( i = 0, il = lights.length; i < il; i ++ ) {
  21169. light = lights[ i ];
  21170. if ( ! light.shadowMap ) {
  21171. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  21172. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  21173. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  21174. light.shadowMatrix = new THREE.Matrix4();
  21175. }
  21176. if ( ! light.shadowCamera ) {
  21177. if ( light instanceof THREE.SpotLight ) {
  21178. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  21179. } else if ( light instanceof THREE.DirectionalLight ) {
  21180. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  21181. } else {
  21182. console.error( "Unsupported light type for shadow" );
  21183. continue;
  21184. }
  21185. scene.add( light.shadowCamera );
  21186. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21187. }
  21188. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  21189. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  21190. light.shadowCamera.add( light.cameraHelper );
  21191. }
  21192. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  21193. updateShadowCamera( camera, light );
  21194. }
  21195. shadowMap = light.shadowMap;
  21196. shadowMatrix = light.shadowMatrix;
  21197. shadowCamera = light.shadowCamera;
  21198. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  21199. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  21200. shadowCamera.updateMatrixWorld();
  21201. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  21202. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  21203. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  21204. // compute shadow matrix
  21205. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  21206. 0.0, 0.5, 0.0, 0.5,
  21207. 0.0, 0.0, 0.5, 0.5,
  21208. 0.0, 0.0, 0.0, 1.0 );
  21209. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  21210. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  21211. // update camera matrices and frustum
  21212. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  21213. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  21214. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  21215. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  21216. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  21217. _frustum.setFromMatrix( _projScreenMatrix );
  21218. // render shadow map
  21219. _renderer.setRenderTarget( shadowMap );
  21220. _renderer.clear();
  21221. // set object matrices & frustum culling
  21222. renderList = scene.__webglObjects;
  21223. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21224. webglObject = renderList[ j ];
  21225. object = webglObject.object;
  21226. webglObject.render = false;
  21227. if ( object.visible && object.castShadow ) {
  21228. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21229. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21230. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  21231. webglObject.render = true;
  21232. }
  21233. }
  21234. }
  21235. // render regular objects
  21236. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21237. webglObject = renderList[ j ];
  21238. if ( webglObject.render ) {
  21239. object = webglObject.object;
  21240. buffer = webglObject.buffer;
  21241. _renderer.setObjectFaces( object );
  21242. if ( object.customDepthMaterial ) {
  21243. material = object.customDepthMaterial;
  21244. } else if ( object.geometry.morphTargets.length ) {
  21245. material = _depthMaterialMorph;
  21246. } else {
  21247. material = _depthMaterial;
  21248. }
  21249. if ( buffer instanceof THREE.BufferGeometry ) {
  21250. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  21251. } else {
  21252. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  21253. }
  21254. }
  21255. }
  21256. // set matrices and render immediate objects
  21257. renderList = scene.__webglObjectsImmediate;
  21258. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21259. webglObject = renderList[ j ];
  21260. object = webglObject.object;
  21261. if ( object.visible && object.castShadow ) {
  21262. if( object.matrixAutoUpdate ) {
  21263. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21264. }
  21265. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  21266. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  21267. }
  21268. }
  21269. }
  21270. // restore GL state
  21271. var clearColor = _renderer.getClearColor(),
  21272. clearAlpha = _renderer.getClearAlpha();
  21273. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21274. _gl.enable( _gl.BLEND );
  21275. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.BACK );
  21276. };
  21277. function createVirtualLight( light, cascade ) {
  21278. var virtualLight = new THREE.DirectionalLight();
  21279. virtualLight.isVirtual = true;
  21280. virtualLight.onlyShadow = true;
  21281. virtualLight.castShadow = true;
  21282. virtualLight.shadowCameraNear = light.shadowCameraNear;
  21283. virtualLight.shadowCameraFar = light.shadowCameraFar;
  21284. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  21285. virtualLight.shadowCameraRight = light.shadowCameraRight;
  21286. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  21287. virtualLight.shadowCameraTop = light.shadowCameraTop;
  21288. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21289. virtualLight.shadowDarkness = light.shadowDarkness;
  21290. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21291. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  21292. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  21293. virtualLight.pointsWorld = [];
  21294. virtualLight.pointsFrustum = [];
  21295. var pointsWorld = virtualLight.pointsWorld,
  21296. pointsFrustum = virtualLight.pointsFrustum;
  21297. for ( var i = 0; i < 8; i ++ ) {
  21298. pointsWorld[ i ] = new THREE.Vector3();
  21299. pointsFrustum[ i ] = new THREE.Vector3();
  21300. }
  21301. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21302. var farZ = light.shadowCascadeFarZ[ cascade ];
  21303. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  21304. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  21305. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  21306. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  21307. pointsFrustum[ 4 ].set( -1, -1, farZ );
  21308. pointsFrustum[ 5 ].set( 1, -1, farZ );
  21309. pointsFrustum[ 6 ].set( -1, 1, farZ );
  21310. pointsFrustum[ 7 ].set( 1, 1, farZ );
  21311. return virtualLight;
  21312. }
  21313. // Synchronize virtual light with the original light
  21314. function updateVirtualLight( light, cascade ) {
  21315. var virtualLight = light.shadowCascadeArray[ cascade ];
  21316. virtualLight.position.copy( light.position );
  21317. virtualLight.target.position.copy( light.target.position );
  21318. virtualLight.lookAt( virtualLight.target );
  21319. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  21320. virtualLight.shadowDarkness = light.shadowDarkness;
  21321. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  21322. var nearZ = light.shadowCascadeNearZ[ cascade ];
  21323. var farZ = light.shadowCascadeFarZ[ cascade ];
  21324. var pointsFrustum = virtualLight.pointsFrustum;
  21325. pointsFrustum[ 0 ].z = nearZ;
  21326. pointsFrustum[ 1 ].z = nearZ;
  21327. pointsFrustum[ 2 ].z = nearZ;
  21328. pointsFrustum[ 3 ].z = nearZ;
  21329. pointsFrustum[ 4 ].z = farZ;
  21330. pointsFrustum[ 5 ].z = farZ;
  21331. pointsFrustum[ 6 ].z = farZ;
  21332. pointsFrustum[ 7 ].z = farZ;
  21333. }
  21334. // Fit shadow camera's ortho frustum to camera frustum
  21335. function updateShadowCamera( camera, light ) {
  21336. var shadowCamera = light.shadowCamera,
  21337. pointsFrustum = light.pointsFrustum,
  21338. pointsWorld = light.pointsWorld;
  21339. _min.set( Infinity, Infinity, Infinity );
  21340. _max.set( -Infinity, -Infinity, -Infinity );
  21341. for ( var i = 0; i < 8; i ++ ) {
  21342. var p = pointsWorld[ i ];
  21343. p.copy( pointsFrustum[ i ] );
  21344. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  21345. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  21346. if ( p.x < _min.x ) _min.x = p.x;
  21347. if ( p.x > _max.x ) _max.x = p.x;
  21348. if ( p.y < _min.y ) _min.y = p.y;
  21349. if ( p.y > _max.y ) _max.y = p.y;
  21350. if ( p.z < _min.z ) _min.z = p.z;
  21351. if ( p.z > _max.z ) _max.z = p.z;
  21352. }
  21353. shadowCamera.left = _min.x;
  21354. shadowCamera.right = _max.x;
  21355. shadowCamera.top = _max.y;
  21356. shadowCamera.bottom = _min.y;
  21357. // can't really fit near/far
  21358. //shadowCamera.near = _min.z;
  21359. //shadowCamera.far = _max.z;
  21360. shadowCamera.updateProjectionMatrix();
  21361. }
  21362. };
  21363. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  21364. /**
  21365. * @author mikael emtinger / http://gomo.se/
  21366. * @author alteredq / http://alteredqualia.com/
  21367. */
  21368. THREE.SpritePlugin = function ( ) {
  21369. var _gl, _renderer, _sprite = {};
  21370. this.init = function ( renderer ) {
  21371. _gl = renderer.context;
  21372. _renderer = renderer;
  21373. _sprite.vertices = new Float32Array( 8 + 8 );
  21374. _sprite.faces = new Uint16Array( 6 );
  21375. var i = 0;
  21376. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  21377. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 0
  21378. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  21379. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 1
  21380. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  21381. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 2
  21382. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  21383. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 3
  21384. i = 0;
  21385. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  21386. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  21387. _sprite.vertexBuffer = _gl.createBuffer();
  21388. _sprite.elementBuffer = _gl.createBuffer();
  21389. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21390. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  21391. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21392. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  21393. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  21394. _sprite.attributes = {};
  21395. _sprite.uniforms = {};
  21396. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  21397. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  21398. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  21399. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  21400. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  21401. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  21402. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  21403. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  21404. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  21405. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  21406. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  21407. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  21408. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  21409. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  21410. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  21411. _sprite.attributesEnabled = false;
  21412. };
  21413. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  21414. var sprites = scene.__webglSprites,
  21415. nSprites = sprites.length;
  21416. if ( ! nSprites ) return;
  21417. var attributes = _sprite.attributes,
  21418. uniforms = _sprite.uniforms;
  21419. var invAspect = viewportHeight / viewportWidth;
  21420. var halfViewportWidth = viewportWidth * 0.5,
  21421. halfViewportHeight = viewportHeight * 0.5;
  21422. var mergeWith3D = true;
  21423. // setup gl
  21424. _gl.useProgram( _sprite.program );
  21425. if ( ! _sprite.attributesEnabled ) {
  21426. _gl.enableVertexAttribArray( attributes.position );
  21427. _gl.enableVertexAttribArray( attributes.uv );
  21428. _sprite.attributesEnabled = true;
  21429. }
  21430. _gl.disable( _gl.CULL_FACE );
  21431. _gl.enable( _gl.BLEND );
  21432. _gl.depthMask( true );
  21433. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  21434. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  21435. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  21436. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  21437. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  21438. _gl.activeTexture( _gl.TEXTURE0 );
  21439. _gl.uniform1i( uniforms.map, 0 );
  21440. // update positions and sort
  21441. var i, sprite, screenPosition, size, scale = [];
  21442. for( i = 0; i < nSprites; i ++ ) {
  21443. sprite = sprites[ i ];
  21444. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21445. if( ! sprite.useScreenCoordinates ) {
  21446. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld);
  21447. sprite.z = - sprite._modelViewMatrix.elements[14];
  21448. } else {
  21449. sprite.z = - sprite.position.z;
  21450. }
  21451. }
  21452. sprites.sort( painterSort );
  21453. // render all sprites
  21454. for( i = 0; i < nSprites; i ++ ) {
  21455. sprite = sprites[ i ];
  21456. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  21457. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  21458. if ( sprite.useScreenCoordinates ) {
  21459. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  21460. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  21461. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  21462. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  21463. } else {
  21464. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  21465. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  21466. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements);
  21467. }
  21468. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  21469. scale[ 0 ] = size * invAspect * sprite.scale.x;
  21470. scale[ 1 ] = size * sprite.scale.y;
  21471. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  21472. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  21473. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  21474. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  21475. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  21476. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  21477. _gl.uniform2fv( uniforms.scale, scale );
  21478. if ( sprite.mergeWith3D && !mergeWith3D ) {
  21479. _gl.enable( _gl.DEPTH_TEST );
  21480. mergeWith3D = true;
  21481. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  21482. _gl.disable( _gl.DEPTH_TEST );
  21483. mergeWith3D = false;
  21484. }
  21485. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  21486. _renderer.setTexture( sprite.map, 0 );
  21487. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  21488. }
  21489. }
  21490. // restore gl
  21491. _gl.enable( _gl.CULL_FACE );
  21492. _gl.enable( _gl.DEPTH_TEST );
  21493. _gl.depthMask( true );
  21494. };
  21495. function createProgram ( shader ) {
  21496. var program = _gl.createProgram();
  21497. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  21498. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  21499. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  21500. _gl.shaderSource( vertexShader, shader.vertexShader );
  21501. _gl.compileShader( fragmentShader );
  21502. _gl.compileShader( vertexShader );
  21503. _gl.attachShader( program, fragmentShader );
  21504. _gl.attachShader( program, vertexShader );
  21505. _gl.linkProgram( program );
  21506. return program;
  21507. };
  21508. function painterSort ( a, b ) {
  21509. return b.z - a.z;
  21510. };
  21511. };/**
  21512. * @author alteredq / http://alteredqualia.com/
  21513. */
  21514. THREE.DepthPassPlugin = function ( ) {
  21515. this.enabled = false;
  21516. this.renderTarget = null;
  21517. var _gl,
  21518. _renderer,
  21519. _depthMaterial, _depthMaterialMorph,
  21520. _frustum = new THREE.Frustum(),
  21521. _projScreenMatrix = new THREE.Matrix4();
  21522. this.init = function ( renderer ) {
  21523. _gl = renderer.context;
  21524. _renderer = renderer;
  21525. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  21526. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  21527. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  21528. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  21529. _depthMaterial._shadowPass = true;
  21530. _depthMaterialMorph._shadowPass = true;
  21531. };
  21532. this.render = function ( scene, camera ) {
  21533. if ( ! this.enabled ) return;
  21534. this.update( scene, camera );
  21535. };
  21536. this.update = function ( scene, camera ) {
  21537. var i, il, j, jl, n,
  21538. program, buffer, material,
  21539. webglObject, object, light,
  21540. renderList,
  21541. fog = null;
  21542. // set GL state for depth map
  21543. _gl.clearColor( 1, 1, 1, 1 );
  21544. _gl.disable( _gl.BLEND );
  21545. _renderer.setDepthTest( true );
  21546. // update scene
  21547. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  21548. // update camera matrices and frustum
  21549. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  21550. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  21551. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  21552. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  21553. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  21554. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  21555. _frustum.setFromMatrix( _projScreenMatrix );
  21556. // render depth map
  21557. _renderer.setRenderTarget( this.renderTarget );
  21558. _renderer.clear();
  21559. // set object matrices & frustum culling
  21560. renderList = scene.__webglObjects;
  21561. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21562. webglObject = renderList[ j ];
  21563. object = webglObject.object;
  21564. webglObject.render = false;
  21565. if ( object.visible ) {
  21566. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  21567. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21568. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  21569. webglObject.render = true;
  21570. }
  21571. }
  21572. }
  21573. // render regular objects
  21574. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21575. webglObject = renderList[ j ];
  21576. if ( webglObject.render ) {
  21577. object = webglObject.object;
  21578. buffer = webglObject.buffer;
  21579. _renderer.setObjectFaces( object );
  21580. if ( object.customDepthMaterial ) {
  21581. material = object.customDepthMaterial;
  21582. } else if ( object.geometry.morphTargets.length ) {
  21583. material = _depthMaterialMorph;
  21584. } else {
  21585. material = _depthMaterial;
  21586. }
  21587. if ( buffer instanceof THREE.BufferGeometry ) {
  21588. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  21589. } else {
  21590. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  21591. }
  21592. }
  21593. }
  21594. // set matrices and render immediate objects
  21595. renderList = scene.__webglObjectsImmediate;
  21596. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  21597. webglObject = renderList[ j ];
  21598. object = webglObject.object;
  21599. if ( object.visible && object.castShadow ) {
  21600. if( object.matrixAutoUpdate ) {
  21601. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  21602. }
  21603. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  21604. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  21605. }
  21606. }
  21607. // restore GL state
  21608. var clearColor = _renderer.getClearColor(),
  21609. clearAlpha = _renderer.getClearAlpha();
  21610. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  21611. _gl.enable( _gl.BLEND );
  21612. };
  21613. };
  21614. /**
  21615. * @author mrdoob / http://mrdoob.com/
  21616. * @author marklundin / http://mark-lundin.com/
  21617. * @author alteredq / http://alteredqualia.com/
  21618. */
  21619. if ( THREE.WebGLRenderer ) {
  21620. THREE.AnaglyphWebGLRenderer = function ( parameters ) {
  21621. THREE.WebGLRenderer.call( this, parameters );
  21622. this.autoUpdateScene = false;
  21623. var _this = this, _setSize = this.setSize, _render = this.render;
  21624. var _cameraL = new THREE.PerspectiveCamera(),
  21625. _cameraR = new THREE.PerspectiveCamera();
  21626. var eyeRight = new THREE.Matrix4(),
  21627. eyeLeft = new THREE.Matrix4(),
  21628. focalLength = 125,
  21629. _aspect, _near, _far, _fov;
  21630. _cameraL.matrixAutoUpdate = _cameraR.matrixAutoUpdate = false;
  21631. var _params = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  21632. var _renderTargetL = new THREE.WebGLRenderTarget( 512, 512, _params ),
  21633. _renderTargetR = new THREE.WebGLRenderTarget( 512, 512, _params );
  21634. var _camera = new THREE.PerspectiveCamera( 53, 1, 1, 10000 );
  21635. _camera.position.z = 2;
  21636. var _material = new THREE.ShaderMaterial( {
  21637. uniforms: {
  21638. "mapLeft": { type: "t", value: 0, texture: _renderTargetL },
  21639. "mapRight": { type: "t", value: 1, texture: _renderTargetR }
  21640. },
  21641. vertexShader: [
  21642. "varying vec2 vUv;",
  21643. "void main() {",
  21644. "vUv = vec2( uv.x, 1.0 - uv.y );",
  21645. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  21646. "}"
  21647. ].join("\n"),
  21648. fragmentShader: [
  21649. "uniform sampler2D mapLeft;",
  21650. "uniform sampler2D mapRight;",
  21651. "varying vec2 vUv;",
  21652. "void main() {",
  21653. "vec4 colorL, colorR;",
  21654. "vec2 uv = vUv;",
  21655. "colorL = texture2D( mapLeft, uv );",
  21656. "colorR = texture2D( mapRight, uv );",
  21657. // http://3dtv.at/Knowhow/AnaglyphComparison_en.aspx
  21658. "gl_FragColor = vec4( colorL.g * 0.7 + colorL.b * 0.3, colorR.g, colorR.b, colorL.a + colorR.a ) * 1.1;",
  21659. "}"
  21660. ].join("\n")
  21661. } );
  21662. var _scene = new THREE.Scene();
  21663. var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), _material );
  21664. mesh.rotation.x = Math.PI / 2;
  21665. _scene.add( mesh );
  21666. _scene.add( _camera );
  21667. this.setSize = function ( width, height ) {
  21668. _setSize.call( _this, width, height );
  21669. _renderTargetL.width = width;
  21670. _renderTargetL.height = height;
  21671. _renderTargetR.width = width;
  21672. _renderTargetR.height = height;
  21673. };
  21674. /*
  21675. * Renderer now uses an asymmetric perspective projection (http://paulbourke.net/miscellaneous/stereographics/stereorender/).
  21676. * Each camera is offset by the eye seperation and its projection matrix is also skewed asymetrically back to converge on the same
  21677. * projection plane. Added a focal length parameter to, this is where the parallax is equal to 0.
  21678. */
  21679. this.render = function ( scene, camera, renderTarget, forceClear ) {
  21680. scene.updateMatrixWorld();
  21681. var hasCameraChanged = ( _aspect !== camera.aspect ) || ( _near !== camera.near ) || ( _far !== camera.far ) || ( _fov !== camera.fov );
  21682. if( hasCameraChanged ) {
  21683. _aspect = camera.aspect;
  21684. _near = camera.near;
  21685. _far = camera.far;
  21686. _fov = camera.fov;
  21687. var projectionMatrix = camera.projectionMatrix.clone(),
  21688. eyeSep = focalLength / 30 * 0.5,
  21689. eyeSepOnProjection = eyeSep * _near / focalLength,
  21690. ymax = _near * Math.tan( _fov * Math.PI / 360 ),
  21691. xmin, xmax;
  21692. // translate xOffset
  21693. eyeRight.elements[12] = eyeSep;
  21694. eyeLeft.elements[12] = -eyeSep;
  21695. // for left eye
  21696. xmin = -ymax * _aspect + eyeSepOnProjection;
  21697. xmax = ymax * _aspect + eyeSepOnProjection;
  21698. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  21699. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  21700. _cameraL.projectionMatrix.copy( projectionMatrix );
  21701. // for right eye
  21702. xmin = -ymax * _aspect - eyeSepOnProjection;
  21703. xmax = ymax * _aspect - eyeSepOnProjection;
  21704. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  21705. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  21706. _cameraR.projectionMatrix.copy( projectionMatrix );
  21707. }
  21708. _cameraL.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeLeft );
  21709. _cameraL.position.copy( camera.position );
  21710. _cameraL.near = camera.near;
  21711. _cameraL.far = camera.far;
  21712. _render.call( _this, scene, _cameraL, _renderTargetL, true );
  21713. _cameraR.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeRight );
  21714. _cameraR.position.copy( camera.position );
  21715. _cameraR.near = camera.near;
  21716. _cameraR.far = camera.far;
  21717. _render.call( _this, scene, _cameraR, _renderTargetR, true );
  21718. _scene.updateMatrixWorld();
  21719. _render.call( _this, _scene, _camera );
  21720. };
  21721. };
  21722. };
  21723. /**
  21724. * @author alteredq / http://alteredqualia.com/
  21725. */
  21726. if ( THREE.WebGLRenderer ) {
  21727. THREE.CrosseyedWebGLRenderer = function ( parameters ) {
  21728. THREE.WebGLRenderer.call( this, parameters );
  21729. this.autoClear = false;
  21730. var _this = this, _setSize = this.setSize, _render = this.render;
  21731. var _width, _height;
  21732. var _cameraL = new THREE.PerspectiveCamera();
  21733. _cameraL.target = new THREE.Vector3( 0, 0, 0 );
  21734. var _cameraR = new THREE.PerspectiveCamera();
  21735. _cameraR.target = new THREE.Vector3( 0, 0, 0 );
  21736. _this.separation = 10;
  21737. if ( parameters && parameters.separation !== undefined ) _this.separation = parameters.separation;
  21738. var SCREEN_WIDTH = window.innerWidth;
  21739. var SCREEN_HEIGHT = window.innerHeight;
  21740. var HALF_WIDTH = SCREEN_WIDTH / 2;
  21741. this.setSize = function ( width, height ) {
  21742. _setSize.call( _this, width, height );
  21743. _width = width/2;
  21744. _height = height;
  21745. };
  21746. this.render = function ( scene, camera, renderTarget, forceClear ) {
  21747. this.clear();
  21748. _cameraL.fov = camera.fov;
  21749. _cameraL.aspect = 0.5 * camera.aspect;
  21750. _cameraL.near = camera.near;
  21751. _cameraL.far = camera.far;
  21752. _cameraL.updateProjectionMatrix();
  21753. _cameraL.position.copy( camera.position );
  21754. _cameraL.target.copy( camera.target );
  21755. _cameraL.translateX( _this.separation );
  21756. _cameraL.lookAt( _cameraL.target );
  21757. _cameraR.projectionMatrix = _cameraL.projectionMatrix;
  21758. _cameraR.position.copy( camera.position );
  21759. _cameraR.target.copy( camera.target );
  21760. _cameraR.translateX( - _this.separation );
  21761. _cameraR.lookAt( _cameraR.target );
  21762. this.setViewport( 0, 0, _width, _height );
  21763. _render.call( _this, scene, _cameraL );
  21764. this.setViewport( _width, 0, _width, _height );
  21765. _render.call( _this, scene, _cameraR, false );
  21766. };
  21767. };
  21768. }
  21769. /**
  21770. * @author mikael emtinger / http://gomo.se/
  21771. *
  21772. */
  21773. THREE.ShaderFlares = {
  21774. 'lensFlareVertexTexture': {
  21775. vertexShader: [
  21776. "uniform vec3 screenPosition;",
  21777. "uniform vec2 scale;",
  21778. "uniform float rotation;",
  21779. "uniform int renderType;",
  21780. "uniform sampler2D occlusionMap;",
  21781. "attribute vec2 position;",
  21782. "attribute vec2 uv;",
  21783. "varying vec2 vUV;",
  21784. "varying float vVisibility;",
  21785. "void main() {",
  21786. "vUV = uv;",
  21787. "vec2 pos = position;",
  21788. "if( renderType == 2 ) {",
  21789. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  21790. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  21791. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  21792. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  21793. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  21794. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  21795. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  21796. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  21797. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  21798. "vVisibility = ( visibility.r / 9.0 ) *",
  21799. "( 1.0 - visibility.g / 9.0 ) *",
  21800. "( visibility.b / 9.0 ) *",
  21801. "( 1.0 - visibility.a / 9.0 );",
  21802. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21803. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21804. "}",
  21805. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21806. "}"
  21807. ].join( "\n" ),
  21808. fragmentShader: [
  21809. "precision mediump float;",
  21810. "uniform sampler2D map;",
  21811. "uniform float opacity;",
  21812. "uniform int renderType;",
  21813. "uniform vec3 color;",
  21814. "varying vec2 vUV;",
  21815. "varying float vVisibility;",
  21816. "void main() {",
  21817. // pink square
  21818. "if( renderType == 0 ) {",
  21819. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  21820. // restore
  21821. "} else if( renderType == 1 ) {",
  21822. "gl_FragColor = texture2D( map, vUV );",
  21823. // flare
  21824. "} else {",
  21825. "vec4 texture = texture2D( map, vUV );",
  21826. "texture.a *= opacity * vVisibility;",
  21827. "gl_FragColor = texture;",
  21828. "gl_FragColor.rgb *= color;",
  21829. "}",
  21830. "}"
  21831. ].join( "\n" )
  21832. },
  21833. 'lensFlare': {
  21834. vertexShader: [
  21835. "uniform vec3 screenPosition;",
  21836. "uniform vec2 scale;",
  21837. "uniform float rotation;",
  21838. "uniform int renderType;",
  21839. "attribute vec2 position;",
  21840. "attribute vec2 uv;",
  21841. "varying vec2 vUV;",
  21842. "void main() {",
  21843. "vUV = uv;",
  21844. "vec2 pos = position;",
  21845. "if( renderType == 2 ) {",
  21846. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  21847. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  21848. "}",
  21849. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  21850. "}"
  21851. ].join( "\n" ),
  21852. fragmentShader: [
  21853. "precision mediump float;",
  21854. "uniform sampler2D map;",
  21855. "uniform sampler2D occlusionMap;",
  21856. "uniform float opacity;",
  21857. "uniform int renderType;",
  21858. "uniform vec3 color;",
  21859. "varying vec2 vUV;",
  21860. "void main() {",
  21861. // pink square
  21862. "if( renderType == 0 ) {",
  21863. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  21864. // restore
  21865. "} else if( renderType == 1 ) {",
  21866. "gl_FragColor = texture2D( map, vUV );",
  21867. // flare
  21868. "} else {",
  21869. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  21870. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  21871. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  21872. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  21873. "visibility = ( 1.0 - visibility / 4.0 );",
  21874. "vec4 texture = texture2D( map, vUV );",
  21875. "texture.a *= opacity * visibility;",
  21876. "gl_FragColor = texture;",
  21877. "gl_FragColor.rgb *= color;",
  21878. "}",
  21879. "}"
  21880. ].join( "\n" )
  21881. }
  21882. };
  21883. /**
  21884. * @author mikael emtinger / http://gomo.se/
  21885. *
  21886. */
  21887. THREE.ShaderSprite = {
  21888. 'sprite': {
  21889. vertexShader: [
  21890. "uniform int useScreenCoordinates;",
  21891. "uniform int affectedByDistance;",
  21892. "uniform vec3 screenPosition;",
  21893. "uniform mat4 modelViewMatrix;",
  21894. "uniform mat4 projectionMatrix;",
  21895. "uniform float rotation;",
  21896. "uniform vec2 scale;",
  21897. "uniform vec2 alignment;",
  21898. "uniform vec2 uvOffset;",
  21899. "uniform vec2 uvScale;",
  21900. "attribute vec2 position;",
  21901. "attribute vec2 uv;",
  21902. "varying vec2 vUV;",
  21903. "void main() {",
  21904. "vUV = uvOffset + uv * uvScale;",
  21905. "vec2 alignedPosition = position + alignment;",
  21906. "vec2 rotatedPosition;",
  21907. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  21908. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  21909. "vec4 finalPosition;",
  21910. "if( useScreenCoordinates != 0 ) {",
  21911. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  21912. "} else {",
  21913. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  21914. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  21915. "}",
  21916. "gl_Position = finalPosition;",
  21917. "}"
  21918. ].join( "\n" ),
  21919. fragmentShader: [
  21920. "precision mediump float;",
  21921. "uniform vec3 color;",
  21922. "uniform sampler2D map;",
  21923. "uniform float opacity;",
  21924. "varying vec2 vUV;",
  21925. "void main() {",
  21926. "vec4 texture = texture2D( map, vUV );",
  21927. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  21928. "}"
  21929. ].join( "\n" )
  21930. }
  21931. };
粤ICP备19079148号