ThreeExtras.js 424 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027
  1. /**
  2. * @author alteredq / http://alteredqualia.com/
  3. */
  4. THREE.ColorUtils = {
  5. adjustHSV : function ( color, h, s, v ) {
  6. var hsv = THREE.ColorUtils.__hsv;
  7. THREE.ColorUtils.rgbToHsv( color, hsv );
  8. hsv.h = THREE.Math.clamp( hsv.h + h, 0, 1 );
  9. hsv.s = THREE.Math.clamp( hsv.s + s, 0, 1 );
  10. hsv.v = THREE.Math.clamp( hsv.v + v, 0, 1 );
  11. color.setHSV( hsv.h, hsv.s, hsv.v );
  12. },
  13. // based on MochiKit implementation by Bob Ippolito
  14. rgbToHsv : function ( color, hsv ) {
  15. var r = color.r;
  16. var g = color.g;
  17. var b = color.b;
  18. var max = Math.max( Math.max( r, g ), b );
  19. var min = Math.min( Math.min( r, g ), b );
  20. var hue;
  21. var saturation;
  22. var value = max;
  23. if ( min === max ) {
  24. hue = 0;
  25. saturation = 0;
  26. } else {
  27. var delta = ( max - min );
  28. saturation = delta / max;
  29. if ( r === max ) {
  30. hue = ( g - b ) / delta;
  31. } else if ( g === max ) {
  32. hue = 2 + ( ( b - r ) / delta );
  33. } else {
  34. hue = 4 + ( ( r - g ) / delta );
  35. }
  36. hue /= 6;
  37. if ( hue < 0 ) {
  38. hue += 1;
  39. }
  40. if ( hue > 1 ) {
  41. hue -= 1;
  42. }
  43. }
  44. if ( hsv === undefined ) {
  45. hsv = { h: 0, s: 0, v: 0 };
  46. }
  47. hsv.h = hue;
  48. hsv.s = saturation;
  49. hsv.v = value;
  50. return hsv;
  51. }
  52. };
  53. THREE.ColorUtils.__hsv = { h: 0, s: 0, v: 0 };/**
  54. * @author mrdoob / http://mrdoob.com/
  55. * @author alteredq / http://alteredqualia.com/
  56. */
  57. THREE.GeometryUtils = {
  58. // Merge two geometries or geometry and geometry from object (using object's transform)
  59. merge: function ( geometry1, object2 /* mesh | geometry */ ) {
  60. var matrix, matrixRotation,
  61. vertexOffset = geometry1.vertices.length,
  62. uvPosition = geometry1.faceVertexUvs[ 0 ].length,
  63. geometry2 = object2 instanceof THREE.Mesh ? object2.geometry : object2,
  64. vertices1 = geometry1.vertices,
  65. vertices2 = geometry2.vertices,
  66. faces1 = geometry1.faces,
  67. faces2 = geometry2.faces,
  68. uvs1 = geometry1.faceVertexUvs[ 0 ],
  69. uvs2 = geometry2.faceVertexUvs[ 0 ];
  70. var geo1MaterialsMap = {};
  71. for ( var i = 0; i < geometry1.materials.length; i ++ ) {
  72. var id = geometry1.materials[ i ].id;
  73. geo1MaterialsMap[ id ] = i;
  74. }
  75. if ( object2 instanceof THREE.Mesh ) {
  76. object2.matrixAutoUpdate && object2.updateMatrix();
  77. matrix = object2.matrix;
  78. matrixRotation = new THREE.Matrix4();
  79. matrixRotation.extractRotation( matrix, object2.scale );
  80. }
  81. // vertices
  82. for ( var i = 0, il = vertices2.length; i < il; i ++ ) {
  83. var vertex = vertices2[ i ];
  84. var vertexCopy = vertex.clone();
  85. if ( matrix ) matrix.multiplyVector3( vertexCopy );
  86. vertices1.push( vertexCopy );
  87. }
  88. // faces
  89. for ( i = 0, il = faces2.length; i < il; i ++ ) {
  90. var face = faces2[ i ], faceCopy, normal, color,
  91. faceVertexNormals = face.vertexNormals,
  92. faceVertexColors = face.vertexColors;
  93. if ( face instanceof THREE.Face3 ) {
  94. faceCopy = new THREE.Face3( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset );
  95. } else if ( face instanceof THREE.Face4 ) {
  96. faceCopy = new THREE.Face4( face.a + vertexOffset, face.b + vertexOffset, face.c + vertexOffset, face.d + vertexOffset );
  97. }
  98. faceCopy.normal.copy( face.normal );
  99. if ( matrixRotation ) matrixRotation.multiplyVector3( faceCopy.normal );
  100. for ( var j = 0, jl = faceVertexNormals.length; j < jl; j ++ ) {
  101. normal = faceVertexNormals[ j ].clone();
  102. if ( matrixRotation ) matrixRotation.multiplyVector3( normal );
  103. faceCopy.vertexNormals.push( normal );
  104. }
  105. faceCopy.color.copy( face.color );
  106. for ( var j = 0, jl = faceVertexColors.length; j < jl; j ++ ) {
  107. color = faceVertexColors[ j ];
  108. faceCopy.vertexColors.push( color.clone() );
  109. }
  110. if ( face.materialIndex !== undefined ) {
  111. var material2 = geometry2.materials[ face.materialIndex ];
  112. var materialId2 = material2.id;
  113. var materialIndex = geo1MaterialsMap[ materialId2 ];
  114. if ( materialIndex === undefined ) {
  115. materialIndex = geometry1.materials.length;
  116. geo1MaterialsMap[ materialId2 ] = materialIndex;
  117. geometry1.materials.push( material2 );
  118. }
  119. faceCopy.materialIndex = materialIndex;
  120. }
  121. faceCopy.centroid.copy( face.centroid );
  122. if ( matrix ) matrix.multiplyVector3( faceCopy.centroid );
  123. faces1.push( faceCopy );
  124. }
  125. // uvs
  126. for ( i = 0, il = uvs2.length; i < il; i ++ ) {
  127. var uv = uvs2[ i ], uvCopy = [];
  128. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  129. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  130. }
  131. uvs1.push( uvCopy );
  132. }
  133. },
  134. clone: function ( geometry ) {
  135. var cloneGeo = new THREE.Geometry();
  136. var i, il;
  137. var vertices = geometry.vertices,
  138. faces = geometry.faces,
  139. uvs = geometry.faceVertexUvs[ 0 ];
  140. // materials
  141. if ( geometry.materials ) {
  142. cloneGeo.materials = geometry.materials.slice();
  143. }
  144. // vertices
  145. for ( i = 0, il = vertices.length; i < il; i ++ ) {
  146. var vertex = vertices[ i ];
  147. cloneGeo.vertices.push( vertex.clone() );
  148. }
  149. // faces
  150. for ( i = 0, il = faces.length; i < il; i ++ ) {
  151. var face = faces[ i ];
  152. cloneGeo.faces.push( face.clone() );
  153. }
  154. // uvs
  155. for ( i = 0, il = uvs.length; i < il; i ++ ) {
  156. var uv = uvs[ i ], uvCopy = [];
  157. for ( var j = 0, jl = uv.length; j < jl; j ++ ) {
  158. uvCopy.push( new THREE.UV( uv[ j ].u, uv[ j ].v ) );
  159. }
  160. cloneGeo.faceVertexUvs[ 0 ].push( uvCopy );
  161. }
  162. return cloneGeo;
  163. },
  164. // Get random point in triangle (via barycentric coordinates)
  165. // (uniform distribution)
  166. // http://www.cgafaq.info/wiki/Random_Point_In_Triangle
  167. randomPointInTriangle: function ( vectorA, vectorB, vectorC ) {
  168. var a, b, c,
  169. point = new THREE.Vector3(),
  170. tmp = THREE.GeometryUtils.__v1;
  171. a = THREE.GeometryUtils.random();
  172. b = THREE.GeometryUtils.random();
  173. if ( ( a + b ) > 1 ) {
  174. a = 1 - a;
  175. b = 1 - b;
  176. }
  177. c = 1 - a - b;
  178. point.copy( vectorA );
  179. point.multiplyScalar( a );
  180. tmp.copy( vectorB );
  181. tmp.multiplyScalar( b );
  182. point.addSelf( tmp );
  183. tmp.copy( vectorC );
  184. tmp.multiplyScalar( c );
  185. point.addSelf( tmp );
  186. return point;
  187. },
  188. // Get random point in face (triangle / quad)
  189. // (uniform distribution)
  190. randomPointInFace: function ( face, geometry, useCachedAreas ) {
  191. var vA, vB, vC, vD;
  192. if ( face instanceof THREE.Face3 ) {
  193. vA = geometry.vertices[ face.a ];
  194. vB = geometry.vertices[ face.b ];
  195. vC = geometry.vertices[ face.c ];
  196. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vC );
  197. } else if ( face instanceof THREE.Face4 ) {
  198. vA = geometry.vertices[ face.a ];
  199. vB = geometry.vertices[ face.b ];
  200. vC = geometry.vertices[ face.c ];
  201. vD = geometry.vertices[ face.d ];
  202. var area1, area2;
  203. if ( useCachedAreas ) {
  204. if ( face._area1 && face._area2 ) {
  205. area1 = face._area1;
  206. area2 = face._area2;
  207. } else {
  208. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  209. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  210. face._area1 = area1;
  211. face._area2 = area2;
  212. }
  213. } else {
  214. area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD ),
  215. area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  216. }
  217. var r = THREE.GeometryUtils.random() * ( area1 + area2 );
  218. if ( r < area1 ) {
  219. return THREE.GeometryUtils.randomPointInTriangle( vA, vB, vD );
  220. } else {
  221. return THREE.GeometryUtils.randomPointInTriangle( vB, vC, vD );
  222. }
  223. }
  224. },
  225. // Get uniformly distributed random points in mesh
  226. // - create array with cumulative sums of face areas
  227. // - pick random number from 0 to total area
  228. // - find corresponding place in area array by binary search
  229. // - get random point in face
  230. randomPointsInGeometry: function ( geometry, n ) {
  231. var face, i,
  232. faces = geometry.faces,
  233. vertices = geometry.vertices,
  234. il = faces.length,
  235. totalArea = 0,
  236. cumulativeAreas = [],
  237. vA, vB, vC, vD;
  238. // precompute face areas
  239. for ( i = 0; i < il; i ++ ) {
  240. face = faces[ i ];
  241. if ( face instanceof THREE.Face3 ) {
  242. vA = vertices[ face.a ];
  243. vB = vertices[ face.b ];
  244. vC = vertices[ face.c ];
  245. face._area = THREE.GeometryUtils.triangleArea( vA, vB, vC );
  246. } else if ( face instanceof THREE.Face4 ) {
  247. vA = vertices[ face.a ];
  248. vB = vertices[ face.b ];
  249. vC = vertices[ face.c ];
  250. vD = vertices[ face.d ];
  251. face._area1 = THREE.GeometryUtils.triangleArea( vA, vB, vD );
  252. face._area2 = THREE.GeometryUtils.triangleArea( vB, vC, vD );
  253. face._area = face._area1 + face._area2;
  254. }
  255. totalArea += face._area;
  256. cumulativeAreas[ i ] = totalArea;
  257. }
  258. // binary search cumulative areas array
  259. function binarySearchIndices( value ) {
  260. function binarySearch( start, end ) {
  261. // return closest larger index
  262. // if exact number is not found
  263. if ( end < start )
  264. return start;
  265. var mid = start + Math.floor( ( end - start ) / 2 );
  266. if ( cumulativeAreas[ mid ] > value ) {
  267. return binarySearch( start, mid - 1 );
  268. } else if ( cumulativeAreas[ mid ] < value ) {
  269. return binarySearch( mid + 1, end );
  270. } else {
  271. return mid;
  272. }
  273. }
  274. var result = binarySearch( 0, cumulativeAreas.length - 1 )
  275. return result;
  276. }
  277. // pick random face weighted by face area
  278. var r, index,
  279. result = [];
  280. var stats = {};
  281. for ( i = 0; i < n; i ++ ) {
  282. r = THREE.GeometryUtils.random() * totalArea;
  283. index = binarySearchIndices( r );
  284. result[ i ] = THREE.GeometryUtils.randomPointInFace( faces[ index ], geometry, true );
  285. if ( ! stats[ index ] ) {
  286. stats[ index ] = 1;
  287. } else {
  288. stats[ index ] += 1;
  289. }
  290. }
  291. return result;
  292. },
  293. // Get triangle area (by Heron's formula)
  294. // http://en.wikipedia.org/wiki/Heron%27s_formula
  295. triangleArea: function ( vectorA, vectorB, vectorC ) {
  296. var s, a, b, c,
  297. tmp = THREE.GeometryUtils.__v1;
  298. tmp.sub( vectorA, vectorB );
  299. a = tmp.length();
  300. tmp.sub( vectorA, vectorC );
  301. b = tmp.length();
  302. tmp.sub( vectorB, vectorC );
  303. c = tmp.length();
  304. s = 0.5 * ( a + b + c );
  305. return Math.sqrt( s * ( s - a ) * ( s - b ) * ( s - c ) );
  306. },
  307. // Center geometry so that 0,0,0 is in center of bounding box
  308. center: function ( geometry ) {
  309. geometry.computeBoundingBox();
  310. var bb = geometry.boundingBox;
  311. var offset = new THREE.Vector3();
  312. offset.add( bb.min, bb.max );
  313. offset.multiplyScalar( -0.5 );
  314. geometry.applyMatrix( new THREE.Matrix4().makeTranslation( offset.x, offset.y, offset.z ) );
  315. geometry.computeBoundingBox();
  316. return offset;
  317. },
  318. // Normalize UVs to be from <0,1>
  319. // (for now just the first set of UVs)
  320. normalizeUVs: function ( geometry ) {
  321. var uvSet = geometry.faceVertexUvs[ 0 ];
  322. for ( var i = 0, il = uvSet.length; i < il; i ++ ) {
  323. var uvs = uvSet[ i ];
  324. for ( var j = 0, jl = uvs.length; j < jl; j ++ ) {
  325. // texture repeat
  326. if( uvs[ j ].u !== 1.0 ) uvs[ j ].u = uvs[ j ].u - Math.floor( uvs[ j ].u );
  327. if( uvs[ j ].v !== 1.0 ) uvs[ j ].v = uvs[ j ].v - Math.floor( uvs[ j ].v );
  328. }
  329. }
  330. },
  331. triangulateQuads: function ( geometry ) {
  332. var i, il, j, jl;
  333. var faces = [];
  334. var faceUvs = [];
  335. var faceVertexUvs = [];
  336. for ( i = 0, il = geometry.faceUvs.length; i < il; i ++ ) {
  337. faceUvs[ i ] = [];
  338. }
  339. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  340. faceVertexUvs[ i ] = [];
  341. }
  342. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  343. var face = geometry.faces[ i ];
  344. if ( face instanceof THREE.Face4 ) {
  345. var a = face.a;
  346. var b = face.b;
  347. var c = face.c;
  348. var d = face.d;
  349. var triA = new THREE.Face3();
  350. var triB = new THREE.Face3();
  351. triA.color.copy( face.color );
  352. triB.color.copy( face.color );
  353. triA.materialIndex = face.materialIndex;
  354. triB.materialIndex = face.materialIndex;
  355. triA.a = a;
  356. triA.b = b;
  357. triA.c = d;
  358. triB.a = b;
  359. triB.b = c;
  360. triB.c = d;
  361. if ( face.vertexColors.length === 4 ) {
  362. triA.vertexColors[ 0 ] = face.vertexColors[ 0 ].clone();
  363. triA.vertexColors[ 1 ] = face.vertexColors[ 1 ].clone();
  364. triA.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  365. triB.vertexColors[ 0 ] = face.vertexColors[ 1 ].clone();
  366. triB.vertexColors[ 1 ] = face.vertexColors[ 2 ].clone();
  367. triB.vertexColors[ 2 ] = face.vertexColors[ 3 ].clone();
  368. }
  369. faces.push( triA, triB );
  370. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  371. if ( geometry.faceVertexUvs[ j ].length ) {
  372. var uvs = geometry.faceVertexUvs[ j ][ i ];
  373. var uvA = uvs[ 0 ];
  374. var uvB = uvs[ 1 ];
  375. var uvC = uvs[ 2 ];
  376. var uvD = uvs[ 3 ];
  377. var uvsTriA = [ uvA.clone(), uvB.clone(), uvD.clone() ];
  378. var uvsTriB = [ uvB.clone(), uvC.clone(), uvD.clone() ];
  379. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  380. }
  381. }
  382. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  383. if ( geometry.faceUvs[ j ].length ) {
  384. var faceUv = geometry.faceUvs[ j ][ i ];
  385. faceUvs[ j ].push( faceUv, faceUv );
  386. }
  387. }
  388. } else {
  389. faces.push( face );
  390. for ( j = 0, jl = geometry.faceUvs.length; j < jl; j ++ ) {
  391. faceUvs[ j ].push( geometry.faceUvs[ j ] );
  392. }
  393. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  394. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ] );
  395. }
  396. }
  397. }
  398. geometry.faces = faces;
  399. geometry.faceUvs = faceUvs;
  400. geometry.faceVertexUvs = faceVertexUvs;
  401. geometry.computeCentroids();
  402. geometry.computeFaceNormals();
  403. geometry.computeVertexNormals();
  404. if ( geometry.hasTangents ) geometry.computeTangents();
  405. },
  406. // Make all faces use unique vertices
  407. // so that each face can be separated from others
  408. explode: function( geometry ) {
  409. var vertices = [];
  410. for ( var i = 0, il = geometry.faces.length; i < il; i ++ ) {
  411. var n = vertices.length;
  412. var face = geometry.faces[ i ];
  413. if ( face instanceof THREE.Face4 ) {
  414. var a = face.a;
  415. var b = face.b;
  416. var c = face.c;
  417. var d = face.d;
  418. var va = geometry.vertices[ a ];
  419. var vb = geometry.vertices[ b ];
  420. var vc = geometry.vertices[ c ];
  421. var vd = geometry.vertices[ d ];
  422. vertices.push( va.clone() );
  423. vertices.push( vb.clone() );
  424. vertices.push( vc.clone() );
  425. vertices.push( vd.clone() );
  426. face.a = n;
  427. face.b = n + 1;
  428. face.c = n + 2;
  429. face.d = n + 3;
  430. } else {
  431. var a = face.a;
  432. var b = face.b;
  433. var c = face.c;
  434. var va = geometry.vertices[ a ];
  435. var vb = geometry.vertices[ b ];
  436. var vc = geometry.vertices[ c ];
  437. vertices.push( va.clone() );
  438. vertices.push( vb.clone() );
  439. vertices.push( vc.clone() );
  440. face.a = n;
  441. face.b = n + 1;
  442. face.c = n + 2;
  443. }
  444. }
  445. geometry.vertices = vertices;
  446. delete geometry.__tmpVertices;
  447. },
  448. // Break faces with edges longer than maxEdgeLength
  449. // - not recursive
  450. tessellate: function ( geometry, maxEdgeLength ) {
  451. var i, il, face,
  452. a, b, c, d,
  453. va, vb, vc, vd,
  454. dab, dbc, dac, dcd, dad,
  455. m, m1, m2,
  456. vm, vm1, vm2,
  457. vnm, vnm1, vnm2,
  458. vcm, vcm1, vcm2,
  459. triA, triB,
  460. quadA, quadB,
  461. edge;
  462. var faces = [];
  463. var faceVertexUvs = [];
  464. for ( i = 0, il = geometry.faceVertexUvs.length; i < il; i ++ ) {
  465. faceVertexUvs[ i ] = [];
  466. }
  467. for ( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  468. face = geometry.faces[ i ];
  469. if ( face instanceof THREE.Face3 ) {
  470. a = face.a;
  471. b = face.b;
  472. c = face.c;
  473. va = geometry.vertices[ a ];
  474. vb = geometry.vertices[ b ];
  475. vc = geometry.vertices[ c ];
  476. dab = va.distanceTo( vb );
  477. dbc = vb.distanceTo( vc );
  478. dac = va.distanceTo( vc );
  479. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dac > maxEdgeLength ) {
  480. m = geometry.vertices.length;
  481. triA = face.clone();
  482. triB = face.clone();
  483. if ( dab >= dbc && dab >= dac ) {
  484. vm = va.clone();
  485. vm.lerpSelf( vb, 0.5 );
  486. triA.a = a;
  487. triA.b = m;
  488. triA.c = c;
  489. triB.a = m;
  490. triB.b = b;
  491. triB.c = c;
  492. if ( face.vertexNormals.length === 3 ) {
  493. vnm = face.vertexNormals[ 0 ].clone();
  494. vnm.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  495. triA.vertexNormals[ 1 ].copy( vnm );
  496. triB.vertexNormals[ 0 ].copy( vnm );
  497. }
  498. if ( face.vertexColors.length === 3 ) {
  499. vcm = face.vertexColors[ 0 ].clone();
  500. vcm.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  501. triA.vertexColors[ 1 ].copy( vcm );
  502. triB.vertexColors[ 0 ].copy( vcm );
  503. }
  504. edge = 0;
  505. } else if ( dbc >= dab && dbc >= dac ) {
  506. vm = vb.clone();
  507. vm.lerpSelf( vc, 0.5 );
  508. triA.a = a;
  509. triA.b = b;
  510. triA.c = m;
  511. triB.a = m;
  512. triB.b = c;
  513. triB.c = a;
  514. if ( face.vertexNormals.length === 3 ) {
  515. vnm = face.vertexNormals[ 1 ].clone();
  516. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  517. triA.vertexNormals[ 2 ].copy( vnm );
  518. triB.vertexNormals[ 0 ].copy( vnm );
  519. triB.vertexNormals[ 1 ].copy( face.vertexNormals[ 2 ] );
  520. triB.vertexNormals[ 2 ].copy( face.vertexNormals[ 0 ] );
  521. }
  522. if ( face.vertexColors.length === 3 ) {
  523. vcm = face.vertexColors[ 1 ].clone();
  524. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  525. triA.vertexColors[ 2 ].copy( vcm );
  526. triB.vertexColors[ 0 ].copy( vcm );
  527. triB.vertexColors[ 1 ].copy( face.vertexColors[ 2 ] );
  528. triB.vertexColors[ 2 ].copy( face.vertexColors[ 0 ] );
  529. }
  530. edge = 1;
  531. } else {
  532. vm = va.clone();
  533. vm.lerpSelf( vc, 0.5 );
  534. triA.a = a;
  535. triA.b = b;
  536. triA.c = m;
  537. triB.a = m;
  538. triB.b = b;
  539. triB.c = c;
  540. if ( face.vertexNormals.length === 3 ) {
  541. vnm = face.vertexNormals[ 0 ].clone();
  542. vnm.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  543. triA.vertexNormals[ 2 ].copy( vnm );
  544. triB.vertexNormals[ 0 ].copy( vnm );
  545. }
  546. if ( face.vertexColors.length === 3 ) {
  547. vcm = face.vertexColors[ 0 ].clone();
  548. vcm.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  549. triA.vertexColors[ 2 ].copy( vcm );
  550. triB.vertexColors[ 0 ].copy( vcm );
  551. }
  552. edge = 2;
  553. }
  554. faces.push( triA, triB );
  555. geometry.vertices.push( vm );
  556. var j, jl, uvs, uvA, uvB, uvC, uvM, uvsTriA, uvsTriB;
  557. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  558. if ( geometry.faceVertexUvs[ j ].length ) {
  559. uvs = geometry.faceVertexUvs[ j ][ i ];
  560. uvA = uvs[ 0 ];
  561. uvB = uvs[ 1 ];
  562. uvC = uvs[ 2 ];
  563. // AB
  564. if ( edge === 0 ) {
  565. uvM = uvA.clone();
  566. uvM.lerpSelf( uvB, 0.5 );
  567. uvsTriA = [ uvA.clone(), uvM.clone(), uvC.clone() ];
  568. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  569. // BC
  570. } else if ( edge === 1 ) {
  571. uvM = uvB.clone();
  572. uvM.lerpSelf( uvC, 0.5 );
  573. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  574. uvsTriB = [ uvM.clone(), uvC.clone(), uvA.clone() ];
  575. // AC
  576. } else {
  577. uvM = uvA.clone();
  578. uvM.lerpSelf( uvC, 0.5 );
  579. uvsTriA = [ uvA.clone(), uvB.clone(), uvM.clone() ];
  580. uvsTriB = [ uvM.clone(), uvB.clone(), uvC.clone() ];
  581. }
  582. faceVertexUvs[ j ].push( uvsTriA, uvsTriB );
  583. }
  584. }
  585. } else {
  586. faces.push( face );
  587. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  588. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  589. }
  590. }
  591. } else {
  592. a = face.a;
  593. b = face.b;
  594. c = face.c;
  595. d = face.d;
  596. va = geometry.vertices[ a ];
  597. vb = geometry.vertices[ b ];
  598. vc = geometry.vertices[ c ];
  599. vd = geometry.vertices[ d ];
  600. dab = va.distanceTo( vb );
  601. dbc = vb.distanceTo( vc );
  602. dcd = vc.distanceTo( vd );
  603. dad = va.distanceTo( vd );
  604. if ( dab > maxEdgeLength || dbc > maxEdgeLength || dcd > maxEdgeLength || dad > maxEdgeLength ) {
  605. m1 = geometry.vertices.length;
  606. m2 = geometry.vertices.length + 1;
  607. quadA = face.clone();
  608. quadB = face.clone();
  609. if ( ( dab >= dbc && dab >= dcd && dab >= dad ) || ( dcd >= dbc && dcd >= dab && dcd >= dad ) ) {
  610. vm1 = va.clone();
  611. vm1.lerpSelf( vb, 0.5 );
  612. vm2 = vc.clone();
  613. vm2.lerpSelf( vd, 0.5 );
  614. quadA.a = a;
  615. quadA.b = m1;
  616. quadA.c = m2;
  617. quadA.d = d;
  618. quadB.a = m1;
  619. quadB.b = b;
  620. quadB.c = c;
  621. quadB.d = m2;
  622. if ( face.vertexNormals.length === 4 ) {
  623. vnm1 = face.vertexNormals[ 0 ].clone();
  624. vnm1.lerpSelf( face.vertexNormals[ 1 ], 0.5 );
  625. vnm2 = face.vertexNormals[ 2 ].clone();
  626. vnm2.lerpSelf( face.vertexNormals[ 3 ], 0.5 );
  627. quadA.vertexNormals[ 1 ].copy( vnm1 );
  628. quadA.vertexNormals[ 2 ].copy( vnm2 );
  629. quadB.vertexNormals[ 0 ].copy( vnm1 );
  630. quadB.vertexNormals[ 3 ].copy( vnm2 );
  631. }
  632. if ( face.vertexColors.length === 4 ) {
  633. vcm1 = face.vertexColors[ 0 ].clone();
  634. vcm1.lerpSelf( face.vertexColors[ 1 ], 0.5 );
  635. vcm2 = face.vertexColors[ 2 ].clone();
  636. vcm2.lerpSelf( face.vertexColors[ 3 ], 0.5 );
  637. quadA.vertexColors[ 1 ].copy( vcm1 );
  638. quadA.vertexColors[ 2 ].copy( vcm2 );
  639. quadB.vertexColors[ 0 ].copy( vcm1 );
  640. quadB.vertexColors[ 3 ].copy( vcm2 );
  641. }
  642. edge = 0;
  643. } else {
  644. vm1 = vb.clone();
  645. vm1.lerpSelf( vc, 0.5 );
  646. vm2 = vd.clone();
  647. vm2.lerpSelf( va, 0.5 );
  648. quadA.a = a;
  649. quadA.b = b;
  650. quadA.c = m1;
  651. quadA.d = m2;
  652. quadB.a = m2;
  653. quadB.b = m1;
  654. quadB.c = c;
  655. quadB.d = d;
  656. if ( face.vertexNormals.length === 4 ) {
  657. vnm1 = face.vertexNormals[ 1 ].clone();
  658. vnm1.lerpSelf( face.vertexNormals[ 2 ], 0.5 );
  659. vnm2 = face.vertexNormals[ 3 ].clone();
  660. vnm2.lerpSelf( face.vertexNormals[ 0 ], 0.5 );
  661. quadA.vertexNormals[ 2 ].copy( vnm1 );
  662. quadA.vertexNormals[ 3 ].copy( vnm2 );
  663. quadB.vertexNormals[ 0 ].copy( vnm2 );
  664. quadB.vertexNormals[ 1 ].copy( vnm1 );
  665. }
  666. if ( face.vertexColors.length === 4 ) {
  667. vcm1 = face.vertexColors[ 1 ].clone();
  668. vcm1.lerpSelf( face.vertexColors[ 2 ], 0.5 );
  669. vcm2 = face.vertexColors[ 3 ].clone();
  670. vcm2.lerpSelf( face.vertexColors[ 0 ], 0.5 );
  671. quadA.vertexColors[ 2 ].copy( vcm1 );
  672. quadA.vertexColors[ 3 ].copy( vcm2 );
  673. quadB.vertexColors[ 0 ].copy( vcm2 );
  674. quadB.vertexColors[ 1 ].copy( vcm1 );
  675. }
  676. edge = 1;
  677. }
  678. faces.push( quadA, quadB );
  679. geometry.vertices.push( vm1, vm2 );
  680. var j, jl, uvs, uvA, uvB, uvC, uvD, uvM1, uvM2, uvsQuadA, uvsQuadB;
  681. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  682. if ( geometry.faceVertexUvs[ j ].length ) {
  683. uvs = geometry.faceVertexUvs[ j ][ i ];
  684. uvA = uvs[ 0 ];
  685. uvB = uvs[ 1 ];
  686. uvC = uvs[ 2 ];
  687. uvD = uvs[ 3 ];
  688. // AB + CD
  689. if ( edge === 0 ) {
  690. uvM1 = uvA.clone();
  691. uvM1.lerpSelf( uvB, 0.5 );
  692. uvM2 = uvC.clone();
  693. uvM2.lerpSelf( uvD, 0.5 );
  694. uvsQuadA = [ uvA.clone(), uvM1.clone(), uvM2.clone(), uvD.clone() ];
  695. uvsQuadB = [ uvM1.clone(), uvB.clone(), uvC.clone(), uvM2.clone() ];
  696. // BC + AD
  697. } else {
  698. uvM1 = uvB.clone();
  699. uvM1.lerpSelf( uvC, 0.5 );
  700. uvM2 = uvD.clone();
  701. uvM2.lerpSelf( uvA, 0.5 );
  702. uvsQuadA = [ uvA.clone(), uvB.clone(), uvM1.clone(), uvM2.clone() ];
  703. uvsQuadB = [ uvM2.clone(), uvM1.clone(), uvC.clone(), uvD.clone() ];
  704. }
  705. faceVertexUvs[ j ].push( uvsQuadA, uvsQuadB );
  706. }
  707. }
  708. } else {
  709. faces.push( face );
  710. for ( j = 0, jl = geometry.faceVertexUvs.length; j < jl; j ++ ) {
  711. faceVertexUvs[ j ].push( geometry.faceVertexUvs[ j ][ i ] );
  712. }
  713. }
  714. }
  715. }
  716. geometry.faces = faces;
  717. geometry.faceVertexUvs = faceVertexUvs;
  718. }
  719. };
  720. THREE.GeometryUtils.random = THREE.Math.random16;
  721. THREE.GeometryUtils.__v1 = new THREE.Vector3();
  722. /**
  723. * @author alteredq / http://alteredqualia.com/
  724. * @author mrdoob / http://mrdoob.com/
  725. */
  726. THREE.ImageUtils = {
  727. crossOrigin: 'anonymous',
  728. loadTexture: function ( path, mapping, callback ) {
  729. var image = new Image(), texture = new THREE.Texture( image, mapping );
  730. image.onload = function () { texture.needsUpdate = true; if ( callback ) callback( this ); };
  731. image.crossOrigin = this.crossOrigin;
  732. image.src = path;
  733. return texture;
  734. },
  735. loadTextureCube: function ( array, mapping, callback ) {
  736. var i, l, images = [], texture = new THREE.Texture( images, mapping );
  737. images.loadCount = 0;
  738. for ( i = 0, l = array.length; i < l; ++ i ) {
  739. images[ i ] = new Image();
  740. images[ i ].onload = function () {
  741. images.loadCount += 1;
  742. if ( images.loadCount === 6 ) texture.needsUpdate = true;
  743. if ( callback ) callback( this );
  744. };
  745. images[ i ].crossOrigin = this.crossOrigin;
  746. images[ i ].src = array[ i ];
  747. }
  748. return texture;
  749. },
  750. getNormalMap: function ( image, depth ) {
  751. // Adapted from http://www.paulbrunt.co.uk/lab/heightnormal/
  752. var cross = function ( a, b ) {
  753. 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 ] ];
  754. }
  755. var subtract = function ( a, b ) {
  756. return [ a[ 0 ] - b[ 0 ], a[ 1 ] - b[ 1 ], a[ 2 ] - b[ 2 ] ];
  757. }
  758. var normalize = function ( a ) {
  759. var l = Math.sqrt( a[ 0 ] * a[ 0 ] + a[ 1 ] * a[ 1 ] + a[ 2 ] * a[ 2 ] );
  760. return [ a[ 0 ] / l, a[ 1 ] / l, a[ 2 ] / l ];
  761. }
  762. depth = depth | 1;
  763. var width = image.width;
  764. var height = image.height;
  765. var canvas = document.createElement( 'canvas' );
  766. canvas.width = width;
  767. canvas.height = height;
  768. var context = canvas.getContext( '2d' );
  769. context.drawImage( image, 0, 0 );
  770. var data = context.getImageData( 0, 0, width, height ).data;
  771. var imageData = context.createImageData( width, height );
  772. var output = imageData.data;
  773. for ( var x = 0; x < width; x ++ ) {
  774. for ( var y = 1; y < height; y ++ ) {
  775. var ly = y - 1 < 0 ? height - 1 : y - 1;
  776. var uy = ( y + 1 ) % height;
  777. var lx = x - 1 < 0 ? width - 1 : x - 1;
  778. var ux = ( x + 1 ) % width;
  779. var points = [];
  780. var origin = [ 0, 0, data[ ( y * width + x ) * 4 ] / 255 * depth ];
  781. points.push( [ - 1, 0, data[ ( y * width + lx ) * 4 ] / 255 * depth ] );
  782. points.push( [ - 1, - 1, data[ ( ly * width + lx ) * 4 ] / 255 * depth ] );
  783. points.push( [ 0, - 1, data[ ( ly * width + x ) * 4 ] / 255 * depth ] );
  784. points.push( [ 1, - 1, data[ ( ly * width + ux ) * 4 ] / 255 * depth ] );
  785. points.push( [ 1, 0, data[ ( y * width + ux ) * 4 ] / 255 * depth ] );
  786. points.push( [ 1, 1, data[ ( uy * width + ux ) * 4 ] / 255 * depth ] );
  787. points.push( [ 0, 1, data[ ( uy * width + x ) * 4 ] / 255 * depth ] );
  788. points.push( [ - 1, 1, data[ ( uy * width + lx ) * 4 ] / 255 * depth ] );
  789. var normals = [];
  790. var num_points = points.length;
  791. for ( var i = 0; i < num_points; i ++ ) {
  792. var v1 = points[ i ];
  793. var v2 = points[ ( i + 1 ) % num_points ];
  794. v1 = subtract( v1, origin );
  795. v2 = subtract( v2, origin );
  796. normals.push( normalize( cross( v1, v2 ) ) );
  797. }
  798. var normal = [ 0, 0, 0 ];
  799. for ( var i = 0; i < normals.length; i ++ ) {
  800. normal[ 0 ] += normals[ i ][ 0 ];
  801. normal[ 1 ] += normals[ i ][ 1 ];
  802. normal[ 2 ] += normals[ i ][ 2 ];
  803. }
  804. normal[ 0 ] /= normals.length;
  805. normal[ 1 ] /= normals.length;
  806. normal[ 2 ] /= normals.length;
  807. var idx = ( y * width + x ) * 4;
  808. output[ idx ] = ( ( normal[ 0 ] + 1.0 ) / 2.0 * 255 ) | 0;
  809. output[ idx + 1 ] = ( ( normal[ 1 ] + 1.0 / 2.0 ) * 255 ) | 0;
  810. output[ idx + 2 ] = ( normal[ 2 ] * 255 ) | 0;
  811. output[ idx + 3 ] = 255;
  812. }
  813. }
  814. context.putImageData( imageData, 0, 0 );
  815. return canvas;
  816. },
  817. generateDataTexture: function ( width, height, color ) {
  818. var size = width * height;
  819. var data = new Uint8Array( 3 * size );
  820. var r = Math.floor( color.r * 255 );
  821. var g = Math.floor( color.g * 255 );
  822. var b = Math.floor( color.b * 255 );
  823. for ( var i = 0; i < size; i ++ ) {
  824. data[ i * 3 ] = r;
  825. data[ i * 3 + 1 ] = g;
  826. data[ i * 3 + 2 ] = b;
  827. }
  828. var texture = new THREE.DataTexture( data, width, height, THREE.RGBFormat );
  829. texture.needsUpdate = true;
  830. return texture;
  831. }
  832. };
  833. /**
  834. * @author alteredq / http://alteredqualia.com/
  835. */
  836. THREE.SceneUtils = {
  837. showHierarchy : function ( root, visible ) {
  838. THREE.SceneUtils.traverseHierarchy( root, function( node ) { node.visible = visible; } );
  839. },
  840. traverseHierarchy : function ( root, callback ) {
  841. var n, i, l = root.children.length;
  842. for ( i = 0; i < l; i ++ ) {
  843. n = root.children[ i ];
  844. callback( n );
  845. THREE.SceneUtils.traverseHierarchy( n, callback );
  846. }
  847. },
  848. createMultiMaterialObject : function ( geometry, materials ) {
  849. var i, il = materials.length,
  850. group = new THREE.Object3D();
  851. for ( i = 0; i < il; i ++ ) {
  852. var object = new THREE.Mesh( geometry, materials[ i ] );
  853. group.add( object );
  854. }
  855. return group;
  856. },
  857. cloneObject: function ( source ) {
  858. var object;
  859. // subclass specific properties
  860. // (must process in order from more specific subclasses to more abstract classes)
  861. if ( source instanceof THREE.MorphAnimMesh ) {
  862. object = new THREE.MorphAnimMesh( source.geometry, source.material );
  863. object.duration = source.duration;
  864. object.mirroredLoop = source.mirroredLoop;
  865. object.time = source.time;
  866. object.lastKeyframe = source.lastKeyframe;
  867. object.currentKeyframe = source.currentKeyframe;
  868. object.direction = source.direction;
  869. object.directionBackwards = source.directionBackwards;
  870. } else if ( source instanceof THREE.SkinnedMesh ) {
  871. object = new THREE.SkinnedMesh( source.geometry, source.material );
  872. } else if ( source instanceof THREE.Mesh ) {
  873. object = new THREE.Mesh( source.geometry, source.material );
  874. } else if ( source instanceof THREE.Line ) {
  875. object = new THREE.Line( source.geometry, source.material, source.type );
  876. } else if ( source instanceof THREE.Ribbon ) {
  877. object = new THREE.Ribbon( source.geometry, source.material );
  878. } else if ( source instanceof THREE.ParticleSystem ) {
  879. object = new THREE.ParticleSystem( source.geometry, source.material );
  880. object.sortParticles = source.sortParticles;
  881. } else if ( source instanceof THREE.Particle ) {
  882. object = new THREE.Particle( source.material );
  883. } else if ( source instanceof THREE.Sprite ) {
  884. object = new THREE.Sprite( {} );
  885. object.color.copy( source.color );
  886. object.map = source.map;
  887. object.blending = source.blending;
  888. object.useScreenCoordinates = source.useScreenCoordinates;
  889. object.mergeWith3D = source.mergeWith3D;
  890. object.affectedByDistance = source.affectedByDistance;
  891. object.scaleByViewport = source.scaleByViewport;
  892. object.alignment = source.alignment;
  893. object.rotation3d.copy( source.rotation3d );
  894. object.rotation = source.rotation;
  895. object.opacity = source.opacity;
  896. object.uvOffset.copy( source.uvOffset );
  897. object.uvScale.copy( source.uvScale);
  898. } else if ( source instanceof THREE.LOD ) {
  899. object = new THREE.LOD();
  900. } else if ( source instanceof THREE.MarchingCubes ) {
  901. object = new THREE.MarchingCubes( source.resolution, source.material );
  902. object.field.set( source.field );
  903. object.isolation = source.isolation;
  904. } else if ( source instanceof THREE.Object3D ) {
  905. object = new THREE.Object3D();
  906. }
  907. // base class properties
  908. object.name = source.name;
  909. object.parent = source.parent;
  910. object.up.copy( source.up );
  911. object.position.copy( source.position );
  912. // because of Sprite madness
  913. if ( object.rotation instanceof THREE.Vector3 )
  914. object.rotation.copy( source.rotation );
  915. object.eulerOrder = source.eulerOrder;
  916. object.scale.copy( source.scale );
  917. object.dynamic = source.dynamic;
  918. object.doubleSided = source.doubleSided;
  919. object.flipSided = source.flipSided;
  920. object.renderDepth = source.renderDepth;
  921. object.rotationAutoUpdate = source.rotationAutoUpdate;
  922. object.matrix.copy( source.matrix );
  923. object.matrixWorld.copy( source.matrixWorld );
  924. object.matrixRotationWorld.copy( source.matrixRotationWorld );
  925. object.matrixAutoUpdate = source.matrixAutoUpdate;
  926. object.matrixWorldNeedsUpdate = source.matrixWorldNeedsUpdate;
  927. object.quaternion.copy( source.quaternion );
  928. object.useQuaternion = source.useQuaternion;
  929. object.boundRadius = source.boundRadius;
  930. object.boundRadiusScale = source.boundRadiusScale;
  931. object.visible = source.visible;
  932. object.castShadow = source.castShadow;
  933. object.receiveShadow = source.receiveShadow;
  934. object.frustumCulled = source.frustumCulled;
  935. // children
  936. for ( var i = 0; i < source.children.length; i ++ ) {
  937. var child = THREE.SceneUtils.cloneObject( source.children[ i ] );
  938. object.children[ i ] = child;
  939. child.parent = object;
  940. }
  941. // LODs need to be patched separately to use cloned children
  942. if ( source instanceof THREE.LOD ) {
  943. for ( var i = 0; i < source.LODs.length; i ++ ) {
  944. var lod = source.LODs[ i ];
  945. object.LODs[ i ] = { visibleAtDistance: lod.visibleAtDistance, object3D: object.children[ i ] };
  946. }
  947. }
  948. return object;
  949. },
  950. detach : function ( child, parent, scene ) {
  951. child.applyMatrix( parent.matrixWorld );
  952. parent.remove( child );
  953. scene.add( child );
  954. },
  955. attach: function ( child, scene, parent ) {
  956. var matrixWorldInverse = new THREE.Matrix4();
  957. matrixWorldInverse.getInverse( parent.matrixWorld );
  958. child.applyMatrix( matrixWorldInverse );
  959. scene.remove( child );
  960. parent.add( child );
  961. }
  962. };
  963. /**
  964. * @author alteredq / http://alteredqualia.com/
  965. * @author mr.doob / http://mrdoob.com/
  966. *
  967. * ShaderUtils currently contains:
  968. *
  969. * fresnel
  970. * normal
  971. * cube
  972. *
  973. */
  974. if ( THREE.WebGLRenderer ) {
  975. THREE.ShaderUtils = {
  976. lib: {
  977. /* -------------------------------------------------------------------------
  978. // Fresnel shader
  979. // - based on Nvidia Cg tutorial
  980. ------------------------------------------------------------------------- */
  981. 'fresnel': {
  982. uniforms: {
  983. "mRefractionRatio": { type: "f", value: 1.02 },
  984. "mFresnelBias": { type: "f", value: 0.1 },
  985. "mFresnelPower": { type: "f", value: 2.0 },
  986. "mFresnelScale": { type: "f", value: 1.0 },
  987. "tCube": { type: "t", value: 1, texture: null }
  988. },
  989. fragmentShader: [
  990. "uniform samplerCube tCube;",
  991. "varying vec3 vReflect;",
  992. "varying vec3 vRefract[3];",
  993. "varying float vReflectionFactor;",
  994. "void main() {",
  995. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  996. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  997. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  998. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  999. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  1000. "refractedColor.a = 1.0;",
  1001. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  1002. "}"
  1003. ].join("\n"),
  1004. vertexShader: [
  1005. "uniform float mRefractionRatio;",
  1006. "uniform float mFresnelBias;",
  1007. "uniform float mFresnelScale;",
  1008. "uniform float mFresnelPower;",
  1009. "varying vec3 vReflect;",
  1010. "varying vec3 vRefract[3];",
  1011. "varying float vReflectionFactor;",
  1012. "void main() {",
  1013. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1014. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  1015. "vec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );",
  1016. "vec3 I = mPosition.xyz - cameraPosition;",
  1017. "vReflect = reflect( I, nWorld );",
  1018. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  1019. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  1020. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  1021. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  1022. "gl_Position = projectionMatrix * mvPosition;",
  1023. "}"
  1024. ].join("\n")
  1025. },
  1026. /* -------------------------------------------------------------------------
  1027. // Normal map shader
  1028. // - Blinn-Phong
  1029. // - normal + diffuse + specular + AO + displacement + reflection + shadow maps
  1030. // - point and directional lights (use with "lights: true" material option)
  1031. ------------------------------------------------------------------------- */
  1032. 'normal' : {
  1033. uniforms: THREE.UniformsUtils.merge( [
  1034. THREE.UniformsLib[ "fog" ],
  1035. THREE.UniformsLib[ "lights" ],
  1036. THREE.UniformsLib[ "shadowmap" ],
  1037. {
  1038. "enableAO" : { type: "i", value: 0 },
  1039. "enableDiffuse" : { type: "i", value: 0 },
  1040. "enableSpecular" : { type: "i", value: 0 },
  1041. "enableReflection": { type: "i", value: 0 },
  1042. "tDiffuse" : { type: "t", value: 0, texture: null },
  1043. "tCube" : { type: "t", value: 1, texture: null },
  1044. "tNormal" : { type: "t", value: 2, texture: null },
  1045. "tSpecular" : { type: "t", value: 3, texture: null },
  1046. "tAO" : { type: "t", value: 4, texture: null },
  1047. "tDisplacement": { type: "t", value: 5, texture: null },
  1048. "uNormalScale": { type: "f", value: 1.0 },
  1049. "uDisplacementBias": { type: "f", value: 0.0 },
  1050. "uDisplacementScale": { type: "f", value: 1.0 },
  1051. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  1052. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  1053. "uAmbientColor": { type: "c", value: new THREE.Color( 0xffffff ) },
  1054. "uShininess": { type: "f", value: 30 },
  1055. "uOpacity": { type: "f", value: 1 },
  1056. "uReflectivity": { type: "f", value: 0.5 },
  1057. "uOffset" : { type: "v2", value: new THREE.Vector2( 0, 0 ) },
  1058. "uRepeat" : { type: "v2", value: new THREE.Vector2( 1, 1 ) },
  1059. "wrapRGB" : { type: "v3", value: new THREE.Vector3( 1, 1, 1 ) }
  1060. }
  1061. ] ),
  1062. fragmentShader: [
  1063. "uniform vec3 uAmbientColor;",
  1064. "uniform vec3 uDiffuseColor;",
  1065. "uniform vec3 uSpecularColor;",
  1066. "uniform float uShininess;",
  1067. "uniform float uOpacity;",
  1068. "uniform bool enableDiffuse;",
  1069. "uniform bool enableSpecular;",
  1070. "uniform bool enableAO;",
  1071. "uniform bool enableReflection;",
  1072. "uniform sampler2D tDiffuse;",
  1073. "uniform sampler2D tNormal;",
  1074. "uniform sampler2D tSpecular;",
  1075. "uniform sampler2D tAO;",
  1076. "uniform samplerCube tCube;",
  1077. "uniform float uNormalScale;",
  1078. "uniform float uReflectivity;",
  1079. "varying vec3 vTangent;",
  1080. "varying vec3 vBinormal;",
  1081. "varying vec3 vNormal;",
  1082. "varying vec2 vUv;",
  1083. "uniform vec3 ambientLightColor;",
  1084. "#if MAX_DIR_LIGHTS > 0",
  1085. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  1086. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  1087. "#endif",
  1088. "#if MAX_POINT_LIGHTS > 0",
  1089. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  1090. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  1091. "#endif",
  1092. "#ifdef WRAP_AROUND",
  1093. "uniform vec3 wrapRGB;",
  1094. "#endif",
  1095. "varying vec3 vViewPosition;",
  1096. THREE.ShaderChunk[ "shadowmap_pars_fragment" ],
  1097. THREE.ShaderChunk[ "fog_pars_fragment" ],
  1098. "void main() {",
  1099. "gl_FragColor = vec4( vec3( 1.0 ), uOpacity );",
  1100. "vec3 specularTex = vec3( 1.0 );",
  1101. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  1102. "normalTex.xy *= uNormalScale;",
  1103. "normalTex = normalize( normalTex );",
  1104. "if( enableDiffuse ) {",
  1105. "#ifdef GAMMA_INPUT",
  1106. "vec4 texelColor = texture2D( tDiffuse, vUv );",
  1107. "texelColor.xyz *= texelColor.xyz;",
  1108. "gl_FragColor = gl_FragColor * texelColor;",
  1109. "#else",
  1110. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  1111. "#endif",
  1112. "}",
  1113. "if( enableAO ) {",
  1114. "#ifdef GAMMA_INPUT",
  1115. "vec4 aoColor = texture2D( tAO, vUv );",
  1116. "aoColor.xyz *= aoColor.xyz;",
  1117. "gl_FragColor.xyz = gl_FragColor.xyz * aoColor.xyz;",
  1118. "#else",
  1119. "gl_FragColor.xyz = gl_FragColor.xyz * texture2D( tAO, vUv ).xyz;",
  1120. "#endif",
  1121. "}",
  1122. "if( enableSpecular )",
  1123. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  1124. "mat3 tsb = mat3( normalize( vTangent ), normalize( vBinormal ), normalize( vNormal ) );",
  1125. "vec3 finalNormal = tsb * normalTex;",
  1126. "vec3 normal = normalize( finalNormal );",
  1127. "vec3 viewPosition = normalize( vViewPosition );",
  1128. // point lights
  1129. "#if MAX_POINT_LIGHTS > 0",
  1130. "vec3 pointDiffuse = vec3( 0.0 );",
  1131. "vec3 pointSpecular = vec3( 0.0 );",
  1132. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  1133. "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
  1134. "float pointDistance = vPointLight[ i ].w;",
  1135. // diffuse
  1136. "#ifdef WRAP_AROUND",
  1137. "float pointDiffuseWeightFull = max( dot( normal, pointVector ), 0.0 );",
  1138. "float pointDiffuseWeightHalf = max( 0.5 * dot( normal, pointVector ) + 0.5, 0.0 );",
  1139. "vec3 pointDiffuseWeight = mix( vec3 ( pointDiffuseWeightFull ), vec3( pointDiffuseWeightHalf ), wrapRGB );",
  1140. "#else",
  1141. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  1142. "#endif",
  1143. "pointDiffuse += pointDistance * pointLightColor[ i ] * uDiffuseColor * pointDiffuseWeight;",
  1144. // specular
  1145. "vec3 pointHalfVector = normalize( pointVector + viewPosition );",
  1146. "float pointDotNormalHalf = max( dot( normal, pointHalfVector ), 0.0 );",
  1147. "float pointSpecularWeight = specularTex.r * max( pow( pointDotNormalHalf, uShininess ), 0.0 );",
  1148. "#ifdef PHYSICALLY_BASED_SHADING",
  1149. // 2.0 => 2.0001 is hack to work around ANGLE bug
  1150. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  1151. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( pointVector, pointHalfVector ), 5.0 );",
  1152. "pointSpecular += schlick * pointLightColor[ i ] * pointSpecularWeight * pointDiffuseWeight * pointDistance * specularNormalization;",
  1153. "#else",
  1154. "pointSpecular += pointDistance * pointLightColor[ i ] * uSpecularColor * pointSpecularWeight * pointDiffuseWeight;",
  1155. "#endif",
  1156. "}",
  1157. "#endif",
  1158. // directional lights
  1159. "#if MAX_DIR_LIGHTS > 0",
  1160. "vec3 dirDiffuse = vec3( 0.0 );",
  1161. "vec3 dirSpecular = vec3( 0.0 );",
  1162. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  1163. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  1164. "vec3 dirVector = normalize( lDirection.xyz );",
  1165. // diffuse
  1166. "#ifdef WRAP_AROUND",
  1167. "float directionalLightWeightingFull = max( dot( normal, dirVector ), 0.0 );",
  1168. "float directionalLightWeightingHalf = max( 0.5 * dot( normal, dirVector ) + 0.5, 0.0 );",
  1169. "vec3 dirDiffuseWeight = mix( vec3( directionalLightWeightingFull ), vec3( directionalLightWeightingHalf ), wrapRGB );",
  1170. "#else",
  1171. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  1172. "#endif",
  1173. "dirDiffuse += directionalLightColor[ i ] * uDiffuseColor * dirDiffuseWeight;",
  1174. // specular
  1175. "vec3 dirHalfVector = normalize( dirVector + viewPosition );",
  1176. "float dirDotNormalHalf = max( dot( normal, dirHalfVector ), 0.0 );",
  1177. "float dirSpecularWeight = specularTex.r * max( pow( dirDotNormalHalf, uShininess ), 0.0 );",
  1178. "#ifdef PHYSICALLY_BASED_SHADING",
  1179. // 2.0 => 2.0001 is hack to work around ANGLE bug
  1180. "float specularNormalization = ( uShininess + 2.0001 ) / 8.0;",
  1181. "vec3 schlick = uSpecularColor + vec3( 1.0 - uSpecularColor ) * pow( 1.0 - dot( dirVector, dirHalfVector ), 5.0 );",
  1182. "dirSpecular += schlick * directionalLightColor[ i ] * dirSpecularWeight * dirDiffuseWeight * specularNormalization;",
  1183. "#else",
  1184. "dirSpecular += directionalLightColor[ i ] * uSpecularColor * dirSpecularWeight * dirDiffuseWeight;",
  1185. "#endif",
  1186. "}",
  1187. "#endif",
  1188. // all lights contribution summation
  1189. "vec3 totalDiffuse = vec3( 0.0 );",
  1190. "vec3 totalSpecular = vec3( 0.0 );",
  1191. "#if MAX_DIR_LIGHTS > 0",
  1192. "totalDiffuse += dirDiffuse;",
  1193. "totalSpecular += dirSpecular;",
  1194. "#endif",
  1195. "#if MAX_POINT_LIGHTS > 0",
  1196. "totalDiffuse += pointDiffuse;",
  1197. "totalSpecular += pointSpecular;",
  1198. "#endif",
  1199. "gl_FragColor.xyz = gl_FragColor.xyz * ( totalDiffuse + ambientLightColor * uAmbientColor) + totalSpecular;",
  1200. "if ( enableReflection ) {",
  1201. "vec3 wPos = cameraPosition - vViewPosition;",
  1202. "vec3 vReflect = reflect( normalize( wPos ), normal );",
  1203. "vec4 cubeColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  1204. "#ifdef GAMMA_INPUT",
  1205. "cubeColor.xyz *= cubeColor.xyz;",
  1206. "#endif",
  1207. "gl_FragColor.xyz = mix( gl_FragColor.xyz, cubeColor.xyz, specularTex.r * uReflectivity );",
  1208. "}",
  1209. THREE.ShaderChunk[ "shadowmap_fragment" ],
  1210. THREE.ShaderChunk[ "linear_to_gamma_fragment" ],
  1211. THREE.ShaderChunk[ "fog_fragment" ],
  1212. "}"
  1213. ].join("\n"),
  1214. vertexShader: [
  1215. "attribute vec4 tangent;",
  1216. "uniform vec2 uOffset;",
  1217. "uniform vec2 uRepeat;",
  1218. "#ifdef VERTEX_TEXTURES",
  1219. "uniform sampler2D tDisplacement;",
  1220. "uniform float uDisplacementScale;",
  1221. "uniform float uDisplacementBias;",
  1222. "#endif",
  1223. "varying vec3 vTangent;",
  1224. "varying vec3 vBinormal;",
  1225. "varying vec3 vNormal;",
  1226. "varying vec2 vUv;",
  1227. "#if MAX_POINT_LIGHTS > 0",
  1228. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  1229. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  1230. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  1231. "#endif",
  1232. "varying vec3 vViewPosition;",
  1233. THREE.ShaderChunk[ "shadowmap_pars_vertex" ],
  1234. "void main() {",
  1235. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  1236. "vViewPosition = -mvPosition.xyz;",
  1237. // normal, tangent and binormal vectors
  1238. "vNormal = normalMatrix * normal;",
  1239. "vTangent = normalMatrix * tangent.xyz;",
  1240. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  1241. "vUv = uv * uRepeat + uOffset;",
  1242. // point lights
  1243. "#if MAX_POINT_LIGHTS > 0",
  1244. "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",
  1245. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  1246. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  1247. "float lDistance = 1.0;",
  1248. "if ( pointLightDistance[ i ] > 0.0 )",
  1249. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  1250. "lVector = normalize( lVector );",
  1251. "vPointLight[ i ] = vec4( lVector, lDistance );",
  1252. "}",
  1253. "#endif",
  1254. // displacement mapping
  1255. "#ifdef VERTEX_TEXTURES",
  1256. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  1257. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  1258. "vec4 displacedPosition = vec4( normalize( vNormal.xyz ) * df, 0.0 ) + mvPosition;",
  1259. "gl_Position = projectionMatrix * displacedPosition;",
  1260. "#else",
  1261. "gl_Position = projectionMatrix * mvPosition;",
  1262. "#endif",
  1263. THREE.ShaderChunk[ "shadowmap_vertex" ],
  1264. "}"
  1265. ].join("\n")
  1266. },
  1267. /* -------------------------------------------------------------------------
  1268. // Cube map shader
  1269. ------------------------------------------------------------------------- */
  1270. 'cube': {
  1271. uniforms: { "tCube": { type: "t", value: 1, texture: null },
  1272. "tFlip": { type: "f", value: -1 } },
  1273. vertexShader: [
  1274. "varying vec3 vViewPosition;",
  1275. "void main() {",
  1276. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  1277. "vViewPosition = cameraPosition - mPosition.xyz;",
  1278. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  1279. "}"
  1280. ].join("\n"),
  1281. fragmentShader: [
  1282. "uniform samplerCube tCube;",
  1283. "uniform float tFlip;",
  1284. "varying vec3 vViewPosition;",
  1285. "void main() {",
  1286. "vec3 wPos = cameraPosition - vViewPosition;",
  1287. "gl_FragColor = textureCube( tCube, vec3( tFlip * wPos.x, wPos.yz ) );",
  1288. "}"
  1289. ].join("\n")
  1290. }
  1291. }
  1292. };
  1293. };/**
  1294. * @author alteredq / http://alteredqualia.com/
  1295. */
  1296. THREE.BufferGeometry = function () {
  1297. this.id = THREE.GeometryCount ++;
  1298. // GL buffers
  1299. this.vertexIndexBuffer = null;
  1300. this.vertexPositionBuffer = null;
  1301. this.vertexNormalBuffer = null;
  1302. this.vertexUvBuffer = null;
  1303. this.vertexColorBuffer = null;
  1304. // typed arrays (kept only if dynamic flag is set)
  1305. this.vertexIndexArray = null;
  1306. this.vertexPositionArray = null;
  1307. this.vertexNormalArray = null;
  1308. this.vertexUvArray = null;
  1309. this.vertexColorArray = null;
  1310. this.dynamic = false;
  1311. // boundings
  1312. this.boundingBox = null;
  1313. this.boundingSphere = null;
  1314. // for compatibility
  1315. this.morphTargets = [];
  1316. };
  1317. THREE.BufferGeometry.prototype = {
  1318. constructor : THREE.BufferGeometry,
  1319. // for compatibility
  1320. computeBoundingBox: function () {
  1321. },
  1322. // for compatibility
  1323. computeBoundingSphere: function () {
  1324. }
  1325. };
  1326. /**
  1327. * @author zz85 / http://www.lab4games.net/zz85/blog
  1328. * Extensible curve object
  1329. *
  1330. * Some common of Curve methods
  1331. * .getPoint(t), getTangent(t)
  1332. * .getPointAt(u), getTagentAt(u)
  1333. * .getPoints(), .getSpacedPoints()
  1334. * .getLength()
  1335. * .updateArcLengths()
  1336. *
  1337. * This file contains following classes:
  1338. *
  1339. * -- 2d classes --
  1340. * THREE.Curve
  1341. * THREE.LineCurve
  1342. * THREE.QuadraticBezierCurve
  1343. * THREE.CubicBezierCurve
  1344. * THREE.SplineCurve
  1345. * THREE.ArcCurve
  1346. *
  1347. * -- 3d classes --
  1348. * THREE.LineCurve3
  1349. * THREE.QuadraticBezierCurve3
  1350. * THREE.CubicBezierCurve3
  1351. * THREE.SplineCurve3
  1352. * THREE.ClosedSplineCurve3
  1353. *
  1354. * A series of curves can be represented as a THREE.CurvePath
  1355. *
  1356. **/
  1357. /**************************************************************
  1358. * Abstract Curve base class
  1359. **************************************************************/
  1360. THREE.Curve = function () {
  1361. };
  1362. // Virtual base class method to overwrite and implement in subclasses
  1363. // - t [0 .. 1]
  1364. THREE.Curve.prototype.getPoint = function ( t ) {
  1365. console.log( "Warning, getPoint() not implemented!" );
  1366. return null;
  1367. };
  1368. // Get point at relative position in curve according to arc length
  1369. // - u [0 .. 1]
  1370. THREE.Curve.prototype.getPointAt = function ( u ) {
  1371. var t = this.getUtoTmapping( u );
  1372. return this.getPoint( t );
  1373. };
  1374. // Get sequence of points using getPoint( t )
  1375. THREE.Curve.prototype.getPoints = function ( divisions ) {
  1376. if ( !divisions ) divisions = 5;
  1377. var d, pts = [];
  1378. for ( d = 0; d <= divisions; d ++ ) {
  1379. pts.push( this.getPoint( d / divisions ) );
  1380. }
  1381. return pts;
  1382. };
  1383. // Get sequence of points using getPointAt( u )
  1384. THREE.Curve.prototype.getSpacedPoints = function ( divisions ) {
  1385. if ( !divisions ) divisions = 5;
  1386. var d, pts = [];
  1387. for ( d = 0; d <= divisions; d ++ ) {
  1388. pts.push( this.getPointAt( d / divisions ) );
  1389. }
  1390. return pts;
  1391. };
  1392. // Get total curve arc length
  1393. THREE.Curve.prototype.getLength = function () {
  1394. var lengths = this.getLengths();
  1395. return lengths[ lengths.length - 1 ];
  1396. };
  1397. // Get list of cumulative segment lengths
  1398. THREE.Curve.prototype.getLengths = function ( divisions ) {
  1399. if ( !divisions ) divisions = (this.__arcLengthDivisions) ? (this.__arcLengthDivisions): 200;
  1400. if ( this.cacheArcLengths
  1401. && ( this.cacheArcLengths.length == divisions + 1 )
  1402. && !this.needsUpdate) {
  1403. //console.log( "cached", this.cacheArcLengths );
  1404. return this.cacheArcLengths;
  1405. }
  1406. this.needsUpdate = false;
  1407. var cache = [];
  1408. var current, last = this.getPoint( 0 );
  1409. var p, sum = 0;
  1410. cache.push( 0 );
  1411. for ( p = 1; p <= divisions; p ++ ) {
  1412. current = this.getPoint ( p / divisions );
  1413. sum += current.distanceTo( last );
  1414. cache.push( sum );
  1415. last = current;
  1416. }
  1417. this.cacheArcLengths = cache;
  1418. return cache; // { sums: cache, sum:sum }; Sum is in the last element.
  1419. };
  1420. THREE.Curve.prototype.updateArcLengths = function() {
  1421. this.needsUpdate = true;
  1422. this.getLengths();
  1423. };
  1424. // Given u ( 0 .. 1 ), get a t to find p. This gives you points which are equi distance
  1425. THREE.Curve.prototype.getUtoTmapping = function ( u, distance ) {
  1426. var arcLengths = this.getLengths();
  1427. var i = 0, il = arcLengths.length;
  1428. var targetArcLength; // The targeted u distance value to get
  1429. if ( distance ) {
  1430. targetArcLength = distance;
  1431. } else {
  1432. targetArcLength = u * arcLengths[ il - 1 ];
  1433. }
  1434. //var time = Date.now();
  1435. // binary search for the index with largest value smaller than target u distance
  1436. var low = 0, high = il - 1, comparison;
  1437. while ( low <= high ) {
  1438. 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
  1439. comparison = arcLengths[ i ] - targetArcLength;
  1440. if ( comparison < 0 ) {
  1441. low = i + 1;
  1442. continue;
  1443. } else if ( comparison > 0 ) {
  1444. high = i - 1;
  1445. continue;
  1446. } else {
  1447. high = i;
  1448. break;
  1449. // DONE
  1450. }
  1451. }
  1452. i = high;
  1453. //console.log('b' , i, low, high, Date.now()- time);
  1454. if ( arcLengths[ i ] == targetArcLength ) {
  1455. var t = i / ( il - 1 );
  1456. return t;
  1457. }
  1458. // we could get finer grain at lengths, or use simple interpolatation between two points
  1459. var lengthBefore = arcLengths[ i ];
  1460. var lengthAfter = arcLengths[ i + 1 ];
  1461. var segmentLength = lengthAfter - lengthBefore;
  1462. // determine where we are between the 'before' and 'after' points
  1463. var segmentFraction = ( targetArcLength - lengthBefore ) / segmentLength;
  1464. // add that fractional amount to t
  1465. var t = ( i + segmentFraction ) / ( il -1 );
  1466. return t;
  1467. };
  1468. // In 2D space, there are actually 2 normal vectors,
  1469. // and in 3D space, infinte
  1470. // TODO this should be depreciated.
  1471. THREE.Curve.prototype.getNormalVector = function( t ) {
  1472. var vec = this.getTangent( t );
  1473. return new THREE.Vector2( -vec.y , vec.x );
  1474. };
  1475. // Returns a unit vector tangent at t
  1476. // In case any sub curve does not implement its tangent / normal finding,
  1477. // we get 2 points with a small delta and find a gradient of the 2 points
  1478. // which seems to make a reasonable approximation
  1479. THREE.Curve.prototype.getTangent = function( t ) {
  1480. var delta = 0.0001;
  1481. var t1 = t - delta;
  1482. var t2 = t + delta;
  1483. // Capping in case of danger
  1484. if ( t1 < 0 ) t1 = 0;
  1485. if ( t2 > 1 ) t2 = 1;
  1486. var pt1 = this.getPoint( t1 );
  1487. var pt2 = this.getPoint( t2 );
  1488. var vec = pt2.clone().subSelf(pt1);
  1489. return vec.normalize();
  1490. };
  1491. THREE.Curve.prototype.getTangentAt = function ( u ) {
  1492. var t = this.getUtoTmapping( u );
  1493. return this.getTangent( t );
  1494. };
  1495. /**************************************************************
  1496. * Line
  1497. **************************************************************/
  1498. THREE.LineCurve = function ( v1, v2 ) {
  1499. this.v1 = v1;
  1500. this.v2 = v2;
  1501. };
  1502. THREE.LineCurve.prototype = new THREE.Curve();
  1503. THREE.LineCurve.prototype.constructor = THREE.LineCurve;
  1504. THREE.LineCurve.prototype.getPoint = function ( t ) {
  1505. var point = this.v2.clone().subSelf(this.v1);
  1506. point.multiplyScalar( t ).addSelf( this.v1 );
  1507. return point;
  1508. };
  1509. // Line curve is linear, so we can overwrite default getPointAt
  1510. THREE.LineCurve.prototype.getPointAt = function ( u ) {
  1511. return this.getPoint( u );
  1512. };
  1513. THREE.LineCurve.prototype.getTangent = function( t ) {
  1514. var tangent = this.v2.clone().subSelf(this.v1);
  1515. return tangent.normalize();
  1516. };
  1517. /**************************************************************
  1518. * Quadratic Bezier curve
  1519. **************************************************************/
  1520. THREE.QuadraticBezierCurve = function ( v0, v1, v2 ) {
  1521. this.v0 = v0;
  1522. this.v1 = v1;
  1523. this.v2 = v2;
  1524. };
  1525. THREE.QuadraticBezierCurve.prototype = new THREE.Curve();
  1526. THREE.QuadraticBezierCurve.prototype.constructor = THREE.QuadraticBezierCurve;
  1527. THREE.QuadraticBezierCurve.prototype.getPoint = function ( t ) {
  1528. var tx, ty;
  1529. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  1530. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  1531. return new THREE.Vector2( tx, ty );
  1532. };
  1533. THREE.QuadraticBezierCurve.prototype.getTangent = function( t ) {
  1534. var tx, ty;
  1535. tx = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.x, this.v1.x, this.v2.x );
  1536. ty = THREE.Curve.Utils.tangentQuadraticBezier( t, this.v0.y, this.v1.y, this.v2.y );
  1537. // returns unit vector
  1538. var tangent = new THREE.Vector2( tx, ty );
  1539. tangent.normalize();
  1540. return tangent;
  1541. };
  1542. /**************************************************************
  1543. * Cubic Bezier curve
  1544. **************************************************************/
  1545. THREE.CubicBezierCurve = function ( v0, v1, v2, v3 ) {
  1546. this.v0 = v0;
  1547. this.v1 = v1;
  1548. this.v2 = v2;
  1549. this.v3 = v3;
  1550. };
  1551. THREE.CubicBezierCurve.prototype = new THREE.Curve();
  1552. THREE.CubicBezierCurve.prototype.constructor = THREE.CubicBezierCurve;
  1553. THREE.CubicBezierCurve.prototype.getPoint = function ( t ) {
  1554. var tx, ty;
  1555. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  1556. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  1557. return new THREE.Vector2( tx, ty );
  1558. };
  1559. THREE.CubicBezierCurve.prototype.getTangent = function( t ) {
  1560. var tx, ty;
  1561. tx = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  1562. ty = THREE.Curve.Utils.tangentCubicBezier( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  1563. var tangent = new THREE.Vector2( tx, ty );
  1564. tangent.normalize();
  1565. return tangent;
  1566. };
  1567. /**************************************************************
  1568. * Spline curve
  1569. **************************************************************/
  1570. THREE.SplineCurve = function ( points /* array of Vector2 */ ) {
  1571. this.points = (points == undefined) ? [] : points;
  1572. };
  1573. THREE.SplineCurve.prototype = new THREE.Curve();
  1574. THREE.SplineCurve.prototype.constructor = THREE.SplineCurve;
  1575. THREE.SplineCurve.prototype.getPoint = function ( t ) {
  1576. var v = new THREE.Vector2();
  1577. var c = [];
  1578. var points = this.points, point, intPoint, weight;
  1579. point = ( points.length - 1 ) * t;
  1580. intPoint = Math.floor( point );
  1581. weight = point - intPoint;
  1582. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  1583. c[ 1 ] = intPoint;
  1584. c[ 2 ] = intPoint > points.length - 2 ? points.length -1 : intPoint + 1;
  1585. c[ 3 ] = intPoint > points.length - 3 ? points.length -1 : intPoint + 2;
  1586. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  1587. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  1588. return v;
  1589. };
  1590. /**************************************************************
  1591. * Arc curve
  1592. **************************************************************/
  1593. THREE.ArcCurve = function ( aX, aY, aRadius,
  1594. aStartAngle, aEndAngle,
  1595. aClockwise ) {
  1596. this.aX = aX;
  1597. this.aY = aY;
  1598. this.aRadius = aRadius;
  1599. this.aStartAngle = aStartAngle;
  1600. this.aEndAngle = aEndAngle;
  1601. this.aClockwise = aClockwise;
  1602. };
  1603. THREE.ArcCurve.prototype = new THREE.Curve();
  1604. THREE.ArcCurve.prototype.constructor = THREE.ArcCurve;
  1605. THREE.ArcCurve.prototype.getPoint = function ( t ) {
  1606. var deltaAngle = this.aEndAngle - this.aStartAngle;
  1607. if ( !this.aClockwise ) {
  1608. t = 1 - t;
  1609. }
  1610. var angle = this.aStartAngle + t * deltaAngle;
  1611. var tx = this.aX + this.aRadius * Math.cos( angle );
  1612. var ty = this.aY + this.aRadius * Math.sin( angle );
  1613. return new THREE.Vector2( tx, ty );
  1614. };
  1615. /**************************************************************
  1616. * Utils
  1617. **************************************************************/
  1618. THREE.Curve.Utils = {
  1619. tangentQuadraticBezier: function ( t, p0, p1, p2 ) {
  1620. return 2 * ( 1 - t ) * ( p1 - p0 ) + 2 * t * ( p2 - p1 );
  1621. },
  1622. // Puay Bing, thanks for helping with this derivative!
  1623. tangentCubicBezier: function (t, p0, p1, p2, p3 ) {
  1624. return -3 * p0 * (1 - t) * (1 - t) +
  1625. 3 * p1 * (1 - t) * (1-t) - 6 *t *p1 * (1-t) +
  1626. 6 * t * p2 * (1-t) - 3 * t * t * p2 +
  1627. 3 * t * t * p3;
  1628. },
  1629. tangentSpline: function ( t, p0, p1, p2, p3 ) {
  1630. // To check if my formulas are correct
  1631. var h00 = 6 * t * t - 6 * t; // derived from 2t^3 − 3t^2 + 1
  1632. var h10 = 3 * t * t - 4 * t + 1; // t^3 − 2t^2 + t
  1633. var h01 = -6 * t * t + 6 * t; // − 2t3 + 3t2
  1634. var h11 = 3 * t * t - 2 * t; // t3 − t2
  1635. return h00 + h10 + h01 + h11;
  1636. },
  1637. // Catmull-Rom
  1638. interpolate: function( p0, p1, p2, p3, t ) {
  1639. var v0 = ( p2 - p0 ) * 0.5;
  1640. var v1 = ( p3 - p1 ) * 0.5;
  1641. var t2 = t * t;
  1642. var t3 = t * t2;
  1643. return ( 2 * p1 - 2 * p2 + v0 + v1 ) * t3 + ( - 3 * p1 + 3 * p2 - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  1644. }
  1645. };
  1646. // TODO: Transformation for Curves?
  1647. /**************************************************************
  1648. * 3D Curves
  1649. **************************************************************/
  1650. // A Factory method for creating new curve subclasses
  1651. THREE.Curve.create = function( constructor, getPointFunc ) {
  1652. var subClass = constructor;
  1653. subClass.prototype = new THREE.Curve();
  1654. subClass.prototype.constructor = constructor;
  1655. subClass.prototype.getPoint = getPointFunc;
  1656. return subClass;
  1657. };
  1658. /**************************************************************
  1659. * Line3D
  1660. **************************************************************/
  1661. THREE.LineCurve3 = THREE.Curve.create(
  1662. function ( v1, v2 ) {
  1663. this.v1 = v1;
  1664. this.v2 = v2;
  1665. },
  1666. function ( t ) {
  1667. var r = new THREE.Vector3();
  1668. r.sub( this.v2, this.v1 ); // diff
  1669. r.multiplyScalar( t );
  1670. r.addSelf( this.v1 );
  1671. return r;
  1672. }
  1673. );
  1674. /**************************************************************
  1675. * Quadratic Bezier 3D curve
  1676. **************************************************************/
  1677. THREE.QuadraticBezierCurve3 = THREE.Curve.create(
  1678. function ( v0, v1, v2 ) {
  1679. this.v0 = v0;
  1680. this.v1 = v1;
  1681. this.v2 = v2;
  1682. },
  1683. function ( t ) {
  1684. var tx, ty, tz;
  1685. tx = THREE.Shape.Utils.b2( t, this.v0.x, this.v1.x, this.v2.x );
  1686. ty = THREE.Shape.Utils.b2( t, this.v0.y, this.v1.y, this.v2.y );
  1687. tz = THREE.Shape.Utils.b2( t, this.v0.z, this.v1.z, this.v2.z );
  1688. return new THREE.Vector3( tx, ty, tz );
  1689. }
  1690. );
  1691. /**************************************************************
  1692. * Cubic Bezier 3D curve
  1693. **************************************************************/
  1694. THREE.CubicBezierCurve3 = THREE.Curve.create(
  1695. function ( v0, v1, v2, v3 ) {
  1696. this.v0 = v0;
  1697. this.v1 = v1;
  1698. this.v2 = v2;
  1699. this.v3 = v3;
  1700. },
  1701. function ( t ) {
  1702. var tx, ty, tz;
  1703. tx = THREE.Shape.Utils.b3( t, this.v0.x, this.v1.x, this.v2.x, this.v3.x );
  1704. ty = THREE.Shape.Utils.b3( t, this.v0.y, this.v1.y, this.v2.y, this.v3.y );
  1705. tz = THREE.Shape.Utils.b3( t, this.v0.z, this.v1.z, this.v2.z, this.v3.z );
  1706. return new THREE.Vector3( tx, ty, tz );
  1707. }
  1708. );
  1709. /**************************************************************
  1710. * Spline 3D curve
  1711. **************************************************************/
  1712. THREE.SplineCurve3 = THREE.Curve.create(
  1713. function ( points /* array of Vector3 */) {
  1714. this.points = (points == undefined) ? [] : points;
  1715. },
  1716. function ( t ) {
  1717. var v = new THREE.Vector3();
  1718. var c = [];
  1719. var points = this.points, point, intPoint, weight;
  1720. point = ( points.length - 1 ) * t;
  1721. intPoint = Math.floor( point );
  1722. weight = point - intPoint;
  1723. c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  1724. c[ 1 ] = intPoint;
  1725. c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  1726. c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  1727. var pt0 = points[ c[0] ],
  1728. pt1 = points[ c[1] ],
  1729. pt2 = points[ c[2] ],
  1730. pt3 = points[ c[3] ];
  1731. v.x = THREE.Curve.Utils.interpolate(pt0.x, pt1.x, pt2.x, pt3.x, weight);
  1732. v.y = THREE.Curve.Utils.interpolate(pt0.y, pt1.y, pt2.y, pt3.y, weight);
  1733. v.z = THREE.Curve.Utils.interpolate(pt0.z, pt1.z, pt2.z, pt3.z, weight);
  1734. return v;
  1735. }
  1736. );
  1737. // THREE.SplineCurve3.prototype.getTangent = function(t) {
  1738. // var v = new THREE.Vector3();
  1739. // var c = [];
  1740. // var points = this.points, point, intPoint, weight;
  1741. // point = ( points.length - 1 ) * t;
  1742. // intPoint = Math.floor( point );
  1743. // weight = point - intPoint;
  1744. // c[ 0 ] = intPoint == 0 ? intPoint : intPoint - 1;
  1745. // c[ 1 ] = intPoint;
  1746. // c[ 2 ] = intPoint > points.length - 2 ? points.length - 1 : intPoint + 1;
  1747. // c[ 3 ] = intPoint > points.length - 3 ? points.length - 1 : intPoint + 2;
  1748. // var pt0 = points[ c[0] ],
  1749. // pt1 = points[ c[1] ],
  1750. // pt2 = points[ c[2] ],
  1751. // pt3 = points[ c[3] ];
  1752. // // t = weight;
  1753. // v.x = THREE.Curve.Utils.tangentSpline( t, pt0.x, pt1.x, pt2.x, pt3.x );
  1754. // v.y = THREE.Curve.Utils.tangentSpline( t, pt0.y, pt1.y, pt2.y, pt3.y );
  1755. // v.z = THREE.Curve.Utils.tangentSpline( t, pt0.z, pt1.z, pt2.z, pt3.z );
  1756. // return v;
  1757. // }
  1758. /**************************************************************
  1759. * Closed Spline 3D curve
  1760. **************************************************************/
  1761. THREE.ClosedSplineCurve3 = THREE.Curve.create(
  1762. function ( points /* array of Vector3 */) {
  1763. this.points = (points == undefined) ? [] : points;
  1764. },
  1765. function ( t ) {
  1766. var v = new THREE.Vector3();
  1767. var c = [];
  1768. var points = this.points, point, intPoint, weight;
  1769. point = ( points.length - 0 ) * t;
  1770. // This needs to be from 0-length +1
  1771. intPoint = Math.floor( point );
  1772. weight = point - intPoint;
  1773. intPoint += intPoint > 0 ? 0 : ( Math.floor( Math.abs( intPoint ) / points.length ) + 1 ) * points.length;
  1774. c[ 0 ] = ( intPoint - 1 ) % points.length;
  1775. c[ 1 ] = ( intPoint ) % points.length;
  1776. c[ 2 ] = ( intPoint + 1 ) % points.length;
  1777. c[ 3 ] = ( intPoint + 2 ) % points.length;
  1778. v.x = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].x, points[ c[ 1 ] ].x, points[ c[ 2 ] ].x, points[ c[ 3 ] ].x, weight );
  1779. v.y = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].y, points[ c[ 1 ] ].y, points[ c[ 2 ] ].y, points[ c[ 3 ] ].y, weight );
  1780. v.z = THREE.Curve.Utils.interpolate( points[ c[ 0 ] ].z, points[ c[ 1 ] ].z, points[ c[ 2 ] ].z, points[ c[ 3 ] ].z, weight );
  1781. return v;
  1782. }
  1783. );/**
  1784. * @author zz85 / http://www.lab4games.net/zz85/blog
  1785. *
  1786. **/
  1787. /**************************************************************
  1788. * Curved Path - a curve path is simply a array of connected
  1789. * curves, but retains the api of a curve
  1790. **************************************************************/
  1791. THREE.CurvePath = function () {
  1792. this.curves = [];
  1793. this.bends = [];
  1794. this.autoClose = false; // Automatically closes the path
  1795. };
  1796. THREE.CurvePath.prototype = new THREE.Curve();
  1797. THREE.CurvePath.prototype.constructor = THREE.CurvePath;
  1798. THREE.CurvePath.prototype.add = function ( curve ) {
  1799. this.curves.push( curve );
  1800. };
  1801. THREE.CurvePath.prototype.checkConnection = function() {
  1802. // TODO
  1803. // If the ending of curve is not connected to the starting
  1804. // or the next curve, then, this is not a real path
  1805. };
  1806. THREE.CurvePath.prototype.closePath = function() {
  1807. // TODO Test
  1808. // and verify for vector3 (needs to implement equals)
  1809. // Add a line curve if start and end of lines are not connected
  1810. var startPoint = this.curves[0].getPoint(0);
  1811. var endPoint = this.curves[this.curves.length-1].getPoint(1);
  1812. if (!startPoint.equals(endPoint)) {
  1813. this.curves.push( new THREE.LineCurve(endPoint, startPoint) );
  1814. }
  1815. };
  1816. // To get accurate point with reference to
  1817. // entire path distance at time t,
  1818. // following has to be done:
  1819. // 1. Length of each sub path have to be known
  1820. // 2. Locate and identify type of curve
  1821. // 3. Get t for the curve
  1822. // 4. Return curve.getPointAt(t')
  1823. THREE.CurvePath.prototype.getPoint = function( t ) {
  1824. var d = t * this.getLength();
  1825. var curveLengths = this.getCurveLengths();
  1826. var i = 0, diff, curve;
  1827. // To think about boundaries points.
  1828. while ( i < curveLengths.length ) {
  1829. if ( curveLengths[ i ] >= d ) {
  1830. diff = curveLengths[ i ] - d;
  1831. curve = this.curves[ i ];
  1832. var u = 1 - diff / curve.getLength();
  1833. return curve.getPointAt( u );
  1834. break;
  1835. }
  1836. i ++;
  1837. }
  1838. return null;
  1839. // loop where sum != 0, sum > d , sum+1 <d
  1840. };
  1841. /*
  1842. THREE.CurvePath.prototype.getTangent = function( t ) {
  1843. };*/
  1844. // We cannot use the default THREE.Curve getPoint() with getLength() because in
  1845. // THREE.Curve, getLength() depends on getPoint() but in THREE.CurvePath
  1846. // getPoint() depends on getLength
  1847. THREE.CurvePath.prototype.getLength = function() {
  1848. var lens = this.getCurveLengths();
  1849. return lens[ lens.length - 1 ];
  1850. };
  1851. // Compute lengths and cache them
  1852. // We cannot overwrite getLengths() because UtoT mapping uses it.
  1853. THREE.CurvePath.prototype.getCurveLengths = function() {
  1854. // We use cache values if curves and cache array are same length
  1855. if ( this.cacheLengths && this.cacheLengths.length == this.curves.length ) {
  1856. return this.cacheLengths;
  1857. };
  1858. // Get length of subsurve
  1859. // Push sums into cached array
  1860. var lengths = [], sums = 0;
  1861. var i, il = this.curves.length;
  1862. for ( i = 0; i < il; i ++ ) {
  1863. sums += this.curves[ i ].getLength();
  1864. lengths.push( sums );
  1865. }
  1866. this.cacheLengths = lengths;
  1867. return lengths;
  1868. };
  1869. // Returns min and max coordinates, as well as centroid
  1870. THREE.CurvePath.prototype.getBoundingBox = function () {
  1871. var points = this.getPoints();
  1872. var maxX, maxY;
  1873. var minX, minY;
  1874. maxX = maxY = Number.NEGATIVE_INFINITY;
  1875. minX = minY = Number.POSITIVE_INFINITY;
  1876. var p, i, il, sum;
  1877. sum = new THREE.Vector2();
  1878. for ( i = 0, il = points.length; i < il; i ++ ) {
  1879. p = points[ i ];
  1880. if ( p.x > maxX ) maxX = p.x;
  1881. else if ( p.x < minX ) minX = p.x;
  1882. if ( p.y > maxY ) maxY = p.y;
  1883. else if ( p.y < maxY ) minY = p.y;
  1884. sum.addSelf( p.x, p.y );
  1885. }
  1886. return {
  1887. minX: minX,
  1888. minY: minY,
  1889. maxX: maxX,
  1890. maxY: maxY,
  1891. centroid: sum.divideScalar( il )
  1892. };
  1893. };
  1894. /**************************************************************
  1895. * Create Geometries Helpers
  1896. **************************************************************/
  1897. /// Generate geometry from path points (for Line or ParticleSystem objects)
  1898. THREE.CurvePath.prototype.createPointsGeometry = function( divisions ) {
  1899. var pts = this.getPoints( divisions, true );
  1900. return this.createGeometry( pts );
  1901. };
  1902. // Generate geometry from equidistance sampling along the path
  1903. THREE.CurvePath.prototype.createSpacedPointsGeometry = function( divisions ) {
  1904. var pts = this.getSpacedPoints( divisions, true );
  1905. return this.createGeometry( pts );
  1906. };
  1907. THREE.CurvePath.prototype.createGeometry = function( points ) {
  1908. var geometry = new THREE.Geometry();
  1909. for( var i = 0; i < points.length; i ++ ) {
  1910. geometry.vertices.push( new THREE.Vertex( points[ i ].x, points[ i ].y, 0 ) );
  1911. }
  1912. return geometry;
  1913. };
  1914. /**************************************************************
  1915. * Bend / Wrap Helper Methods
  1916. **************************************************************/
  1917. // Wrap path / Bend modifiers?
  1918. THREE.CurvePath.prototype.addWrapPath = function ( bendpath ) {
  1919. this.bends.push( bendpath );
  1920. };
  1921. THREE.CurvePath.prototype.getTransformedPoints = function( segments, bends ) {
  1922. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  1923. var i, il;
  1924. if ( !bends ) {
  1925. bends = this.bends;
  1926. }
  1927. for ( i = 0, il = bends.length; i < il; i ++ ) {
  1928. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  1929. }
  1930. return oldPts;
  1931. };
  1932. THREE.CurvePath.prototype.getTransformedSpacedPoints = function( segments, bends ) {
  1933. var oldPts = this.getSpacedPoints( segments );
  1934. var i, il;
  1935. if ( !bends ) {
  1936. bends = this.bends;
  1937. }
  1938. for ( i = 0, il = bends.length; i < il; i ++ ) {
  1939. oldPts = this.getWrapPoints( oldPts, bends[ i ] );
  1940. }
  1941. return oldPts;
  1942. };
  1943. // This returns getPoints() bend/wrapped around the contour of a path.
  1944. // Read http://www.planetclegg.com/projects/WarpingTextToSplines.html
  1945. THREE.CurvePath.prototype.getWrapPoints = function ( oldPts, path ) {
  1946. var bounds = this.getBoundingBox();
  1947. var i, il, p, oldX, oldY, xNorm;
  1948. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  1949. p = oldPts[ i ];
  1950. oldX = p.x;
  1951. oldY = p.y;
  1952. xNorm = oldX / bounds.maxX;
  1953. // If using actual distance, for length > path, requires line extrusions
  1954. //xNorm = path.getUtoTmapping(xNorm, oldX); // 3 styles. 1) wrap stretched. 2) wrap stretch by arc length 3) warp by actual distance
  1955. xNorm = path.getUtoTmapping( xNorm, oldX );
  1956. // check for out of bounds?
  1957. var pathPt = path.getPoint( xNorm );
  1958. var normal = path.getNormalVector( xNorm ).multiplyScalar( oldY );
  1959. p.x = pathPt.x + normal.x;
  1960. p.y = pathPt.y + normal.y;
  1961. }
  1962. return oldPts;
  1963. };
  1964. /**
  1965. * https://github.com/mrdoob/eventtarget.js/
  1966. */
  1967. THREE.EventTarget = function () {
  1968. var listeners = {};
  1969. this.addEventListener = function ( type, listener ) {
  1970. if ( listeners[ type ] == undefined ) {
  1971. listeners[ type ] = [];
  1972. }
  1973. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  1974. listeners[ type ].push( listener );
  1975. }
  1976. };
  1977. this.dispatchEvent = function ( event ) {
  1978. for ( var listener in listeners[ event.type ] ) {
  1979. listeners[ event.type ][ listener ]( event );
  1980. }
  1981. };
  1982. this.removeEventListener = function ( type, listener ) {
  1983. var index = listeners[ type ].indexOf( listener );
  1984. if ( index !== - 1 ) {
  1985. listeners[ type ].splice( index, 1 );
  1986. }
  1987. };
  1988. };
  1989. /**
  1990. * @author alteredq / http://alteredqualia.com/
  1991. */
  1992. THREE.Gyroscope = function () {
  1993. THREE.Object3D.call( this );
  1994. };
  1995. THREE.Gyroscope.prototype = new THREE.Object3D();
  1996. THREE.Gyroscope.prototype.constructor = THREE.Gyroscope;
  1997. THREE.Gyroscope.prototype.updateMatrixWorld = function ( force ) {
  1998. this.matrixAutoUpdate && this.updateMatrix();
  1999. // update matrixWorld
  2000. if ( this.matrixWorldNeedsUpdate || force ) {
  2001. if ( this.parent ) {
  2002. this.matrixWorld.multiply( this.parent.matrixWorld, this.matrix );
  2003. this.matrixWorld.decompose( this.translationWorld, this.rotationWorld, this.scaleWorld );
  2004. this.matrix.decompose( this.translationObject, this.rotationObject, this.scaleObject );
  2005. this.matrixWorld.compose( this.translationWorld, this.rotationObject, this.scaleWorld );
  2006. } else {
  2007. this.matrixWorld.copy( this.matrix );
  2008. }
  2009. this.matrixWorldNeedsUpdate = false;
  2010. force = true;
  2011. }
  2012. // update children
  2013. for ( var i = 0, l = this.children.length; i < l; i ++ ) {
  2014. this.children[ i ].updateMatrixWorld( force );
  2015. }
  2016. };
  2017. THREE.Gyroscope.prototype.translationWorld = new THREE.Vector3();
  2018. THREE.Gyroscope.prototype.translationObject = new THREE.Vector3();
  2019. THREE.Gyroscope.prototype.rotationWorld = new THREE.Quaternion();
  2020. THREE.Gyroscope.prototype.rotationObject = new THREE.Quaternion();
  2021. THREE.Gyroscope.prototype.scaleWorld = new THREE.Vector3();
  2022. THREE.Gyroscope.prototype.scaleObject = new THREE.Vector3();
  2023. /**
  2024. * @author zz85 / http://www.lab4games.net/zz85/blog
  2025. * Creates free form 2d path using series of points, lines or curves.
  2026. *
  2027. **/
  2028. THREE.Path = function ( points ) {
  2029. THREE.CurvePath.call(this);
  2030. this.actions = [];
  2031. if ( points ) {
  2032. this.fromPoints( points );
  2033. }
  2034. };
  2035. THREE.Path.prototype = new THREE.CurvePath();
  2036. THREE.Path.prototype.constructor = THREE.Path;
  2037. THREE.PathActions = {
  2038. MOVE_TO: 'moveTo',
  2039. LINE_TO: 'lineTo',
  2040. QUADRATIC_CURVE_TO: 'quadraticCurveTo', // Bezier quadratic curve
  2041. BEZIER_CURVE_TO: 'bezierCurveTo', // Bezier cubic curve
  2042. CSPLINE_THRU: 'splineThru', // Catmull-rom spline
  2043. ARC: 'arc' // Circle
  2044. };
  2045. // TODO Clean up PATH API
  2046. // Create path using straight lines to connect all points
  2047. // - vectors: array of Vector2
  2048. THREE.Path.prototype.fromPoints = function ( vectors ) {
  2049. this.moveTo( vectors[ 0 ].x, vectors[ 0 ].y );
  2050. for ( var v = 1, vlen = vectors.length; v < vlen; v ++ ) {
  2051. this.lineTo( vectors[ v ].x, vectors[ v ].y );
  2052. };
  2053. };
  2054. // startPath() endPath()?
  2055. THREE.Path.prototype.moveTo = function ( x, y ) {
  2056. var args = Array.prototype.slice.call( arguments );
  2057. this.actions.push( { action: THREE.PathActions.MOVE_TO, args: args } );
  2058. };
  2059. THREE.Path.prototype.lineTo = function ( x, y ) {
  2060. var args = Array.prototype.slice.call( arguments );
  2061. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2062. var x0 = lastargs[ lastargs.length - 2 ];
  2063. var y0 = lastargs[ lastargs.length - 1 ];
  2064. var curve = new THREE.LineCurve( new THREE.Vector2( x0, y0 ), new THREE.Vector2( x, y ) );
  2065. this.curves.push( curve );
  2066. this.actions.push( { action: THREE.PathActions.LINE_TO, args: args } );
  2067. };
  2068. THREE.Path.prototype.quadraticCurveTo = function( aCPx, aCPy, aX, aY ) {
  2069. var args = Array.prototype.slice.call( arguments );
  2070. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2071. var x0 = lastargs[ lastargs.length - 2 ];
  2072. var y0 = lastargs[ lastargs.length - 1 ];
  2073. var curve = new THREE.QuadraticBezierCurve( new THREE.Vector2( x0, y0 ),
  2074. new THREE.Vector2( aCPx, aCPy ),
  2075. new THREE.Vector2( aX, aY ) );
  2076. this.curves.push( curve );
  2077. this.actions.push( { action: THREE.PathActions.QUADRATIC_CURVE_TO, args: args } );
  2078. };
  2079. THREE.Path.prototype.bezierCurveTo = function( aCP1x, aCP1y,
  2080. aCP2x, aCP2y,
  2081. aX, aY ) {
  2082. var args = Array.prototype.slice.call( arguments );
  2083. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2084. var x0 = lastargs[ lastargs.length - 2 ];
  2085. var y0 = lastargs[ lastargs.length - 1 ];
  2086. var curve = new THREE.CubicBezierCurve( new THREE.Vector2( x0, y0 ),
  2087. new THREE.Vector2( aCP1x, aCP1y ),
  2088. new THREE.Vector2( aCP2x, aCP2y ),
  2089. new THREE.Vector2( aX, aY ) );
  2090. this.curves.push( curve );
  2091. this.actions.push( { action: THREE.PathActions.BEZIER_CURVE_TO, args: args } );
  2092. };
  2093. THREE.Path.prototype.splineThru = function( pts /*Array of Vector*/ ) {
  2094. var args = Array.prototype.slice.call( arguments );
  2095. var lastargs = this.actions[ this.actions.length - 1 ].args;
  2096. var x0 = lastargs[ lastargs.length - 2 ];
  2097. var y0 = lastargs[ lastargs.length - 1 ];
  2098. //---
  2099. var npts = [ new THREE.Vector2( x0, y0 ) ];
  2100. Array.prototype.push.apply( npts, pts );
  2101. var curve = new THREE.SplineCurve( npts );
  2102. this.curves.push( curve );
  2103. this.actions.push( { action: THREE.PathActions.CSPLINE_THRU, args: args } );
  2104. };
  2105. // FUTURE: Change the API or follow canvas API?
  2106. // TODO ARC ( x, y, x - radius, y - radius, startAngle, endAngle )
  2107. THREE.Path.prototype.arc = function ( aX, aY, aRadius,
  2108. aStartAngle, aEndAngle, aClockwise ) {
  2109. var args = Array.prototype.slice.call( arguments );
  2110. var laste = this.actions[ this.actions.length - 1];
  2111. var curve = new THREE.ArcCurve( laste.x + aX, laste.y + aY, aRadius,
  2112. aStartAngle, aEndAngle, aClockwise );
  2113. this.curves.push( curve );
  2114. // All of the other actions look to the last two elements in the list to
  2115. // find the ending point, so we need to append them.
  2116. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  2117. args.push(lastPoint.x);
  2118. args.push(lastPoint.y);
  2119. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  2120. };
  2121. THREE.Path.prototype.absarc = function ( aX, aY, aRadius,
  2122. aStartAngle, aEndAngle, aClockwise ) {
  2123. var args = Array.prototype.slice.call( arguments );
  2124. var curve = new THREE.ArcCurve( aX, aY, aRadius,
  2125. aStartAngle, aEndAngle, aClockwise );
  2126. this.curves.push( curve );
  2127. // console.log( 'arc', args );
  2128. // All of the other actions look to the last two elements in the list to
  2129. // find the ending point, so we need to append them.
  2130. var lastPoint = curve.getPoint(aClockwise ? 1 : 0);
  2131. args.push(lastPoint.x);
  2132. args.push(lastPoint.y);
  2133. this.actions.push( { action: THREE.PathActions.ARC, args: args } );
  2134. };
  2135. THREE.Path.prototype.getSpacedPoints = function ( divisions, closedPath ) {
  2136. if ( ! divisions ) divisions = 40;
  2137. var points = [];
  2138. for ( var i = 0; i < divisions; i ++ ) {
  2139. points.push( this.getPoint( i / divisions ) );
  2140. //if( !this.getPoint( i / divisions ) ) throw "DIE";
  2141. }
  2142. // if ( closedPath ) {
  2143. //
  2144. // points.push( points[ 0 ] );
  2145. //
  2146. // }
  2147. return points;
  2148. };
  2149. /* Return an array of vectors based on contour of the path */
  2150. THREE.Path.prototype.getPoints = function( divisions, closedPath ) {
  2151. if (this.useSpacedPoints) {
  2152. console.log('tata');
  2153. return this.getSpacedPoints( divisions, closedPath );
  2154. }
  2155. divisions = divisions || 12;
  2156. var points = [];
  2157. var i, il, item, action, args;
  2158. var cpx, cpy, cpx2, cpy2, cpx1, cpy1, cpx0, cpy0,
  2159. laste, j,
  2160. t, tx, ty;
  2161. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  2162. item = this.actions[ i ];
  2163. action = item.action;
  2164. args = item.args;
  2165. switch( action ) {
  2166. case THREE.PathActions.MOVE_TO:
  2167. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  2168. break;
  2169. case THREE.PathActions.LINE_TO:
  2170. points.push( new THREE.Vector2( args[ 0 ], args[ 1 ] ) );
  2171. break;
  2172. case THREE.PathActions.QUADRATIC_CURVE_TO:
  2173. cpx = args[ 2 ];
  2174. cpy = args[ 3 ];
  2175. cpx1 = args[ 0 ];
  2176. cpy1 = args[ 1 ];
  2177. if ( points.length > 0 ) {
  2178. laste = points[ points.length - 1 ];
  2179. cpx0 = laste.x;
  2180. cpy0 = laste.y;
  2181. } else {
  2182. laste = this.actions[ i - 1 ].args;
  2183. cpx0 = laste[ laste.length - 2 ];
  2184. cpy0 = laste[ laste.length - 1 ];
  2185. }
  2186. for ( j = 1; j <= divisions; j ++ ) {
  2187. t = j / divisions;
  2188. tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  2189. ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  2190. points.push( new THREE.Vector2( tx, ty ) );
  2191. }
  2192. break;
  2193. case THREE.PathActions.BEZIER_CURVE_TO:
  2194. cpx = args[ 4 ];
  2195. cpy = args[ 5 ];
  2196. cpx1 = args[ 0 ];
  2197. cpy1 = args[ 1 ];
  2198. cpx2 = args[ 2 ];
  2199. cpy2 = args[ 3 ];
  2200. if ( points.length > 0 ) {
  2201. laste = points[ points.length - 1 ];
  2202. cpx0 = laste.x;
  2203. cpy0 = laste.y;
  2204. } else {
  2205. laste = this.actions[ i - 1 ].args;
  2206. cpx0 = laste[ laste.length - 2 ];
  2207. cpy0 = laste[ laste.length - 1 ];
  2208. }
  2209. for ( j = 1; j <= divisions; j ++ ) {
  2210. t = j / divisions;
  2211. tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  2212. ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  2213. points.push( new THREE.Vector2( tx, ty ) );
  2214. }
  2215. break;
  2216. case THREE.PathActions.CSPLINE_THRU:
  2217. laste = this.actions[ i - 1 ].args;
  2218. var last = new THREE.Vector2( laste[ laste.length - 2 ], laste[ laste.length - 1 ] );
  2219. var spts = [ last ];
  2220. var n = divisions * args[ 0 ].length;
  2221. spts = spts.concat( args[ 0 ] );
  2222. var spline = new THREE.SplineCurve( spts );
  2223. for ( j = 1; j <= n; j ++ ) {
  2224. points.push( spline.getPointAt( j / n ) ) ;
  2225. }
  2226. break;
  2227. case THREE.PathActions.ARC:
  2228. laste = this.actions[ i - 1 ].args;
  2229. var aX = args[ 0 ], aY = args[ 1 ],
  2230. aRadius = args[ 2 ],
  2231. aStartAngle = args[ 3 ], aEndAngle = args[ 4 ],
  2232. aClockwise = !!args[ 5 ];
  2233. var deltaAngle = aEndAngle - aStartAngle;
  2234. var angle;
  2235. var tdivisions = divisions * 2;
  2236. for ( j = 1; j <= tdivisions; j ++ ) {
  2237. t = j / tdivisions;
  2238. if ( ! aClockwise ) {
  2239. t = 1 - t;
  2240. }
  2241. angle = aStartAngle + t * deltaAngle;
  2242. tx = aX + aRadius * Math.cos( angle );
  2243. ty = aY + aRadius * Math.sin( angle );
  2244. //console.log('t', t, 'angle', angle, 'tx', tx, 'ty', ty);
  2245. points.push( new THREE.Vector2( tx, ty ) );
  2246. }
  2247. //console.log(points);
  2248. break;
  2249. } // end switch
  2250. }
  2251. // Normalize to remove the closing point by default.
  2252. var lastPoint = points[ points.length - 1];
  2253. var EPSILON = 0.0000000001;
  2254. if ( Math.abs(lastPoint.x - points[ 0 ].x) < EPSILON &&
  2255. Math.abs(lastPoint.y - points[ 0 ].y) < EPSILON)
  2256. points.splice( points.length - 1, 1);
  2257. if ( closedPath ) {
  2258. points.push( points[ 0 ] );
  2259. }
  2260. return points;
  2261. };
  2262. // This was used for testing purposes. Should be removed soon.
  2263. THREE.Path.prototype.transform = function( path, segments ) {
  2264. var bounds = this.getBoundingBox();
  2265. var oldPts = this.getPoints( segments ); // getPoints getSpacedPoints
  2266. //console.log( path.cacheArcLengths() );
  2267. //path.getLengths(400);
  2268. //segments = 40;
  2269. return this.getWrapPoints( oldPts, path );
  2270. };
  2271. // Read http://www.tinaja.com/glib/nonlingr.pdf
  2272. // nonlinear transforms
  2273. THREE.Path.prototype.nltransform = function( a, b, c, d, e, f ) {
  2274. // a - horizontal size
  2275. // b - lean
  2276. // c - x offset
  2277. // d - vertical size
  2278. // e - climb
  2279. // f - y offset
  2280. var oldPts = this.getPoints();
  2281. var i, il, p, oldX, oldY;
  2282. for ( i = 0, il = oldPts.length; i < il; i ++ ) {
  2283. p = oldPts[i];
  2284. oldX = p.x;
  2285. oldY = p.y;
  2286. p.x = a * oldX + b * oldY + c;
  2287. p.y = d * oldY + e * oldX + f;
  2288. }
  2289. return oldPts;
  2290. };
  2291. // FUTURE Export JSON Format
  2292. /* Draws this path onto a 2d canvas easily */
  2293. THREE.Path.prototype.debug = function( canvas ) {
  2294. var bounds = this.getBoundingBox();
  2295. if ( !canvas ) {
  2296. canvas = document.createElement( "canvas" );
  2297. canvas.setAttribute( 'width', bounds.maxX + 100 );
  2298. canvas.setAttribute( 'height', bounds.maxY + 100 );
  2299. document.body.appendChild( canvas );
  2300. }
  2301. var ctx = canvas.getContext( "2d" );
  2302. ctx.fillStyle = "white";
  2303. ctx.fillRect( 0, 0, canvas.width, canvas.height );
  2304. ctx.strokeStyle = "black";
  2305. ctx.beginPath();
  2306. var i, il, item, action, args;
  2307. // Debug Path
  2308. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  2309. item = this.actions[ i ];
  2310. args = item.args;
  2311. action = item.action;
  2312. // Short hand for now
  2313. if ( action != THREE.PathActions.CSPLINE_THRU ) {
  2314. ctx[ action ].apply( ctx, args );
  2315. }
  2316. /*
  2317. switch ( action ) {
  2318. case THREE.PathActions.MOVE_TO:
  2319. ctx[ action ]( args[ 0 ], args[ 1 ] );
  2320. break;
  2321. case THREE.PathActions.LINE_TO:
  2322. ctx[ action ]( args[ 0 ], args[ 1 ] );
  2323. break;
  2324. case THREE.PathActions.QUADRATIC_CURVE_TO:
  2325. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ] );
  2326. break;
  2327. case THREE.PathActions.CUBIC_CURVE_TO:
  2328. ctx[ action ]( args[ 0 ], args[ 1 ], args[ 2 ], args[ 3 ], args[ 4 ], args[ 5 ] );
  2329. break;
  2330. }
  2331. */
  2332. }
  2333. ctx.stroke();
  2334. ctx.closePath();
  2335. // Debug Points
  2336. ctx.strokeStyle = "red";
  2337. /* TO CLEAN UP */
  2338. var p, points = this.getPoints();
  2339. for ( i = 0, il = points.length; i < il; i ++ ) {
  2340. p = points[ i ];
  2341. ctx.beginPath();
  2342. ctx.arc( p.x, p.y, 1.5, 0, Math.PI * 2, false );
  2343. ctx.stroke();
  2344. ctx.closePath();
  2345. }
  2346. };
  2347. // Breaks path into shapes
  2348. THREE.Path.prototype.toShapes = function() {
  2349. var i, il, item, action, args;
  2350. var subPaths = [], lastPath = new THREE.Path();
  2351. for ( i = 0, il = this.actions.length; i < il; i ++ ) {
  2352. item = this.actions[ i ];
  2353. args = item.args;
  2354. action = item.action;
  2355. if ( action == THREE.PathActions.MOVE_TO ) {
  2356. if ( lastPath.actions.length != 0 ) {
  2357. subPaths.push( lastPath );
  2358. lastPath = new THREE.Path();
  2359. }
  2360. }
  2361. lastPath[ action ].apply( lastPath, args );
  2362. }
  2363. if ( lastPath.actions.length != 0 ) {
  2364. subPaths.push( lastPath );
  2365. }
  2366. // console.log(subPaths);
  2367. if ( subPaths.length == 0 ) return [];
  2368. var tmpPath, tmpShape, shapes = [];
  2369. var holesFirst = !THREE.Shape.Utils.isClockWise( subPaths[ 0 ].getPoints() );
  2370. // console.log("Holes first", holesFirst);
  2371. if ( subPaths.length == 1) {
  2372. tmpPath = subPaths[0];
  2373. tmpShape = new THREE.Shape();
  2374. tmpShape.actions = tmpPath.actions;
  2375. tmpShape.curves = tmpPath.curves;
  2376. shapes.push( tmpShape );
  2377. return shapes;
  2378. };
  2379. if ( holesFirst ) {
  2380. tmpShape = new THREE.Shape();
  2381. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  2382. tmpPath = subPaths[ i ];
  2383. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  2384. tmpShape.actions = tmpPath.actions;
  2385. tmpShape.curves = tmpPath.curves;
  2386. shapes.push( tmpShape );
  2387. tmpShape = new THREE.Shape();
  2388. //console.log('cw', i);
  2389. } else {
  2390. tmpShape.holes.push( tmpPath );
  2391. //console.log('ccw', i);
  2392. }
  2393. }
  2394. } else {
  2395. // Shapes first
  2396. for ( i = 0, il = subPaths.length; i < il; i ++ ) {
  2397. tmpPath = subPaths[ i ];
  2398. if ( THREE.Shape.Utils.isClockWise( tmpPath.getPoints() ) ) {
  2399. if ( tmpShape ) shapes.push( tmpShape );
  2400. tmpShape = new THREE.Shape();
  2401. tmpShape.actions = tmpPath.actions;
  2402. tmpShape.curves = tmpPath.curves;
  2403. } else {
  2404. tmpShape.holes.push( tmpPath );
  2405. }
  2406. }
  2407. shapes.push( tmpShape );
  2408. }
  2409. //console.log("shape", shapes);
  2410. return shapes;
  2411. };
  2412. /**
  2413. * @author zz85 / http://www.lab4games.net/zz85/blog
  2414. * Defines a 2d shape plane using paths.
  2415. **/
  2416. // STEP 1 Create a path.
  2417. // STEP 2 Turn path into shape.
  2418. // STEP 3 ExtrudeGeometry takes in Shape/Shapes
  2419. // STEP 3a - Extract points from each shape, turn to vertices
  2420. // STEP 3b - Triangulate each shape, add faces.
  2421. THREE.Shape = function ( ) {
  2422. THREE.Path.apply( this, arguments );
  2423. this.holes = [];
  2424. };
  2425. THREE.Shape.prototype = new THREE.Path();
  2426. THREE.Shape.prototype.constructor = THREE.Path;
  2427. // Convenience method to return ExtrudeGeometry
  2428. THREE.Shape.prototype.extrude = function ( options ) {
  2429. var extruded = new THREE.ExtrudeGeometry( this, options );
  2430. return extruded;
  2431. };
  2432. // Get points of holes
  2433. THREE.Shape.prototype.getPointsHoles = function ( divisions ) {
  2434. var i, il = this.holes.length, holesPts = [];
  2435. for ( i = 0; i < il; i ++ ) {
  2436. holesPts[ i ] = this.holes[ i ].getTransformedPoints( divisions, this.bends );
  2437. }
  2438. return holesPts;
  2439. };
  2440. // Get points of holes (spaced by regular distance)
  2441. THREE.Shape.prototype.getSpacedPointsHoles = function ( divisions ) {
  2442. var i, il = this.holes.length, holesPts = [];
  2443. for ( i = 0; i < il; i ++ ) {
  2444. holesPts[ i ] = this.holes[ i ].getTransformedSpacedPoints( divisions, this.bends );
  2445. }
  2446. return holesPts;
  2447. };
  2448. // Get points of shape and holes (keypoints based on segments parameter)
  2449. THREE.Shape.prototype.extractAllPoints = function ( divisions ) {
  2450. return {
  2451. shape: this.getTransformedPoints( divisions ),
  2452. holes: this.getPointsHoles( divisions )
  2453. };
  2454. };
  2455. THREE.Shape.prototype.extractPoints = function ( divisions ) {
  2456. if (this.useSpacedPoints) {
  2457. return this.extractAllSpacedPoints(divisions);
  2458. }
  2459. return this.extractAllPoints(divisions);
  2460. };
  2461. //
  2462. // THREE.Shape.prototype.extractAllPointsWithBend = function ( divisions, bend ) {
  2463. //
  2464. // return {
  2465. //
  2466. // shape: this.transform( bend, divisions ),
  2467. // holes: this.getPointsHoles( divisions, bend )
  2468. //
  2469. // };
  2470. //
  2471. // };
  2472. // Get points of shape and holes (spaced by regular distance)
  2473. THREE.Shape.prototype.extractAllSpacedPoints = function ( divisions ) {
  2474. return {
  2475. shape: this.getTransformedSpacedPoints( divisions ),
  2476. holes: this.getSpacedPointsHoles( divisions )
  2477. };
  2478. };
  2479. /**************************************************************
  2480. * Utils
  2481. **************************************************************/
  2482. THREE.Shape.Utils = {
  2483. /*
  2484. contour - array of vector2 for contour
  2485. holes - array of array of vector2
  2486. */
  2487. removeHoles: function ( contour, holes ) {
  2488. var shape = contour.concat(); // work on this shape
  2489. var allpoints = shape.concat();
  2490. /* For each isolated shape, find the closest points and break to the hole to allow triangulation */
  2491. var prevShapeVert, nextShapeVert,
  2492. prevHoleVert, nextHoleVert,
  2493. holeIndex, shapeIndex,
  2494. shapeId, shapeGroup,
  2495. h, h2,
  2496. hole, shortest, d,
  2497. p, pts1, pts2,
  2498. tmpShape1, tmpShape2,
  2499. tmpHole1, tmpHole2,
  2500. verts = [];
  2501. for ( h = 0; h < holes.length; h ++ ) {
  2502. hole = holes[ h ];
  2503. /*
  2504. shapeholes[ h ].concat(); // preserves original
  2505. holes.push( hole );
  2506. */
  2507. Array.prototype.push.apply( allpoints, hole );
  2508. shortest = Number.POSITIVE_INFINITY;
  2509. // Find the shortest pair of pts between shape and hole
  2510. // Note: Actually, I'm not sure now if we could optimize this to be faster than O(m*n)
  2511. // Using distanceToSquared() intead of distanceTo() should speed a little
  2512. // since running square roots operations are reduced.
  2513. for ( h2 = 0; h2 < hole.length; h2 ++ ) {
  2514. pts1 = hole[ h2 ];
  2515. var dist = [];
  2516. for ( p = 0; p < shape.length; p++ ) {
  2517. pts2 = shape[ p ];
  2518. d = pts1.distanceToSquared( pts2 );
  2519. dist.push( d );
  2520. if ( d < shortest ) {
  2521. shortest = d;
  2522. holeIndex = h2;
  2523. shapeIndex = p;
  2524. }
  2525. }
  2526. }
  2527. //console.log("shortest", shortest, dist);
  2528. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  2529. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  2530. var areaapts = [
  2531. hole[ holeIndex ],
  2532. shape[ shapeIndex ],
  2533. shape[ prevShapeVert ]
  2534. ];
  2535. var areaa = THREE.FontUtils.Triangulate.area( areaapts );
  2536. var areabpts = [
  2537. hole[ holeIndex ],
  2538. hole[ prevHoleVert ],
  2539. shape[ shapeIndex ]
  2540. ];
  2541. var areab = THREE.FontUtils.Triangulate.area( areabpts );
  2542. var shapeOffset = 1;
  2543. var holeOffset = -1;
  2544. var oldShapeIndex = shapeIndex, oldHoleIndex = holeIndex;
  2545. shapeIndex += shapeOffset;
  2546. holeIndex += holeOffset;
  2547. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  2548. shapeIndex %= shape.length;
  2549. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  2550. holeIndex %= hole.length;
  2551. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  2552. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  2553. areaapts = [
  2554. hole[ holeIndex ],
  2555. shape[ shapeIndex ],
  2556. shape[ prevShapeVert ]
  2557. ];
  2558. var areaa2 = THREE.FontUtils.Triangulate.area( areaapts );
  2559. areabpts = [
  2560. hole[ holeIndex ],
  2561. hole[ prevHoleVert ],
  2562. shape[ shapeIndex ]
  2563. ];
  2564. var areab2 = THREE.FontUtils.Triangulate.area( areabpts );
  2565. //console.log(areaa,areab ,areaa2,areab2, ( areaa + areab ), ( areaa2 + areab2 ));
  2566. if ( ( areaa + areab ) > ( areaa2 + areab2 ) ) {
  2567. // In case areas are not correct.
  2568. //console.log("USE THIS");
  2569. shapeIndex = oldShapeIndex;
  2570. holeIndex = oldHoleIndex ;
  2571. if ( shapeIndex < 0 ) { shapeIndex += shape.length; }
  2572. shapeIndex %= shape.length;
  2573. if ( holeIndex < 0 ) { holeIndex += hole.length; }
  2574. holeIndex %= hole.length;
  2575. prevShapeVert = ( shapeIndex - 1 ) >= 0 ? shapeIndex - 1 : shape.length - 1;
  2576. prevHoleVert = ( holeIndex - 1 ) >= 0 ? holeIndex - 1 : hole.length - 1;
  2577. } else {
  2578. //console.log("USE THAT ")
  2579. }
  2580. tmpShape1 = shape.slice( 0, shapeIndex );
  2581. tmpShape2 = shape.slice( shapeIndex );
  2582. tmpHole1 = hole.slice( holeIndex );
  2583. tmpHole2 = hole.slice( 0, holeIndex );
  2584. // Should check orders here again?
  2585. var trianglea = [
  2586. hole[ holeIndex ],
  2587. shape[ shapeIndex ],
  2588. shape[ prevShapeVert ]
  2589. ];
  2590. var triangleb = [
  2591. hole[ holeIndex ] ,
  2592. hole[ prevHoleVert ],
  2593. shape[ shapeIndex ]
  2594. ];
  2595. verts.push( trianglea );
  2596. verts.push( triangleb );
  2597. shape = tmpShape1.concat( tmpHole1 ).concat( tmpHole2 ).concat( tmpShape2 );
  2598. }
  2599. return {
  2600. shape:shape, /* shape with no holes */
  2601. isolatedPts: verts, /* isolated faces */
  2602. allpoints: allpoints
  2603. }
  2604. },
  2605. triangulateShape: function ( contour, holes ) {
  2606. var shapeWithoutHoles = THREE.Shape.Utils.removeHoles( contour, holes );
  2607. var shape = shapeWithoutHoles.shape,
  2608. allpoints = shapeWithoutHoles.allpoints,
  2609. isolatedPts = shapeWithoutHoles.isolatedPts;
  2610. var triangles = THREE.FontUtils.Triangulate( shape, false ); // True returns indices for points of spooled shape
  2611. // 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.
  2612. //console.log( "triangles",triangles, triangles.length );
  2613. //console.log( "allpoints",allpoints, allpoints.length );
  2614. var i, il, f, face,
  2615. key, index,
  2616. allPointsMap = {},
  2617. isolatedPointsMap = {};
  2618. // prepare all points map
  2619. for ( i = 0, il = allpoints.length; i < il; i ++ ) {
  2620. key = allpoints[ i ].x + ":" + allpoints[ i ].y;
  2621. if ( allPointsMap[ key ] !== undefined ) {
  2622. console.log( "Duplicate point", key );
  2623. }
  2624. allPointsMap[ key ] = i;
  2625. }
  2626. // check all face vertices against all points map
  2627. for ( i = 0, il = triangles.length; i < il; i ++ ) {
  2628. face = triangles[ i ];
  2629. for ( f = 0; f < 3; f ++ ) {
  2630. key = face[ f ].x + ":" + face[ f ].y;
  2631. index = allPointsMap[ key ];
  2632. if ( index !== undefined ) {
  2633. face[ f ] = index;
  2634. }
  2635. }
  2636. }
  2637. // check isolated points vertices against all points map
  2638. for ( i = 0, il = isolatedPts.length; i < il; i ++ ) {
  2639. face = isolatedPts[ i ];
  2640. for ( f = 0; f < 3; f ++ ) {
  2641. key = face[ f ].x + ":" + face[ f ].y;
  2642. index = allPointsMap[ key ];
  2643. if ( index !== undefined ) {
  2644. face[ f ] = index;
  2645. }
  2646. }
  2647. }
  2648. return triangles.concat( isolatedPts );
  2649. }, // end triangulate shapes
  2650. /*
  2651. triangulate2 : function( pts, holes ) {
  2652. // For use with Poly2Tri.js
  2653. var allpts = pts.concat();
  2654. var shape = [];
  2655. for (var p in pts) {
  2656. shape.push(new js.poly2tri.Point(pts[p].x, pts[p].y));
  2657. }
  2658. var swctx = new js.poly2tri.SweepContext(shape);
  2659. for (var h in holes) {
  2660. var aHole = holes[h];
  2661. var newHole = []
  2662. for (i in aHole) {
  2663. newHole.push(new js.poly2tri.Point(aHole[i].x, aHole[i].y));
  2664. allpts.push(aHole[i]);
  2665. }
  2666. swctx.AddHole(newHole);
  2667. }
  2668. var find;
  2669. var findIndexForPt = function (pt) {
  2670. find = new THREE.Vector2(pt.x, pt.y);
  2671. var p;
  2672. for (p=0, pl = allpts.length; p<pl; p++) {
  2673. if (allpts[p].equals(find)) return p;
  2674. }
  2675. return -1;
  2676. };
  2677. // triangulate
  2678. js.poly2tri.sweep.Triangulate(swctx);
  2679. var triangles = swctx.GetTriangles();
  2680. var tr ;
  2681. var facesPts = [];
  2682. for (var t in triangles) {
  2683. tr = triangles[t];
  2684. facesPts.push([
  2685. findIndexForPt(tr.GetPoint(0)),
  2686. findIndexForPt(tr.GetPoint(1)),
  2687. findIndexForPt(tr.GetPoint(2))
  2688. ]);
  2689. }
  2690. // console.log(facesPts);
  2691. // console.log("triangles", triangles.length, triangles);
  2692. // Returns array of faces with 3 element each
  2693. return facesPts;
  2694. },
  2695. */
  2696. isClockWise: function ( pts ) {
  2697. return THREE.FontUtils.Triangulate.area( pts ) < 0;
  2698. },
  2699. // Bezier Curves formulas obtained from
  2700. // http://en.wikipedia.org/wiki/B%C3%A9zier_curve
  2701. // Quad Bezier Functions
  2702. b2p0: function ( t, p ) {
  2703. var k = 1 - t;
  2704. return k * k * p;
  2705. },
  2706. b2p1: function ( t, p ) {
  2707. return 2 * ( 1 - t ) * t * p;
  2708. },
  2709. b2p2: function ( t, p ) {
  2710. return t * t * p;
  2711. },
  2712. b2: function ( t, p0, p1, p2 ) {
  2713. return this.b2p0( t, p0 ) + this.b2p1( t, p1 ) + this.b2p2( t, p2 );
  2714. },
  2715. // Cubic Bezier Functions
  2716. b3p0: function ( t, p ) {
  2717. var k = 1 - t;
  2718. return k * k * k * p;
  2719. },
  2720. b3p1: function ( t, p ) {
  2721. var k = 1 - t;
  2722. return 3 * k * k * t * p;
  2723. },
  2724. b3p2: function ( t, p ) {
  2725. var k = 1 - t;
  2726. return 3 * k * t * t * p;
  2727. },
  2728. b3p3: function ( t, p ) {
  2729. return t * t * t * p;
  2730. },
  2731. b3: function ( t, p0, p1, p2, p3 ) {
  2732. return this.b3p0( t, p0 ) + this.b3p1( t, p1 ) + this.b3p2( t, p2 ) + this.b3p3( t, p3 );
  2733. }
  2734. };
  2735. /**
  2736. * @author zz85 / http://www.lab4games.net/zz85/blog
  2737. *
  2738. * TextPath
  2739. *
  2740. **/
  2741. THREE.TextPath = function ( text, parameters ) {
  2742. THREE.Path.call( this );
  2743. this.parameters = parameters || {};
  2744. this.set( text );
  2745. };
  2746. THREE.TextPath.prototype.set = function ( text, parameters ) {
  2747. parameters = parameters || this.parameters;
  2748. this.text = text;
  2749. var size = parameters.size !== undefined ? parameters.size : 100;
  2750. var curveSegments = parameters.curveSegments !== undefined ? parameters.curveSegments: 4;
  2751. var font = parameters.font !== undefined ? parameters.font : "helvetiker";
  2752. var weight = parameters.weight !== undefined ? parameters.weight : "normal";
  2753. var style = parameters.style !== undefined ? parameters.style : "normal";
  2754. THREE.FontUtils.size = size;
  2755. THREE.FontUtils.divisions = curveSegments;
  2756. THREE.FontUtils.face = font;
  2757. THREE.FontUtils.weight = weight;
  2758. THREE.FontUtils.style = style;
  2759. };
  2760. THREE.TextPath.prototype.toShapes = function () {
  2761. // Get a Font data json object
  2762. var data = THREE.FontUtils.drawText( this.text );
  2763. var paths = data.paths;
  2764. var shapes = [];
  2765. for ( var p = 0, pl = paths.length; p < pl; p ++ ) {
  2766. Array.prototype.push.apply( shapes, paths[ p ].toShapes() );
  2767. }
  2768. return shapes;
  2769. //console.log(path);
  2770. //console.log(fontShapes);
  2771. // Either find actions or curves.
  2772. //var text3d = new THREE.ExtrudeGeometry( shapes , { amount: 20, bevelEnabled:true, bevelThickness:3 } );
  2773. //return text3d;
  2774. };
  2775. /**
  2776. * @author mikael emtinger / http://gomo.se/
  2777. */
  2778. THREE.AnimationHandler = (function() {
  2779. var playing = [];
  2780. var library = {};
  2781. var that = {};
  2782. //--- update ---
  2783. that.update = function( deltaTimeMS ) {
  2784. for( var i = 0; i < playing.length; i++ )
  2785. playing[ i ].update( deltaTimeMS );
  2786. };
  2787. //--- add ---
  2788. that.addToUpdate = function( animation ) {
  2789. if( playing.indexOf( animation ) === -1 )
  2790. playing.push( animation );
  2791. };
  2792. //--- remove ---
  2793. that.removeFromUpdate = function( animation ) {
  2794. var index = playing.indexOf( animation );
  2795. if( index !== -1 )
  2796. playing.splice( index, 1 );
  2797. };
  2798. //--- add ---
  2799. that.add = function( data ) {
  2800. if( library[ data.name ] !== undefined )
  2801. console.log( "THREE.AnimationHandler.add: Warning! " + data.name + " already exists in library. Overwriting." );
  2802. library[ data.name ] = data;
  2803. initData( data );
  2804. };
  2805. //--- get ---
  2806. that.get = function( name ) {
  2807. if( typeof name === "string" ) {
  2808. if( library[ name ] ) {
  2809. return library[ name ];
  2810. } else {
  2811. console.log( "THREE.AnimationHandler.get: Couldn't find animation " + name );
  2812. return null;
  2813. }
  2814. } else {
  2815. // todo: add simple tween library
  2816. }
  2817. };
  2818. //--- parse ---
  2819. that.parse = function( root ) {
  2820. // setup hierarchy
  2821. var hierarchy = [];
  2822. if ( root instanceof THREE.SkinnedMesh ) {
  2823. for( var b = 0; b < root.bones.length; b++ ) {
  2824. hierarchy.push( root.bones[ b ] );
  2825. }
  2826. } else {
  2827. parseRecurseHierarchy( root, hierarchy );
  2828. }
  2829. return hierarchy;
  2830. };
  2831. var parseRecurseHierarchy = function( root, hierarchy ) {
  2832. hierarchy.push( root );
  2833. for( var c = 0; c < root.children.length; c++ )
  2834. parseRecurseHierarchy( root.children[ c ], hierarchy );
  2835. }
  2836. //--- init data ---
  2837. var initData = function( data ) {
  2838. if( data.initialized === true )
  2839. return;
  2840. // loop through all keys
  2841. for( var h = 0; h < data.hierarchy.length; h ++ ) {
  2842. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2843. // remove minus times
  2844. if( data.hierarchy[ h ].keys[ k ].time < 0 )
  2845. data.hierarchy[ h ].keys[ k ].time = 0;
  2846. // create quaternions
  2847. if( data.hierarchy[ h ].keys[ k ].rot !== undefined &&
  2848. !( data.hierarchy[ h ].keys[ k ].rot instanceof THREE.Quaternion ) ) {
  2849. var quat = data.hierarchy[ h ].keys[ k ].rot;
  2850. data.hierarchy[ h ].keys[ k ].rot = new THREE.Quaternion( quat[0], quat[1], quat[2], quat[3] );
  2851. }
  2852. }
  2853. // prepare morph target keys
  2854. if( data.hierarchy[h].keys.length && data.hierarchy[ h ].keys[ 0 ].morphTargets !== undefined ) {
  2855. // get all used
  2856. var usedMorphTargets = {};
  2857. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2858. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  2859. var morphTargetName = data.hierarchy[ h ].keys[ k ].morphTargets[ m ];
  2860. usedMorphTargets[ morphTargetName ] = -1;
  2861. }
  2862. }
  2863. data.hierarchy[ h ].usedMorphTargets = usedMorphTargets;
  2864. // set all used on all frames
  2865. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2866. var influences = {};
  2867. for( var morphTargetName in usedMorphTargets ) {
  2868. for( var m = 0; m < data.hierarchy[ h ].keys[ k ].morphTargets.length; m ++ ) {
  2869. if( data.hierarchy[ h ].keys[ k ].morphTargets[ m ] === morphTargetName ) {
  2870. influences[ morphTargetName ] = data.hierarchy[ h ].keys[ k ].morphTargetsInfluences[ m ];
  2871. break;
  2872. }
  2873. }
  2874. if( m === data.hierarchy[ h ].keys[ k ].morphTargets.length ) {
  2875. influences[ morphTargetName ] = 0;
  2876. }
  2877. }
  2878. data.hierarchy[ h ].keys[ k ].morphTargetsInfluences = influences;
  2879. }
  2880. }
  2881. // remove all keys that are on the same time
  2882. for( var k = 1; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2883. if( data.hierarchy[ h ].keys[ k ].time === data.hierarchy[ h ].keys[ k - 1 ].time ) {
  2884. data.hierarchy[ h ].keys.splice( k, 1 );
  2885. k --;
  2886. }
  2887. }
  2888. // set index
  2889. for( var k = 0; k < data.hierarchy[ h ].keys.length; k ++ ) {
  2890. data.hierarchy[ h ].keys[ k ].index = k;
  2891. }
  2892. }
  2893. // JIT
  2894. var lengthInFrames = parseInt( data.length * data.fps, 10 );
  2895. data.JIT = {};
  2896. data.JIT.hierarchy = [];
  2897. for( var h = 0; h < data.hierarchy.length; h ++ )
  2898. data.JIT.hierarchy.push( new Array( lengthInFrames ) );
  2899. // done
  2900. data.initialized = true;
  2901. };
  2902. // interpolation types
  2903. that.LINEAR = 0;
  2904. that.CATMULLROM = 1;
  2905. that.CATMULLROM_FORWARD = 2;
  2906. return that;
  2907. }());
  2908. /**
  2909. * @author mikael emtinger / http://gomo.se/
  2910. * @author mrdoob / http://mrdoob.com/
  2911. * @author alteredq / http://alteredqualia.com/
  2912. */
  2913. THREE.Animation = function( root, data, interpolationType, JITCompile ) {
  2914. this.root = root;
  2915. this.data = THREE.AnimationHandler.get( data );
  2916. this.hierarchy = THREE.AnimationHandler.parse( root );
  2917. this.currentTime = 0;
  2918. this.timeScale = 1;
  2919. this.isPlaying = false;
  2920. this.isPaused = true;
  2921. this.loop = true;
  2922. this.interpolationType = interpolationType !== undefined ? interpolationType : THREE.AnimationHandler.LINEAR;
  2923. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  2924. this.points = [];
  2925. this.target = new THREE.Vector3();
  2926. };
  2927. // Play
  2928. THREE.Animation.prototype.play = function( loop, startTimeMS ) {
  2929. if( !this.isPlaying ) {
  2930. this.isPlaying = true;
  2931. this.loop = loop !== undefined ? loop : true;
  2932. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  2933. // reset key cache
  2934. var h, hl = this.hierarchy.length,
  2935. object;
  2936. for ( h = 0; h < hl; h++ ) {
  2937. object = this.hierarchy[ h ];
  2938. if ( this.interpolationType !== THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  2939. object.useQuaternion = true;
  2940. }
  2941. object.matrixAutoUpdate = true;
  2942. if ( object.animationCache === undefined ) {
  2943. object.animationCache = {};
  2944. object.animationCache.prevKey = { pos: 0, rot: 0, scl: 0 };
  2945. object.animationCache.nextKey = { pos: 0, rot: 0, scl: 0 };
  2946. object.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  2947. }
  2948. var prevKey = object.animationCache.prevKey;
  2949. var nextKey = object.animationCache.nextKey;
  2950. prevKey.pos = this.data.hierarchy[ h ].keys[ 0 ];
  2951. prevKey.rot = this.data.hierarchy[ h ].keys[ 0 ];
  2952. prevKey.scl = this.data.hierarchy[ h ].keys[ 0 ];
  2953. nextKey.pos = this.getNextKeyWith( "pos", h, 1 );
  2954. nextKey.rot = this.getNextKeyWith( "rot", h, 1 );
  2955. nextKey.scl = this.getNextKeyWith( "scl", h, 1 );
  2956. }
  2957. this.update( 0 );
  2958. }
  2959. this.isPaused = false;
  2960. THREE.AnimationHandler.addToUpdate( this );
  2961. };
  2962. // Pause
  2963. THREE.Animation.prototype.pause = function() {
  2964. if( this.isPaused ) {
  2965. THREE.AnimationHandler.addToUpdate( this );
  2966. } else {
  2967. THREE.AnimationHandler.removeFromUpdate( this );
  2968. }
  2969. this.isPaused = !this.isPaused;
  2970. };
  2971. // Stop
  2972. THREE.Animation.prototype.stop = function() {
  2973. this.isPlaying = false;
  2974. this.isPaused = false;
  2975. THREE.AnimationHandler.removeFromUpdate( this );
  2976. // reset JIT matrix and remove cache
  2977. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  2978. if ( this.hierarchy[ h ].animationCache !== undefined ) {
  2979. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  2980. this.hierarchy[ h ].skinMatrix = this.hierarchy[ h ].animationCache.originalMatrix;
  2981. } else {
  2982. this.hierarchy[ h ].matrix = this.hierarchy[ h ].animationCache.originalMatrix;
  2983. }
  2984. delete this.hierarchy[ h ].animationCache;
  2985. }
  2986. }
  2987. };
  2988. // Update
  2989. THREE.Animation.prototype.update = function( deltaTimeMS ) {
  2990. // early out
  2991. if( !this.isPlaying ) return;
  2992. // vars
  2993. var types = [ "pos", "rot", "scl" ];
  2994. var type;
  2995. var scale;
  2996. var vector;
  2997. var prevXYZ, nextXYZ;
  2998. var prevKey, nextKey;
  2999. var object;
  3000. var animationCache;
  3001. var frame;
  3002. var JIThierarchy = this.data.JIT.hierarchy;
  3003. var currentTime, unloopedCurrentTime;
  3004. var currentPoint, forwardPoint, angle;
  3005. // update
  3006. this.currentTime += deltaTimeMS * this.timeScale;
  3007. unloopedCurrentTime = this.currentTime;
  3008. currentTime = this.currentTime = this.currentTime % this.data.length;
  3009. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  3010. // update
  3011. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3012. object = this.hierarchy[ h ];
  3013. animationCache = object.animationCache;
  3014. // use JIT?
  3015. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  3016. if( object instanceof THREE.Bone ) {
  3017. object.skinMatrix = JIThierarchy[ h ][ frame ];
  3018. object.matrixAutoUpdate = false;
  3019. object.matrixWorldNeedsUpdate = false;
  3020. } else {
  3021. object.matrix = JIThierarchy[ h ][ frame ];
  3022. object.matrixAutoUpdate = false;
  3023. object.matrixWorldNeedsUpdate = true;
  3024. }
  3025. // use interpolation
  3026. } else {
  3027. // make sure so original matrix and not JIT matrix is set
  3028. if ( this.JITCompile ) {
  3029. if( object instanceof THREE.Bone ) {
  3030. object.skinMatrix = object.animationCache.originalMatrix;
  3031. } else {
  3032. object.matrix = object.animationCache.originalMatrix;
  3033. }
  3034. }
  3035. // loop through pos/rot/scl
  3036. for ( var t = 0; t < 3; t++ ) {
  3037. // get keys
  3038. type = types[ t ];
  3039. prevKey = animationCache.prevKey[ type ];
  3040. nextKey = animationCache.nextKey[ type ];
  3041. // switch keys?
  3042. if ( nextKey.time <= unloopedCurrentTime ) {
  3043. // did we loop?
  3044. if ( currentTime < unloopedCurrentTime ) {
  3045. if ( this.loop ) {
  3046. prevKey = this.data.hierarchy[ h ].keys[ 0 ];
  3047. nextKey = this.getNextKeyWith( type, h, 1 );
  3048. while( nextKey.time < currentTime ) {
  3049. prevKey = nextKey;
  3050. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  3051. }
  3052. } else {
  3053. this.stop();
  3054. return;
  3055. }
  3056. } else {
  3057. do {
  3058. prevKey = nextKey;
  3059. nextKey = this.getNextKeyWith( type, h, nextKey.index + 1 );
  3060. } while( nextKey.time < currentTime )
  3061. }
  3062. animationCache.prevKey[ type ] = prevKey;
  3063. animationCache.nextKey[ type ] = nextKey;
  3064. }
  3065. object.matrixAutoUpdate = true;
  3066. object.matrixWorldNeedsUpdate = true;
  3067. scale = ( currentTime - prevKey.time ) / ( nextKey.time - prevKey.time );
  3068. prevXYZ = prevKey[ type ];
  3069. nextXYZ = nextKey[ type ];
  3070. // check scale error
  3071. if ( scale < 0 || scale > 1 ) {
  3072. console.log( "THREE.Animation.update: Warning! Scale out of bounds:" + scale + " on bone " + h );
  3073. scale = scale < 0 ? 0 : 1;
  3074. }
  3075. // interpolate
  3076. if ( type === "pos" ) {
  3077. vector = object.position;
  3078. if( this.interpolationType === THREE.AnimationHandler.LINEAR ) {
  3079. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  3080. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  3081. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  3082. } else if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  3083. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3084. this.points[ 0 ] = this.getPrevKeyWith( "pos", h, prevKey.index - 1 )[ "pos" ];
  3085. this.points[ 1 ] = prevXYZ;
  3086. this.points[ 2 ] = nextXYZ;
  3087. this.points[ 3 ] = this.getNextKeyWith( "pos", h, nextKey.index + 1 )[ "pos" ];
  3088. scale = scale * 0.33 + 0.33;
  3089. currentPoint = this.interpolateCatmullRom( this.points, scale );
  3090. vector.x = currentPoint[ 0 ];
  3091. vector.y = currentPoint[ 1 ];
  3092. vector.z = currentPoint[ 2 ];
  3093. if( this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3094. forwardPoint = this.interpolateCatmullRom( this.points, scale * 1.01 );
  3095. this.target.set( forwardPoint[ 0 ], forwardPoint[ 1 ], forwardPoint[ 2 ] );
  3096. this.target.subSelf( vector );
  3097. this.target.y = 0;
  3098. this.target.normalize();
  3099. angle = Math.atan2( this.target.x, this.target.z );
  3100. object.rotation.set( 0, angle, 0 );
  3101. }
  3102. }
  3103. } else if ( type === "rot" ) {
  3104. THREE.Quaternion.slerp( prevXYZ, nextXYZ, object.quaternion, scale );
  3105. } else if( type === "scl" ) {
  3106. vector = object.scale;
  3107. vector.x = prevXYZ[ 0 ] + ( nextXYZ[ 0 ] - prevXYZ[ 0 ] ) * scale;
  3108. vector.y = prevXYZ[ 1 ] + ( nextXYZ[ 1 ] - prevXYZ[ 1 ] ) * scale;
  3109. vector.z = prevXYZ[ 2 ] + ( nextXYZ[ 2 ] - prevXYZ[ 2 ] ) * scale;
  3110. }
  3111. }
  3112. }
  3113. }
  3114. // update JIT?
  3115. if ( this.JITCompile ) {
  3116. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  3117. this.hierarchy[ 0 ].updateMatrixWorld( true );
  3118. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  3119. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  3120. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  3121. } else {
  3122. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  3123. }
  3124. }
  3125. }
  3126. }
  3127. };
  3128. // Catmull-Rom spline
  3129. THREE.Animation.prototype.interpolateCatmullRom = function ( points, scale ) {
  3130. var c = [], v3 = [],
  3131. point, intPoint, weight, w2, w3,
  3132. pa, pb, pc, pd;
  3133. point = ( points.length - 1 ) * scale;
  3134. intPoint = Math.floor( point );
  3135. weight = point - intPoint;
  3136. c[ 0 ] = intPoint === 0 ? intPoint : intPoint - 1;
  3137. c[ 1 ] = intPoint;
  3138. c[ 2 ] = intPoint > points.length - 2 ? intPoint : intPoint + 1;
  3139. c[ 3 ] = intPoint > points.length - 3 ? intPoint : intPoint + 2;
  3140. pa = points[ c[ 0 ] ];
  3141. pb = points[ c[ 1 ] ];
  3142. pc = points[ c[ 2 ] ];
  3143. pd = points[ c[ 3 ] ];
  3144. w2 = weight * weight;
  3145. w3 = weight * w2;
  3146. v3[ 0 ] = this.interpolate( pa[ 0 ], pb[ 0 ], pc[ 0 ], pd[ 0 ], weight, w2, w3 );
  3147. v3[ 1 ] = this.interpolate( pa[ 1 ], pb[ 1 ], pc[ 1 ], pd[ 1 ], weight, w2, w3 );
  3148. v3[ 2 ] = this.interpolate( pa[ 2 ], pb[ 2 ], pc[ 2 ], pd[ 2 ], weight, w2, w3 );
  3149. return v3;
  3150. };
  3151. THREE.Animation.prototype.interpolate = function( p0, p1, p2, p3, t, t2, t3 ) {
  3152. var v0 = ( p2 - p0 ) * 0.5,
  3153. v1 = ( p3 - p1 ) * 0.5;
  3154. return ( 2 * ( p1 - p2 ) + v0 + v1 ) * t3 + ( - 3 * ( p1 - p2 ) - 2 * v0 - v1 ) * t2 + v0 * t + p1;
  3155. };
  3156. // Get next key with
  3157. THREE.Animation.prototype.getNextKeyWith = function( type, h, key ) {
  3158. var keys = this.data.hierarchy[ h ].keys;
  3159. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  3160. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3161. key = key < keys.length - 1 ? key : keys.length - 1;
  3162. } else {
  3163. key = key % keys.length;
  3164. }
  3165. for ( ; key < keys.length; key++ ) {
  3166. if ( keys[ key ][ type ] !== undefined ) {
  3167. return keys[ key ];
  3168. }
  3169. }
  3170. return this.data.hierarchy[ h ].keys[ 0 ];
  3171. };
  3172. // Get previous key with
  3173. THREE.Animation.prototype.getPrevKeyWith = function( type, h, key ) {
  3174. var keys = this.data.hierarchy[ h ].keys;
  3175. if ( this.interpolationType === THREE.AnimationHandler.CATMULLROM ||
  3176. this.interpolationType === THREE.AnimationHandler.CATMULLROM_FORWARD ) {
  3177. key = key > 0 ? key : 0;
  3178. } else {
  3179. key = key >= 0 ? key : key + keys.length;
  3180. }
  3181. for ( ; key >= 0; key-- ) {
  3182. if ( keys[ key ][ type ] !== undefined ) {
  3183. return keys[ key ];
  3184. }
  3185. }
  3186. return this.data.hierarchy[ h ].keys[ keys.length - 1 ];
  3187. };/**
  3188. * @author mikael emtinger / http://gomo.se/
  3189. * @author mrdoob / http://mrdoob.com/
  3190. * @author alteredq / http://alteredqualia.com/
  3191. * @author khang duong
  3192. * @author erik kitson
  3193. */
  3194. THREE.KeyFrameAnimation = function( root, data, JITCompile ) {
  3195. this.root = root;
  3196. this.data = THREE.AnimationHandler.get( data );
  3197. this.hierarchy = THREE.AnimationHandler.parse( root );
  3198. this.currentTime = 0;
  3199. this.timeScale = 0.001;
  3200. this.isPlaying = false;
  3201. this.isPaused = true;
  3202. this.loop = true;
  3203. this.JITCompile = JITCompile !== undefined ? JITCompile : true;
  3204. // initialize to first keyframes
  3205. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3206. var keys = this.data.hierarchy[h].keys,
  3207. sids = this.data.hierarchy[h].sids,
  3208. obj = this.hierarchy[h];
  3209. if ( keys.length && sids ) {
  3210. for ( var s = 0; s < sids.length; s++ ) {
  3211. var sid = sids[ s ],
  3212. next = this.getNextKeyWith( sid, h, 0 );
  3213. if ( next ) {
  3214. next.apply( sid );
  3215. }
  3216. }
  3217. obj.matrixAutoUpdate = false;
  3218. this.data.hierarchy[h].node.updateMatrix();
  3219. obj.matrixWorldNeedsUpdate = true;
  3220. }
  3221. }
  3222. };
  3223. // Play
  3224. THREE.KeyFrameAnimation.prototype.play = function( loop, startTimeMS ) {
  3225. if( !this.isPlaying ) {
  3226. this.isPlaying = true;
  3227. this.loop = loop !== undefined ? loop : true;
  3228. this.currentTime = startTimeMS !== undefined ? startTimeMS : 0;
  3229. this.startTimeMs = startTimeMS;
  3230. this.startTime = 10000000;
  3231. this.endTime = -this.startTime;
  3232. // reset key cache
  3233. var h, hl = this.hierarchy.length,
  3234. object,
  3235. node;
  3236. for ( h = 0; h < hl; h++ ) {
  3237. object = this.hierarchy[ h ];
  3238. node = this.data.hierarchy[ h ];
  3239. object.useQuaternion = true;
  3240. if ( node.animationCache === undefined ) {
  3241. node.animationCache = {};
  3242. node.animationCache.prevKey = null;
  3243. node.animationCache.nextKey = null;
  3244. node.animationCache.originalMatrix = object instanceof THREE.Bone ? object.skinMatrix : object.matrix;
  3245. }
  3246. var keys = this.data.hierarchy[h].keys;
  3247. if (keys.length) {
  3248. node.animationCache.prevKey = keys[ 0 ];
  3249. node.animationCache.nextKey = keys[ 1 ];
  3250. this.startTime = Math.min( keys[0].time, this.startTime );
  3251. this.endTime = Math.max( keys[keys.length - 1].time, this.endTime );
  3252. }
  3253. }
  3254. this.update( 0 );
  3255. }
  3256. this.isPaused = false;
  3257. THREE.AnimationHandler.addToUpdate( this );
  3258. };
  3259. // Pause
  3260. THREE.KeyFrameAnimation.prototype.pause = function() {
  3261. if( this.isPaused ) {
  3262. THREE.AnimationHandler.addToUpdate( this );
  3263. } else {
  3264. THREE.AnimationHandler.removeFromUpdate( this );
  3265. }
  3266. this.isPaused = !this.isPaused;
  3267. };
  3268. // Stop
  3269. THREE.KeyFrameAnimation.prototype.stop = function() {
  3270. this.isPlaying = false;
  3271. this.isPaused = false;
  3272. THREE.AnimationHandler.removeFromUpdate( this );
  3273. // reset JIT matrix and remove cache
  3274. for ( var h = 0; h < this.data.hierarchy.length; h++ ) {
  3275. var obj = this.hierarchy[ h ];
  3276. var node = this.data.hierarchy[ h ];
  3277. if ( node.animationCache !== undefined ) {
  3278. var original = node.animationCache.originalMatrix;
  3279. if( obj instanceof THREE.Bone ) {
  3280. original.copy( obj.skinMatrix );
  3281. obj.skinMatrix = original;
  3282. } else {
  3283. original.copy( obj.matrix );
  3284. obj.matrix = original;
  3285. }
  3286. delete node.animationCache;
  3287. }
  3288. }
  3289. };
  3290. // Update
  3291. THREE.KeyFrameAnimation.prototype.update = function( deltaTimeMS ) {
  3292. // early out
  3293. if( !this.isPlaying ) return;
  3294. // vars
  3295. var prevKey, nextKey;
  3296. var object;
  3297. var node;
  3298. var frame;
  3299. var JIThierarchy = this.data.JIT.hierarchy;
  3300. var currentTime, unloopedCurrentTime;
  3301. var looped;
  3302. // update
  3303. this.currentTime += deltaTimeMS * this.timeScale;
  3304. unloopedCurrentTime = this.currentTime;
  3305. currentTime = this.currentTime = this.currentTime % this.data.length;
  3306. // if looped around, the current time should be based on the startTime
  3307. if ( currentTime < this.startTimeMs ) {
  3308. currentTime = this.currentTime = this.startTimeMs + currentTime;
  3309. }
  3310. frame = parseInt( Math.min( currentTime * this.data.fps, this.data.length * this.data.fps ), 10 );
  3311. looped = currentTime < unloopedCurrentTime;
  3312. if ( looped && !this.loop ) {
  3313. // Set the animation to the last keyframes and stop
  3314. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3315. var keys = this.data.hierarchy[h].keys,
  3316. sids = this.data.hierarchy[h].sids,
  3317. end = keys.length-1,
  3318. obj = this.hierarchy[h];
  3319. if ( keys.length ) {
  3320. for ( var s = 0; s < sids.length; s++ ) {
  3321. var sid = sids[ s ],
  3322. prev = this.getPrevKeyWith( sid, h, end );
  3323. if ( prev ) {
  3324. prev.apply( sid );
  3325. }
  3326. }
  3327. this.data.hierarchy[h].node.updateMatrix();
  3328. obj.matrixWorldNeedsUpdate = true;
  3329. }
  3330. }
  3331. this.stop();
  3332. return;
  3333. }
  3334. // check pre-infinity
  3335. if ( currentTime < this.startTime ) {
  3336. return;
  3337. }
  3338. // update
  3339. for ( var h = 0, hl = this.hierarchy.length; h < hl; h++ ) {
  3340. object = this.hierarchy[ h ];
  3341. node = this.data.hierarchy[ h ];
  3342. var keys = node.keys,
  3343. animationCache = node.animationCache;
  3344. // use JIT?
  3345. if ( this.JITCompile && JIThierarchy[ h ][ frame ] !== undefined ) {
  3346. if( object instanceof THREE.Bone ) {
  3347. object.skinMatrix = JIThierarchy[ h ][ frame ];
  3348. object.matrixWorldNeedsUpdate = false;
  3349. } else {
  3350. object.matrix = JIThierarchy[ h ][ frame ];
  3351. object.matrixWorldNeedsUpdate = true;
  3352. }
  3353. // use interpolation
  3354. } else if ( keys.length ) {
  3355. // make sure so original matrix and not JIT matrix is set
  3356. if ( this.JITCompile && animationCache ) {
  3357. if( object instanceof THREE.Bone ) {
  3358. object.skinMatrix = animationCache.originalMatrix;
  3359. } else {
  3360. object.matrix = animationCache.originalMatrix;
  3361. }
  3362. }
  3363. prevKey = animationCache.prevKey;
  3364. nextKey = animationCache.nextKey;
  3365. if ( prevKey && nextKey ) {
  3366. // switch keys?
  3367. if ( nextKey.time <= unloopedCurrentTime ) {
  3368. // did we loop?
  3369. if ( looped && this.loop ) {
  3370. prevKey = keys[ 0 ];
  3371. nextKey = keys[ 1 ];
  3372. while ( nextKey.time < currentTime ) {
  3373. prevKey = nextKey;
  3374. nextKey = keys[ prevKey.index + 1 ];
  3375. }
  3376. } else if ( !looped ) {
  3377. var lastIndex = keys.length - 1;
  3378. while ( nextKey.time < currentTime && nextKey.index !== lastIndex ) {
  3379. prevKey = nextKey;
  3380. nextKey = keys[ prevKey.index + 1 ];
  3381. }
  3382. }
  3383. animationCache.prevKey = prevKey;
  3384. animationCache.nextKey = nextKey;
  3385. }
  3386. if(nextKey.time >= currentTime)
  3387. prevKey.interpolate( nextKey, currentTime );
  3388. else
  3389. prevKey.interpolate( nextKey, nextKey.time);
  3390. }
  3391. this.data.hierarchy[h].node.updateMatrix();
  3392. object.matrixWorldNeedsUpdate = true;
  3393. }
  3394. }
  3395. // update JIT?
  3396. if ( this.JITCompile ) {
  3397. if ( JIThierarchy[ 0 ][ frame ] === undefined ) {
  3398. this.hierarchy[ 0 ].updateMatrixWorld( true );
  3399. for ( var h = 0; h < this.hierarchy.length; h++ ) {
  3400. if( this.hierarchy[ h ] instanceof THREE.Bone ) {
  3401. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].skinMatrix.clone();
  3402. } else {
  3403. JIThierarchy[ h ][ frame ] = this.hierarchy[ h ].matrix.clone();
  3404. }
  3405. }
  3406. }
  3407. }
  3408. };
  3409. // Get next key with
  3410. THREE.KeyFrameAnimation.prototype.getNextKeyWith = function( sid, h, key ) {
  3411. var keys = this.data.hierarchy[ h ].keys;
  3412. key = key % keys.length;
  3413. for ( ; key < keys.length; key++ ) {
  3414. if ( keys[ key ].hasTarget( sid ) ) {
  3415. return keys[ key ];
  3416. }
  3417. }
  3418. return keys[ 0 ];
  3419. };
  3420. // Get previous key with
  3421. THREE.KeyFrameAnimation.prototype.getPrevKeyWith = function( sid, h, key ) {
  3422. var keys = this.data.hierarchy[ h ].keys;
  3423. key = key >= 0 ? key : key + keys.length;
  3424. for ( ; key >= 0; key-- ) {
  3425. if ( keys[ key ].hasTarget( sid ) ) {
  3426. return keys[ key ];
  3427. }
  3428. }
  3429. return keys[ keys.length - 1 ];
  3430. };
  3431. /**
  3432. * Camera for rendering cube maps
  3433. * - renders scene into axis-aligned cube
  3434. *
  3435. * @author alteredq / http://alteredqualia.com/
  3436. */
  3437. THREE.CubeCamera = function ( near, far, cubeResolution ) {
  3438. THREE.Object3D.call( this );
  3439. var fov = 90, aspect = 1;
  3440. var cameraPX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3441. cameraPX.up.set( 0, -1, 0 );
  3442. cameraPX.lookAt( new THREE.Vector3( 1, 0, 0 ) );
  3443. this.add( cameraPX );
  3444. var cameraNX = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3445. cameraNX.up.set( 0, -1, 0 );
  3446. cameraNX.lookAt( new THREE.Vector3( -1, 0, 0 ) );
  3447. this.add( cameraNX );
  3448. var cameraPY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3449. cameraPY.up.set( 0, 0, 1 );
  3450. cameraPY.lookAt( new THREE.Vector3( 0, 1, 0 ) );
  3451. this.add( cameraPY );
  3452. var cameraNY = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3453. cameraNY.up.set( 0, 0, -1 );
  3454. cameraNY.lookAt( new THREE.Vector3( 0, -1, 0 ) );
  3455. this.add( cameraNY );
  3456. var cameraPZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3457. cameraPZ.up.set( 0, -1, 0 );
  3458. cameraPZ.lookAt( new THREE.Vector3( 0, 0, 1 ) );
  3459. this.add( cameraPZ );
  3460. var cameraNZ = new THREE.PerspectiveCamera( fov, aspect, near, far );
  3461. cameraNZ.up.set( 0, -1, 0 );
  3462. cameraNZ.lookAt( new THREE.Vector3( 0, 0, -1 ) );
  3463. this.add( cameraNZ );
  3464. this.renderTarget = new THREE.WebGLRenderTargetCube( cubeResolution, cubeResolution, { format: THREE.RGBFormat, magFilter: THREE.LinearFilter, minFilter: THREE.LinearFilter } );
  3465. this.updateCubeMap = function ( renderer, scene ) {
  3466. var renderTarget = this.renderTarget;
  3467. var generateMipmaps = renderTarget.generateMipmaps;
  3468. renderTarget.generateMipmaps = false;
  3469. renderTarget.activeCubeFace = 0;
  3470. renderer.render( scene, cameraPX, renderTarget );
  3471. renderTarget.activeCubeFace = 1;
  3472. renderer.render( scene, cameraNX, renderTarget );
  3473. renderTarget.activeCubeFace = 2;
  3474. renderer.render( scene, cameraPY, renderTarget );
  3475. renderTarget.activeCubeFace = 3;
  3476. renderer.render( scene, cameraNY, renderTarget );
  3477. renderTarget.activeCubeFace = 4;
  3478. renderer.render( scene, cameraPZ, renderTarget );
  3479. renderTarget.generateMipmaps = generateMipmaps;
  3480. renderTarget.activeCubeFace = 5;
  3481. renderer.render( scene, cameraNZ, renderTarget );
  3482. };
  3483. };
  3484. THREE.CubeCamera.prototype = new THREE.Object3D();
  3485. THREE.CubeCamera.prototype.constructor = THREE.CubeCamera;
  3486. /*
  3487. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  3488. *
  3489. * A general perpose camera, for setting FOV, Lens Focal Length,
  3490. * and switching between perspective and orthographic views easily.
  3491. * Use this only if you do not wish to manage
  3492. * both a Orthographic and Perspective Camera
  3493. *
  3494. */
  3495. THREE.CombinedCamera = function ( width, height, fov, near, far, orthonear, orthofar ) {
  3496. THREE.Camera.call( this );
  3497. this.fov = fov;
  3498. this.left = -width / 2;
  3499. this.right = width / 2
  3500. this.top = height / 2;
  3501. this.bottom = -height / 2;
  3502. // We could also handle the projectionMatrix internally, but just wanted to test nested camera objects
  3503. this.cameraO = new THREE.OrthographicCamera( width / - 2, width / 2, height / 2, height / - 2, orthonear, orthofar );
  3504. this.cameraP = new THREE.PerspectiveCamera( fov, width/height, near, far );
  3505. this.zoom = 1;
  3506. this.toPerspective();
  3507. var aspect = width/height;
  3508. };
  3509. THREE.CombinedCamera.prototype = new THREE.Camera();
  3510. THREE.CombinedCamera.prototype.constructor = THREE.CombinedCamera;
  3511. THREE.CombinedCamera.prototype.toPerspective = function () {
  3512. // Switches to the Perspective Camera
  3513. this.near = this.cameraP.near;
  3514. this.far = this.cameraP.far;
  3515. this.cameraP.fov = this.fov / this.zoom ;
  3516. this.cameraP.updateProjectionMatrix();
  3517. this.projectionMatrix = this.cameraP.projectionMatrix;
  3518. this.inPersepectiveMode = true;
  3519. this.inOrthographicMode = false;
  3520. };
  3521. THREE.CombinedCamera.prototype.toOrthographic = function () {
  3522. // Switches to the Orthographic camera estimating viewport from Perspective
  3523. var fov = this.fov;
  3524. var aspect = this.cameraP.aspect;
  3525. var near = this.cameraP.near;
  3526. var far = this.cameraP.far;
  3527. // The size that we set is the mid plane of the viewing frustum
  3528. var hyperfocus = ( near + far ) / 2;
  3529. var halfHeight = Math.tan( fov / 2 ) * hyperfocus;
  3530. var planeHeight = 2 * halfHeight;
  3531. var planeWidth = planeHeight * aspect;
  3532. var halfWidth = planeWidth / 2;
  3533. halfHeight /= this.zoom;
  3534. halfWidth /= this.zoom;
  3535. this.cameraO.left = -halfWidth;
  3536. this.cameraO.right = halfWidth;
  3537. this.cameraO.top = halfHeight;
  3538. this.cameraO.bottom = -halfHeight;
  3539. // this.cameraO.left = -farHalfWidth;
  3540. // this.cameraO.right = farHalfWidth;
  3541. // this.cameraO.top = farHalfHeight;
  3542. // this.cameraO.bottom = -farHalfHeight;
  3543. // this.cameraO.left = this.left / this.zoom;
  3544. // this.cameraO.right = this.right / this.zoom;
  3545. // this.cameraO.top = this.top / this.zoom;
  3546. // this.cameraO.bottom = this.bottom / this.zoom;
  3547. this.cameraO.updateProjectionMatrix();
  3548. this.near = this.cameraO.near;
  3549. this.far = this.cameraO.far;
  3550. this.projectionMatrix = this.cameraO.projectionMatrix;
  3551. this.inPersepectiveMode = false;
  3552. this.inOrthographicMode = true;
  3553. };
  3554. THREE.CombinedCamera.prototype.setSize = function(width, height) {
  3555. this.cameraP.aspect = width / height;
  3556. this.left = -width / 2;
  3557. this.right = width / 2
  3558. this.top = height / 2;
  3559. this.bottom = -height / 2;
  3560. }
  3561. THREE.CombinedCamera.prototype.setFov = function(fov) {
  3562. this.fov = fov;
  3563. if (this.inPersepectiveMode) {
  3564. this.toPerspective();
  3565. } else {
  3566. this.toOrthographic();
  3567. }
  3568. };
  3569. // For mantaining similar API with PerspectiveCamera
  3570. THREE.CombinedCamera.prototype.updateProjectionMatrix = function() {
  3571. if (this.inPersepectiveMode) {
  3572. this.toPerspective();
  3573. } else {
  3574. this.toPerspective();
  3575. this.toOrthographic();
  3576. }
  3577. };
  3578. /*
  3579. * Uses Focal Length (in mm) to estimate and set FOV
  3580. * 35mm (fullframe) camera is used if frame size is not specified;
  3581. * Formula based on http://www.bobatkins.com/photography/technical/field_of_view.html
  3582. */
  3583. THREE.CombinedCamera.prototype.setLens = function ( focalLength, frameHeight ) {
  3584. frameHeight = frameHeight !== undefined ? frameHeight : 24;
  3585. var fov = 2 * Math.atan( frameHeight / ( focalLength * 2 ) ) * ( 180 / Math.PI );
  3586. this.setFov( fov );
  3587. return fov;
  3588. };
  3589. THREE.CombinedCamera.prototype.setZoom = function(zoom) {
  3590. this.zoom = zoom;
  3591. if (this.inPersepectiveMode) {
  3592. this.toPerspective();
  3593. } else {
  3594. this.toOrthographic();
  3595. }
  3596. };
  3597. THREE.CombinedCamera.prototype.toFrontView = function() {
  3598. this.rotation.x = 0;
  3599. this.rotation.y = 0;
  3600. this.rotation.z = 0;
  3601. // should we be modifing the matrix instead?
  3602. this.rotationAutoUpdate = false;
  3603. };
  3604. THREE.CombinedCamera.prototype.toBackView = function() {
  3605. this.rotation.x = 0;
  3606. this.rotation.y = Math.PI;
  3607. this.rotation.z = 0;
  3608. this.rotationAutoUpdate = false;
  3609. };
  3610. THREE.CombinedCamera.prototype.toLeftView = function() {
  3611. this.rotation.x = 0;
  3612. this.rotation.y = - Math.PI / 2;
  3613. this.rotation.z = 0;
  3614. this.rotationAutoUpdate = false;
  3615. };
  3616. THREE.CombinedCamera.prototype.toRightView = function() {
  3617. this.rotation.x = 0;
  3618. this.rotation.y = Math.PI / 2;
  3619. this.rotation.z = 0;
  3620. this.rotationAutoUpdate = false;
  3621. };
  3622. THREE.CombinedCamera.prototype.toTopView = function() {
  3623. this.rotation.x = - Math.PI / 2;
  3624. this.rotation.y = 0;
  3625. this.rotation.z = 0;
  3626. this.rotationAutoUpdate = false;
  3627. };
  3628. THREE.CombinedCamera.prototype.toBottomView = function() {
  3629. this.rotation.x = Math.PI / 2;
  3630. this.rotation.y = 0;
  3631. this.rotation.z = 0;
  3632. this.rotationAutoUpdate = false;
  3633. };
  3634. /**
  3635. * @author mrdoob / http://mrdoob.com/
  3636. * @author alteredq / http://alteredqualia.com/
  3637. * @author paulirish / http://paulirish.com/
  3638. */
  3639. THREE.FirstPersonControls = function ( object, domElement ) {
  3640. this.object = object;
  3641. this.target = new THREE.Vector3( 0, 0, 0 );
  3642. this.domElement = ( domElement !== undefined ) ? domElement : document;
  3643. this.movementSpeed = 1.0;
  3644. this.lookSpeed = 0.005;
  3645. this.noFly = false;
  3646. this.lookVertical = true;
  3647. this.autoForward = false;
  3648. this.activeLook = true;
  3649. this.heightSpeed = false;
  3650. this.heightCoef = 1.0;
  3651. this.heightMin = 0.0;
  3652. this.constrainVertical = false;
  3653. this.verticalMin = 0;
  3654. this.verticalMax = Math.PI;
  3655. this.autoSpeedFactor = 0.0;
  3656. this.mouseX = 0;
  3657. this.mouseY = 0;
  3658. this.lat = 0;
  3659. this.lon = 0;
  3660. this.phi = 0;
  3661. this.theta = 0;
  3662. this.moveForward = false;
  3663. this.moveBackward = false;
  3664. this.moveLeft = false;
  3665. this.moveRight = false;
  3666. this.freeze = false;
  3667. this.mouseDragOn = false;
  3668. if ( this.domElement === document ) {
  3669. this.viewHalfX = window.innerWidth / 2;
  3670. this.viewHalfY = window.innerHeight / 2;
  3671. } else {
  3672. this.viewHalfX = this.domElement.offsetWidth / 2;
  3673. this.viewHalfY = this.domElement.offsetHeight / 2;
  3674. this.domElement.setAttribute( 'tabindex', -1 );
  3675. }
  3676. this.onMouseDown = function ( event ) {
  3677. if ( this.domElement !== document ) {
  3678. this.domElement.focus();
  3679. }
  3680. event.preventDefault();
  3681. event.stopPropagation();
  3682. if ( this.activeLook ) {
  3683. switch ( event.button ) {
  3684. case 0: this.moveForward = true; break;
  3685. case 2: this.moveBackward = true; break;
  3686. }
  3687. }
  3688. this.mouseDragOn = true;
  3689. };
  3690. this.onMouseUp = function ( event ) {
  3691. event.preventDefault();
  3692. event.stopPropagation();
  3693. if ( this.activeLook ) {
  3694. switch ( event.button ) {
  3695. case 0: this.moveForward = false; break;
  3696. case 2: this.moveBackward = false; break;
  3697. }
  3698. }
  3699. this.mouseDragOn = false;
  3700. };
  3701. this.onMouseMove = function ( event ) {
  3702. if ( this.domElement === document ) {
  3703. this.mouseX = event.pageX - this.viewHalfX;
  3704. this.mouseY = event.pageY - this.viewHalfY;
  3705. } else {
  3706. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  3707. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  3708. }
  3709. };
  3710. this.onKeyDown = function ( event ) {
  3711. switch( event.keyCode ) {
  3712. case 38: /*up*/
  3713. case 87: /*W*/ this.moveForward = true; break;
  3714. case 37: /*left*/
  3715. case 65: /*A*/ this.moveLeft = true; break;
  3716. case 40: /*down*/
  3717. case 83: /*S*/ this.moveBackward = true; break;
  3718. case 39: /*right*/
  3719. case 68: /*D*/ this.moveRight = true; break;
  3720. case 82: /*R*/ this.moveUp = true; break;
  3721. case 70: /*F*/ this.moveDown = true; break;
  3722. case 81: /*Q*/ this.freeze = !this.freeze; break;
  3723. }
  3724. };
  3725. this.onKeyUp = function ( event ) {
  3726. switch( event.keyCode ) {
  3727. case 38: /*up*/
  3728. case 87: /*W*/ this.moveForward = false; break;
  3729. case 37: /*left*/
  3730. case 65: /*A*/ this.moveLeft = false; break;
  3731. case 40: /*down*/
  3732. case 83: /*S*/ this.moveBackward = false; break;
  3733. case 39: /*right*/
  3734. case 68: /*D*/ this.moveRight = false; break;
  3735. case 82: /*R*/ this.moveUp = false; break;
  3736. case 70: /*F*/ this.moveDown = false; break;
  3737. }
  3738. };
  3739. this.update = function( delta ) {
  3740. var actualMoveSpeed = 0;
  3741. if ( this.freeze ) {
  3742. return;
  3743. } else {
  3744. if ( this.heightSpeed ) {
  3745. var y = THREE.Math.clamp( this.object.position.y, this.heightMin, this.heightMax );
  3746. var heightDelta = y - this.heightMin;
  3747. this.autoSpeedFactor = delta * ( heightDelta * this.heightCoef );
  3748. } else {
  3749. this.autoSpeedFactor = 0.0;
  3750. }
  3751. actualMoveSpeed = delta * this.movementSpeed;
  3752. if ( this.moveForward || ( this.autoForward && !this.moveBackward ) ) this.object.translateZ( - ( actualMoveSpeed + this.autoSpeedFactor ) );
  3753. if ( this.moveBackward ) this.object.translateZ( actualMoveSpeed );
  3754. if ( this.moveLeft ) this.object.translateX( - actualMoveSpeed );
  3755. if ( this.moveRight ) this.object.translateX( actualMoveSpeed );
  3756. if ( this.moveUp ) this.object.translateY( actualMoveSpeed );
  3757. if ( this.moveDown ) this.object.translateY( - actualMoveSpeed );
  3758. var actualLookSpeed = delta * this.lookSpeed;
  3759. if ( !this.activeLook ) {
  3760. actualLookSpeed = 0;
  3761. }
  3762. this.lon += this.mouseX * actualLookSpeed;
  3763. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed;
  3764. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  3765. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  3766. this.theta = this.lon * Math.PI / 180;
  3767. var targetPosition = this.target,
  3768. position = this.object.position;
  3769. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  3770. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  3771. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  3772. }
  3773. var verticalLookRatio = 1;
  3774. if ( this.constrainVertical ) {
  3775. verticalLookRatio = Math.PI / ( this.verticalMax - this.verticalMin );
  3776. }
  3777. this.lon += this.mouseX * actualLookSpeed;
  3778. if( this.lookVertical ) this.lat -= this.mouseY * actualLookSpeed * verticalLookRatio;
  3779. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  3780. this.phi = ( 90 - this.lat ) * Math.PI / 180;
  3781. this.theta = this.lon * Math.PI / 180;
  3782. if ( this.constrainVertical ) {
  3783. this.phi = THREE.Math.mapLinear( this.phi, 0, Math.PI, this.verticalMin, this.verticalMax );
  3784. }
  3785. var targetPosition = this.target,
  3786. position = this.object.position;
  3787. targetPosition.x = position.x + 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  3788. targetPosition.y = position.y + 100 * Math.cos( this.phi );
  3789. targetPosition.z = position.z + 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  3790. this.object.lookAt( targetPosition );
  3791. };
  3792. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  3793. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  3794. this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false );
  3795. this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false );
  3796. this.domElement.addEventListener( 'keydown', bind( this, this.onKeyDown ), false );
  3797. this.domElement.addEventListener( 'keyup', bind( this, this.onKeyUp ), false );
  3798. function bind( scope, fn ) {
  3799. return function () {
  3800. fn.apply( scope, arguments );
  3801. };
  3802. };
  3803. };
  3804. /**
  3805. * @author alteredq / http://alteredqualia.com/
  3806. */
  3807. THREE.PathControls = function ( object, domElement ) {
  3808. this.object = object;
  3809. this.domElement = ( domElement !== undefined ) ? domElement : document;
  3810. this.id = "PathControls" + THREE.PathControlsIdCounter ++;
  3811. // API
  3812. this.duration = 10 * 1000; // milliseconds
  3813. this.waypoints = [];
  3814. this.useConstantSpeed = true;
  3815. this.resamplingCoef = 50;
  3816. this.debugPath = new THREE.Object3D();
  3817. this.debugDummy = new THREE.Object3D();
  3818. this.animationParent = new THREE.Object3D();
  3819. this.lookSpeed = 0.005;
  3820. this.lookVertical = true;
  3821. this.lookHorizontal = true;
  3822. this.verticalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  3823. this.horizontalAngleMap = { srcRange: [ 0, 2 * Math.PI ], dstRange: [ 0, 2 * Math.PI ] };
  3824. // internals
  3825. this.target = new THREE.Object3D();
  3826. this.mouseX = 0;
  3827. this.mouseY = 0;
  3828. this.lat = 0;
  3829. this.lon = 0;
  3830. this.phi = 0;
  3831. this.theta = 0;
  3832. if ( this.domElement === document ) {
  3833. this.viewHalfX = window.innerWidth / 2;
  3834. this.viewHalfY = window.innerHeight / 2;
  3835. } else {
  3836. this.viewHalfX = this.domElement.offsetWidth / 2;
  3837. this.viewHalfY = this.domElement.offsetHeight / 2;
  3838. this.domElement.setAttribute( 'tabindex', -1 );
  3839. }
  3840. var PI2 = Math.PI * 2,
  3841. PI180 = Math.PI / 180;
  3842. // methods
  3843. this.update = function ( delta ) {
  3844. var srcRange, dstRange;
  3845. if( this.lookHorizontal ) this.lon += this.mouseX * this.lookSpeed * delta;
  3846. if( this.lookVertical ) this.lat -= this.mouseY * this.lookSpeed * delta;
  3847. this.lon = Math.max( 0, Math.min( 360, this.lon ) );
  3848. this.lat = Math.max( - 85, Math.min( 85, this.lat ) );
  3849. this.phi = ( 90 - this.lat ) * PI180;
  3850. this.theta = this.lon * PI180;
  3851. this.phi = normalize_angle_rad( this.phi );
  3852. // constrain vertical look angle
  3853. srcRange = this.verticalAngleMap.srcRange;
  3854. dstRange = this.verticalAngleMap.dstRange;
  3855. var tmpPhi = THREE.Math.mapLinear( this.phi, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  3856. var tmpPhiFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  3857. var tmpPhiNormalized = ( tmpPhi - dstRange[ 0 ] ) / tmpPhiFullRange;
  3858. this.phi = QuadraticEaseInOut( tmpPhiNormalized ) * tmpPhiFullRange + dstRange[ 0 ];
  3859. // constrain horizontal look angle
  3860. srcRange = this.horizontalAngleMap.srcRange;
  3861. dstRange = this.horizontalAngleMap.dstRange;
  3862. var tmpTheta = THREE.Math.mapLinear( this.theta, srcRange[ 0 ], srcRange[ 1 ], dstRange[ 0 ], dstRange[ 1 ] );
  3863. var tmpThetaFullRange = dstRange[ 1 ] - dstRange[ 0 ];
  3864. var tmpThetaNormalized = ( tmpTheta - dstRange[ 0 ] ) / tmpThetaFullRange;
  3865. this.theta = QuadraticEaseInOut( tmpThetaNormalized ) * tmpThetaFullRange + dstRange[ 0 ];
  3866. var targetPosition = this.target.position,
  3867. position = this.object.position;
  3868. targetPosition.x = 100 * Math.sin( this.phi ) * Math.cos( this.theta );
  3869. targetPosition.y = 100 * Math.cos( this.phi );
  3870. targetPosition.z = 100 * Math.sin( this.phi ) * Math.sin( this.theta );
  3871. this.object.lookAt( this.target.position );
  3872. };
  3873. this.onMouseMove = function ( event ) {
  3874. if ( this.domElement === document ) {
  3875. this.mouseX = event.pageX - this.viewHalfX;
  3876. this.mouseY = event.pageY - this.viewHalfY;
  3877. } else {
  3878. this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX;
  3879. this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY;
  3880. }
  3881. };
  3882. // utils
  3883. function normalize_angle_rad( a ) {
  3884. var b = a % PI2;
  3885. return b >= 0 ? b : b + PI2;
  3886. };
  3887. function distance( a, b ) {
  3888. var dx = a[ 0 ] - b[ 0 ],
  3889. dy = a[ 1 ] - b[ 1 ],
  3890. dz = a[ 2 ] - b[ 2 ];
  3891. return Math.sqrt( dx * dx + dy * dy + dz * dz );
  3892. };
  3893. function QuadraticEaseInOut ( k ) {
  3894. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  3895. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  3896. };
  3897. function bind( scope, fn ) {
  3898. return function () {
  3899. fn.apply( scope, arguments );
  3900. };
  3901. };
  3902. function initAnimationPath( parent, spline, name, duration ) {
  3903. var animationData = {
  3904. name: name,
  3905. fps: 0.6,
  3906. length: duration,
  3907. hierarchy: []
  3908. };
  3909. var i,
  3910. parentAnimation, childAnimation,
  3911. path = spline.getControlPointsArray(),
  3912. sl = spline.getLength(),
  3913. pl = path.length,
  3914. t = 0,
  3915. first = 0,
  3916. last = pl - 1;
  3917. parentAnimation = { parent: -1, keys: [] };
  3918. parentAnimation.keys[ first ] = { time: 0, pos: path[ first ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  3919. parentAnimation.keys[ last ] = { time: duration, pos: path[ last ], rot: [ 0, 0, 0, 1 ], scl: [ 1, 1, 1 ] };
  3920. for ( i = 1; i < pl - 1; i++ ) {
  3921. // real distance (approximation via linear segments)
  3922. t = duration * sl.chunks[ i ] / sl.total;
  3923. // equal distance
  3924. //t = duration * ( i / pl );
  3925. // linear distance
  3926. //t += duration * distance( path[ i ], path[ i - 1 ] ) / sl.total;
  3927. parentAnimation.keys[ i ] = { time: t, pos: path[ i ] };
  3928. }
  3929. animationData.hierarchy[ 0 ] = parentAnimation;
  3930. THREE.AnimationHandler.add( animationData );
  3931. return new THREE.Animation( parent, name, THREE.AnimationHandler.CATMULLROM_FORWARD, false );
  3932. };
  3933. function createSplineGeometry( spline, n_sub ) {
  3934. var i, index, position,
  3935. geometry = new THREE.Geometry();
  3936. for ( i = 0; i < spline.points.length * n_sub; i ++ ) {
  3937. index = i / ( spline.points.length * n_sub );
  3938. position = spline.getPoint( index );
  3939. geometry.vertices[ i ] = new THREE.Vertex( position.x, position.y, position.z );
  3940. }
  3941. return geometry;
  3942. };
  3943. function createPath( parent, spline ) {
  3944. var lineGeo = createSplineGeometry( spline, 10 ),
  3945. particleGeo = createSplineGeometry( spline, 10 ),
  3946. lineMat = new THREE.LineBasicMaterial( { color: 0xff0000, linewidth: 3 } ),
  3947. lineObj = new THREE.Line( lineGeo, lineMat ),
  3948. particleObj = new THREE.ParticleSystem( particleGeo, new THREE.ParticleBasicMaterial( { color: 0xffaa00, size: 3 } ) );
  3949. lineObj.scale.set( 1, 1, 1 );
  3950. parent.add( lineObj );
  3951. particleObj.scale.set( 1, 1, 1 );
  3952. parent.add( particleObj );
  3953. var waypoint,
  3954. geo = new THREE.SphereGeometry( 1, 16, 8 ),
  3955. mat = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
  3956. for ( var i = 0; i < spline.points.length; i ++ ) {
  3957. waypoint = new THREE.Mesh( geo, mat );
  3958. waypoint.position.copy( spline.points[ i ] );
  3959. parent.add( waypoint );
  3960. }
  3961. };
  3962. this.init = function ( ) {
  3963. // constructor
  3964. this.spline = new THREE.Spline();
  3965. this.spline.initFromArray( this.waypoints );
  3966. if ( this.useConstantSpeed ) {
  3967. this.spline.reparametrizeByArcLength( this.resamplingCoef );
  3968. }
  3969. if ( this.createDebugDummy ) {
  3970. var dummyParentMaterial = new THREE.MeshLambertMaterial( { color: 0x0077ff } ),
  3971. dummyChildMaterial = new THREE.MeshLambertMaterial( { color: 0x00ff00 } ),
  3972. dummyParentGeo = new THREE.CubeGeometry( 10, 10, 20 ),
  3973. dummyChildGeo = new THREE.CubeGeometry( 2, 2, 10 );
  3974. this.animationParent = new THREE.Mesh( dummyParentGeo, dummyParentMaterial );
  3975. var dummyChild = new THREE.Mesh( dummyChildGeo, dummyChildMaterial );
  3976. dummyChild.position.set( 0, 10, 0 );
  3977. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  3978. this.animationParent.add( this.object );
  3979. this.animationParent.add( this.target );
  3980. this.animationParent.add( dummyChild );
  3981. } else {
  3982. this.animation = initAnimationPath( this.animationParent, this.spline, this.id, this.duration );
  3983. this.animationParent.add( this.target );
  3984. this.animationParent.add( this.object );
  3985. }
  3986. if ( this.createDebugPath ) {
  3987. createPath( this.debugPath, this.spline );
  3988. }
  3989. this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false );
  3990. };
  3991. };
  3992. THREE.PathControlsIdCounter = 0;
  3993. /**
  3994. * @author James Baicoianu / http://www.baicoianu.com/
  3995. */
  3996. THREE.FlyControls = function ( object, domElement ) {
  3997. this.object = object;
  3998. this.domElement = ( domElement !== undefined ) ? domElement : document;
  3999. if ( domElement ) this.domElement.setAttribute( 'tabindex', -1 );
  4000. // API
  4001. this.movementSpeed = 1.0;
  4002. this.rollSpeed = 0.005;
  4003. this.dragToLook = false;
  4004. this.autoForward = false;
  4005. // disable default target object behavior
  4006. this.object.useQuaternion = true;
  4007. // internals
  4008. this.tmpQuaternion = new THREE.Quaternion();
  4009. this.mouseStatus = 0;
  4010. 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 };
  4011. this.moveVector = new THREE.Vector3( 0, 0, 0 );
  4012. this.rotationVector = new THREE.Vector3( 0, 0, 0 );
  4013. this.handleEvent = function ( event ) {
  4014. if ( typeof this[ event.type ] == 'function' ) {
  4015. this[ event.type ]( event );
  4016. }
  4017. };
  4018. this.keydown = function( event ) {
  4019. if ( event.altKey ) {
  4020. return;
  4021. }
  4022. switch( event.keyCode ) {
  4023. case 16: /* shift */ this.movementSpeedMultiplier = .1; break;
  4024. case 87: /*W*/ this.moveState.forward = 1; break;
  4025. case 83: /*S*/ this.moveState.back = 1; break;
  4026. case 65: /*A*/ this.moveState.left = 1; break;
  4027. case 68: /*D*/ this.moveState.right = 1; break;
  4028. case 82: /*R*/ this.moveState.up = 1; break;
  4029. case 70: /*F*/ this.moveState.down = 1; break;
  4030. case 38: /*up*/ this.moveState.pitchUp = 1; break;
  4031. case 40: /*down*/ this.moveState.pitchDown = 1; break;
  4032. case 37: /*left*/ this.moveState.yawLeft = 1; break;
  4033. case 39: /*right*/ this.moveState.yawRight = 1; break;
  4034. case 81: /*Q*/ this.moveState.rollLeft = 1; break;
  4035. case 69: /*E*/ this.moveState.rollRight = 1; break;
  4036. }
  4037. this.updateMovementVector();
  4038. this.updateRotationVector();
  4039. };
  4040. this.keyup = function( event ) {
  4041. switch( event.keyCode ) {
  4042. case 16: /* shift */ this.movementSpeedMultiplier = 1; break;
  4043. case 87: /*W*/ this.moveState.forward = 0; break;
  4044. case 83: /*S*/ this.moveState.back = 0; break;
  4045. case 65: /*A*/ this.moveState.left = 0; break;
  4046. case 68: /*D*/ this.moveState.right = 0; break;
  4047. case 82: /*R*/ this.moveState.up = 0; break;
  4048. case 70: /*F*/ this.moveState.down = 0; break;
  4049. case 38: /*up*/ this.moveState.pitchUp = 0; break;
  4050. case 40: /*down*/ this.moveState.pitchDown = 0; break;
  4051. case 37: /*left*/ this.moveState.yawLeft = 0; break;
  4052. case 39: /*right*/ this.moveState.yawRight = 0; break;
  4053. case 81: /*Q*/ this.moveState.rollLeft = 0; break;
  4054. case 69: /*E*/ this.moveState.rollRight = 0; break;
  4055. }
  4056. this.updateMovementVector();
  4057. this.updateRotationVector();
  4058. };
  4059. this.mousedown = function( event ) {
  4060. if ( this.domElement !== document ) {
  4061. this.domElement.focus();
  4062. }
  4063. event.preventDefault();
  4064. event.stopPropagation();
  4065. if ( this.dragToLook ) {
  4066. this.mouseStatus ++;
  4067. } else {
  4068. switch ( event.button ) {
  4069. case 0: this.object.moveForward = true; break;
  4070. case 2: this.object.moveBackward = true; break;
  4071. }
  4072. }
  4073. };
  4074. this.mousemove = function( event ) {
  4075. if ( !this.dragToLook || this.mouseStatus > 0 ) {
  4076. var container = this.getContainerDimensions();
  4077. var halfWidth = container.size[ 0 ] / 2;
  4078. var halfHeight = container.size[ 1 ] / 2;
  4079. this.moveState.yawLeft = - ( ( event.pageX - container.offset[ 0 ] ) - halfWidth ) / halfWidth;
  4080. this.moveState.pitchDown = ( ( event.pageY - container.offset[ 1 ] ) - halfHeight ) / halfHeight;
  4081. this.updateRotationVector();
  4082. }
  4083. };
  4084. this.mouseup = function( event ) {
  4085. event.preventDefault();
  4086. event.stopPropagation();
  4087. if ( this.dragToLook ) {
  4088. this.mouseStatus --;
  4089. this.moveState.yawLeft = this.moveState.pitchDown = 0;
  4090. } else {
  4091. switch ( event.button ) {
  4092. case 0: this.moveForward = false; break;
  4093. case 2: this.moveBackward = false; break;
  4094. }
  4095. }
  4096. this.updateRotationVector();
  4097. };
  4098. this.update = function( delta ) {
  4099. var moveMult = delta * this.movementSpeed;
  4100. var rotMult = delta * this.rollSpeed;
  4101. this.object.translateX( this.moveVector.x * moveMult );
  4102. this.object.translateY( this.moveVector.y * moveMult );
  4103. this.object.translateZ( this.moveVector.z * moveMult );
  4104. this.tmpQuaternion.set( this.rotationVector.x * rotMult, this.rotationVector.y * rotMult, this.rotationVector.z * rotMult, 1 ).normalize();
  4105. this.object.quaternion.multiplySelf( this.tmpQuaternion );
  4106. this.object.matrix.setPosition( this.object.position );
  4107. this.object.matrix.setRotationFromQuaternion( this.object.quaternion );
  4108. this.object.matrixWorldNeedsUpdate = true;
  4109. };
  4110. this.updateMovementVector = function() {
  4111. var forward = ( this.moveState.forward || ( this.autoForward && !this.moveState.back ) ) ? 1 : 0;
  4112. this.moveVector.x = ( -this.moveState.left + this.moveState.right );
  4113. this.moveVector.y = ( -this.moveState.down + this.moveState.up );
  4114. this.moveVector.z = ( -forward + this.moveState.back );
  4115. //console.log( 'move:', [ this.moveVector.x, this.moveVector.y, this.moveVector.z ] );
  4116. };
  4117. this.updateRotationVector = function() {
  4118. this.rotationVector.x = ( -this.moveState.pitchDown + this.moveState.pitchUp );
  4119. this.rotationVector.y = ( -this.moveState.yawRight + this.moveState.yawLeft );
  4120. this.rotationVector.z = ( -this.moveState.rollRight + this.moveState.rollLeft );
  4121. //console.log( 'rotate:', [ this.rotationVector.x, this.rotationVector.y, this.rotationVector.z ] );
  4122. };
  4123. this.getContainerDimensions = function() {
  4124. if ( this.domElement != document ) {
  4125. return {
  4126. size : [ this.domElement.offsetWidth, this.domElement.offsetHeight ],
  4127. offset : [ this.domElement.offsetLeft, this.domElement.offsetTop ]
  4128. };
  4129. } else {
  4130. return {
  4131. size : [ window.innerWidth, window.innerHeight ],
  4132. offset : [ 0, 0 ]
  4133. };
  4134. }
  4135. };
  4136. function bind( scope, fn ) {
  4137. return function () {
  4138. fn.apply( scope, arguments );
  4139. };
  4140. };
  4141. this.domElement.addEventListener( 'mousemove', bind( this, this.mousemove ), false );
  4142. this.domElement.addEventListener( 'mousedown', bind( this, this.mousedown ), false );
  4143. this.domElement.addEventListener( 'mouseup', bind( this, this.mouseup ), false );
  4144. this.domElement.addEventListener( 'keydown', bind( this, this.keydown ), false );
  4145. this.domElement.addEventListener( 'keyup', bind( this, this.keyup ), false );
  4146. this.updateMovementVector();
  4147. this.updateRotationVector();
  4148. };
  4149. /**
  4150. * @author mikael emtinger / http://gomo.se/
  4151. * @author alteredq / http://alteredqualia.com/
  4152. */
  4153. THREE.RollControls = function ( object, domElement ) {
  4154. this.object = object;
  4155. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4156. // API
  4157. this.mouseLook = true;
  4158. this.autoForward = false;
  4159. this.lookSpeed = 1;
  4160. this.movementSpeed = 1;
  4161. this.rollSpeed = 1;
  4162. this.constrainVertical = [ -0.9, 0.9 ];
  4163. // disable default target object behavior
  4164. this.object.matrixAutoUpdate = false;
  4165. // internals
  4166. this.forward = new THREE.Vector3( 0, 0, 1 );
  4167. this.roll = 0;
  4168. var xTemp = new THREE.Vector3();
  4169. var yTemp = new THREE.Vector3();
  4170. var zTemp = new THREE.Vector3();
  4171. var rollMatrix = new THREE.Matrix4();
  4172. var doRoll = false, rollDirection = 1, forwardSpeed = 0, sideSpeed = 0, upSpeed = 0;
  4173. var mouseX = 0, mouseY = 0;
  4174. var windowHalfX = window.innerWidth / 2;
  4175. var windowHalfY = window.innerHeight / 2;
  4176. // custom update
  4177. this.update = function ( delta ) {
  4178. if ( this.mouseLook ) {
  4179. var actualLookSpeed = delta * this.lookSpeed;
  4180. this.rotateHorizontally( actualLookSpeed * mouseX );
  4181. this.rotateVertically( actualLookSpeed * mouseY );
  4182. }
  4183. var actualSpeed = delta * this.movementSpeed;
  4184. var forwardOrAuto = ( forwardSpeed > 0 || ( this.autoForward && ! ( forwardSpeed < 0 ) ) ) ? 1 : forwardSpeed;
  4185. this.object.translateZ( -actualSpeed * forwardOrAuto );
  4186. this.object.translateX( actualSpeed * sideSpeed );
  4187. this.object.translateY( actualSpeed * upSpeed );
  4188. if( doRoll ) {
  4189. this.roll += this.rollSpeed * delta * rollDirection;
  4190. }
  4191. // cap forward up / down
  4192. if( this.forward.y > this.constrainVertical[ 1 ] ) {
  4193. this.forward.y = this.constrainVertical[ 1 ];
  4194. this.forward.normalize();
  4195. } else if( this.forward.y < this.constrainVertical[ 0 ] ) {
  4196. this.forward.y = this.constrainVertical[ 0 ];
  4197. this.forward.normalize();
  4198. }
  4199. // construct unrolled camera matrix
  4200. zTemp.copy( this.forward );
  4201. yTemp.set( 0, 1, 0 );
  4202. xTemp.cross( yTemp, zTemp ).normalize();
  4203. yTemp.cross( zTemp, xTemp ).normalize();
  4204. this.object.matrix.elements[0] = xTemp.x; this.object.matrix.elements[4] = yTemp.x; this.object.matrix.elements[8] = zTemp.x;
  4205. this.object.matrix.elements[1] = xTemp.y; this.object.matrix.elements[5] = yTemp.y; this.object.matrix.elements[9] = zTemp.y;
  4206. this.object.matrix.elements[2] = xTemp.z; this.object.matrix.elements[6] = yTemp.z; this.object.matrix.elements[10] = zTemp.z;
  4207. // calculate roll matrix
  4208. rollMatrix.identity();
  4209. rollMatrix.elements[0] = Math.cos( this.roll ); rollMatrix.elements[4] = -Math.sin( this.roll );
  4210. rollMatrix.elements[1] = Math.sin( this.roll ); rollMatrix.elements[5] = Math.cos( this.roll );
  4211. // multiply camera with roll
  4212. this.object.matrix.multiplySelf( rollMatrix );
  4213. this.object.matrixWorldNeedsUpdate = true;
  4214. // set position
  4215. this.object.matrix.elements[12] = this.object.position.x;
  4216. this.object.matrix.elements[13] = this.object.position.y;
  4217. this.object.matrix.elements[14] = this.object.position.z;
  4218. };
  4219. this.translateX = function ( distance ) {
  4220. this.object.position.x += this.object.matrix.elements[0] * distance;
  4221. this.object.position.y += this.object.matrix.elements[1] * distance;
  4222. this.object.position.z += this.object.matrix.elements[2] * distance;
  4223. };
  4224. this.translateY = function ( distance ) {
  4225. this.object.position.x += this.object.matrix.elements[4] * distance;
  4226. this.object.position.y += this.object.matrix.elements[5] * distance;
  4227. this.object.position.z += this.object.matrix.elements[6] * distance;
  4228. };
  4229. this.translateZ = function ( distance ) {
  4230. this.object.position.x -= this.object.matrix.elements[8] * distance;
  4231. this.object.position.y -= this.object.matrix.elements[9] * distance;
  4232. this.object.position.z -= this.object.matrix.elements[10] * distance;
  4233. };
  4234. this.rotateHorizontally = function ( amount ) {
  4235. // please note that the amount is NOT degrees, but a scale value
  4236. xTemp.set( this.object.matrix.elements[0], this.object.matrix.elements[1], this.object.matrix.elements[2] );
  4237. xTemp.multiplyScalar( amount );
  4238. this.forward.subSelf( xTemp );
  4239. this.forward.normalize();
  4240. };
  4241. this.rotateVertically = function ( amount ) {
  4242. // please note that the amount is NOT degrees, but a scale value
  4243. yTemp.set( this.object.matrix.elements[4], this.object.matrix.elements[5], this.object.matrix.elements[6] );
  4244. yTemp.multiplyScalar( amount );
  4245. this.forward.addSelf( yTemp );
  4246. this.forward.normalize();
  4247. };
  4248. function onKeyDown( event ) {
  4249. switch( event.keyCode ) {
  4250. case 38: /*up*/
  4251. case 87: /*W*/ forwardSpeed = 1; break;
  4252. case 37: /*left*/
  4253. case 65: /*A*/ sideSpeed = -1; break;
  4254. case 40: /*down*/
  4255. case 83: /*S*/ forwardSpeed = -1; break;
  4256. case 39: /*right*/
  4257. case 68: /*D*/ sideSpeed = 1; break;
  4258. case 81: /*Q*/ doRoll = true; rollDirection = 1; break;
  4259. case 69: /*E*/ doRoll = true; rollDirection = -1; break;
  4260. case 82: /*R*/ upSpeed = 1; break;
  4261. case 70: /*F*/ upSpeed = -1; break;
  4262. }
  4263. };
  4264. function onKeyUp( event ) {
  4265. switch( event.keyCode ) {
  4266. case 38: /*up*/
  4267. case 87: /*W*/ forwardSpeed = 0; break;
  4268. case 37: /*left*/
  4269. case 65: /*A*/ sideSpeed = 0; break;
  4270. case 40: /*down*/
  4271. case 83: /*S*/ forwardSpeed = 0; break;
  4272. case 39: /*right*/
  4273. case 68: /*D*/ sideSpeed = 0; break;
  4274. case 81: /*Q*/ doRoll = false; break;
  4275. case 69: /*E*/ doRoll = false; break;
  4276. case 82: /*R*/ upSpeed = 0; break;
  4277. case 70: /*F*/ upSpeed = 0; break;
  4278. }
  4279. };
  4280. function onMouseMove( event ) {
  4281. mouseX = ( event.clientX - windowHalfX ) / window.innerWidth;
  4282. mouseY = ( event.clientY - windowHalfY ) / window.innerHeight;
  4283. };
  4284. function onMouseDown ( event ) {
  4285. event.preventDefault();
  4286. event.stopPropagation();
  4287. switch ( event.button ) {
  4288. case 0: forwardSpeed = 1; break;
  4289. case 2: forwardSpeed = -1; break;
  4290. }
  4291. };
  4292. function onMouseUp ( event ) {
  4293. event.preventDefault();
  4294. event.stopPropagation();
  4295. switch ( event.button ) {
  4296. case 0: forwardSpeed = 0; break;
  4297. case 2: forwardSpeed = 0; break;
  4298. }
  4299. };
  4300. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  4301. this.domElement.addEventListener( 'mousemove', onMouseMove, false );
  4302. this.domElement.addEventListener( 'mousedown', onMouseDown, false );
  4303. this.domElement.addEventListener( 'mouseup', onMouseUp, false );
  4304. this.domElement.addEventListener( 'keydown', onKeyDown, false );
  4305. this.domElement.addEventListener( 'keyup', onKeyUp, false );
  4306. };
  4307. /**
  4308. * @author Eberhard Graether / http://egraether.com/
  4309. */
  4310. THREE.TrackballControls = function ( object, domElement ) {
  4311. THREE.EventTarget.call( this );
  4312. var _this = this,
  4313. STATE = { NONE : -1, ROTATE : 0, ZOOM : 1, PAN : 2 };
  4314. this.object = object;
  4315. this.domElement = ( domElement !== undefined ) ? domElement : document;
  4316. // API
  4317. this.enabled = true;
  4318. this.screen = { width: window.innerWidth, height: window.innerHeight, offsetLeft: 0, offsetTop: 0 };
  4319. this.radius = ( this.screen.width + this.screen.height ) / 4;
  4320. this.rotateSpeed = 1.0;
  4321. this.zoomSpeed = 1.2;
  4322. this.panSpeed = 0.3;
  4323. this.noRotate = false;
  4324. this.noZoom = false;
  4325. this.noPan = false;
  4326. this.staticMoving = false;
  4327. this.dynamicDampingFactor = 0.2;
  4328. this.minDistance = 0;
  4329. this.maxDistance = Infinity;
  4330. this.keys = [ 65 /*A*/, 83 /*S*/, 68 /*D*/ ];
  4331. // internals
  4332. this.target = new THREE.Vector3();
  4333. var lastPosition = new THREE.Vector3();
  4334. var _keyPressed = false,
  4335. _state = STATE.NONE,
  4336. _eye = new THREE.Vector3(),
  4337. _rotateStart = new THREE.Vector3(),
  4338. _rotateEnd = new THREE.Vector3(),
  4339. _zoomStart = new THREE.Vector2(),
  4340. _zoomEnd = new THREE.Vector2(),
  4341. _panStart = new THREE.Vector2(),
  4342. _panEnd = new THREE.Vector2();
  4343. // events
  4344. var changeEvent = { type: 'change' };
  4345. // methods
  4346. this.handleEvent = function ( event ) {
  4347. if ( typeof this[ event.type ] == 'function' ) {
  4348. this[ event.type ]( event );
  4349. }
  4350. };
  4351. this.getMouseOnScreen = function ( clientX, clientY ) {
  4352. return new THREE.Vector2(
  4353. ( clientX - _this.screen.offsetLeft ) / _this.radius * 0.5,
  4354. ( clientY - _this.screen.offsetTop ) / _this.radius * 0.5
  4355. );
  4356. };
  4357. this.getMouseProjectionOnBall = function ( clientX, clientY ) {
  4358. var mouseOnBall = new THREE.Vector3(
  4359. ( clientX - _this.screen.width * 0.5 - _this.screen.offsetLeft ) / _this.radius,
  4360. ( _this.screen.height * 0.5 + _this.screen.offsetTop - clientY ) / _this.radius,
  4361. 0.0
  4362. );
  4363. var length = mouseOnBall.length();
  4364. if ( length > 1.0 ) {
  4365. mouseOnBall.normalize();
  4366. } else {
  4367. mouseOnBall.z = Math.sqrt( 1.0 - length * length );
  4368. }
  4369. _eye.copy( _this.object.position ).subSelf( _this.target );
  4370. var projection = _this.object.up.clone().setLength( mouseOnBall.y );
  4371. projection.addSelf( _this.object.up.clone().crossSelf( _eye ).setLength( mouseOnBall.x ) );
  4372. projection.addSelf( _eye.setLength( mouseOnBall.z ) );
  4373. return projection;
  4374. };
  4375. this.rotateCamera = function () {
  4376. var angle = Math.acos( _rotateStart.dot( _rotateEnd ) / _rotateStart.length() / _rotateEnd.length() );
  4377. if ( angle ) {
  4378. var axis = ( new THREE.Vector3() ).cross( _rotateStart, _rotateEnd ).normalize(),
  4379. quaternion = new THREE.Quaternion();
  4380. angle *= _this.rotateSpeed;
  4381. quaternion.setFromAxisAngle( axis, -angle );
  4382. quaternion.multiplyVector3( _eye );
  4383. quaternion.multiplyVector3( _this.object.up );
  4384. quaternion.multiplyVector3( _rotateEnd );
  4385. if ( _this.staticMoving ) {
  4386. _rotateStart = _rotateEnd;
  4387. } else {
  4388. quaternion.setFromAxisAngle( axis, angle * ( _this.dynamicDampingFactor - 1.0 ) );
  4389. quaternion.multiplyVector3( _rotateStart );
  4390. }
  4391. }
  4392. };
  4393. this.zoomCamera = function () {
  4394. var factor = 1.0 + ( _zoomEnd.y - _zoomStart.y ) * _this.zoomSpeed;
  4395. if ( factor !== 1.0 && factor > 0.0 ) {
  4396. _eye.multiplyScalar( factor );
  4397. if ( _this.staticMoving ) {
  4398. _zoomStart = _zoomEnd;
  4399. } else {
  4400. _zoomStart.y += ( _zoomEnd.y - _zoomStart.y ) * this.dynamicDampingFactor;
  4401. }
  4402. }
  4403. };
  4404. this.panCamera = function () {
  4405. var mouseChange = _panEnd.clone().subSelf( _panStart );
  4406. if ( mouseChange.lengthSq() ) {
  4407. mouseChange.multiplyScalar( _eye.length() * _this.panSpeed );
  4408. var pan = _eye.clone().crossSelf( _this.object.up ).setLength( mouseChange.x );
  4409. pan.addSelf( _this.object.up.clone().setLength( mouseChange.y ) );
  4410. _this.object.position.addSelf( pan );
  4411. _this.target.addSelf( pan );
  4412. if ( _this.staticMoving ) {
  4413. _panStart = _panEnd;
  4414. } else {
  4415. _panStart.addSelf( mouseChange.sub( _panEnd, _panStart ).multiplyScalar( _this.dynamicDampingFactor ) );
  4416. }
  4417. }
  4418. };
  4419. this.checkDistances = function () {
  4420. if ( !_this.noZoom || !_this.noPan ) {
  4421. if ( _this.object.position.lengthSq() > _this.maxDistance * _this.maxDistance ) {
  4422. _this.object.position.setLength( _this.maxDistance );
  4423. }
  4424. if ( _eye.lengthSq() < _this.minDistance * _this.minDistance ) {
  4425. _this.object.position.add( _this.target, _eye.setLength( _this.minDistance ) );
  4426. }
  4427. }
  4428. };
  4429. this.update = function () {
  4430. _eye.copy( _this.object.position ).subSelf( _this.target );
  4431. if ( !_this.noRotate ) {
  4432. _this.rotateCamera();
  4433. }
  4434. if ( !_this.noZoom ) {
  4435. _this.zoomCamera();
  4436. }
  4437. if ( !_this.noPan ) {
  4438. _this.panCamera();
  4439. }
  4440. _this.object.position.add( _this.target, _eye );
  4441. _this.checkDistances();
  4442. _this.object.lookAt( _this.target );
  4443. if ( lastPosition.distanceTo( _this.object.position ) > 0 ) {
  4444. _this.dispatchEvent( changeEvent );
  4445. lastPosition.copy( _this.object.position );
  4446. }
  4447. };
  4448. // listeners
  4449. function keydown( event ) {
  4450. if ( ! _this.enabled ) return;
  4451. if ( _state !== STATE.NONE ) {
  4452. return;
  4453. } else if ( event.keyCode === _this.keys[ STATE.ROTATE ] && !_this.noRotate ) {
  4454. _state = STATE.ROTATE;
  4455. } else if ( event.keyCode === _this.keys[ STATE.ZOOM ] && !_this.noZoom ) {
  4456. _state = STATE.ZOOM;
  4457. } else if ( event.keyCode === _this.keys[ STATE.PAN ] && !_this.noPan ) {
  4458. _state = STATE.PAN;
  4459. }
  4460. if ( _state !== STATE.NONE ) {
  4461. _keyPressed = true;
  4462. }
  4463. };
  4464. function keyup( event ) {
  4465. if ( ! _this.enabled ) return;
  4466. if ( _state !== STATE.NONE ) {
  4467. _state = STATE.NONE;
  4468. }
  4469. };
  4470. function mousedown( event ) {
  4471. if ( ! _this.enabled ) return;
  4472. event.preventDefault();
  4473. event.stopPropagation();
  4474. if ( _state === STATE.NONE ) {
  4475. _state = event.button;
  4476. if ( _state === STATE.ROTATE && !_this.noRotate ) {
  4477. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  4478. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  4479. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4480. } else if ( !this.noPan ) {
  4481. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4482. }
  4483. }
  4484. };
  4485. function mousemove( event ) {
  4486. if ( ! _this.enabled ) return;
  4487. if ( _keyPressed ) {
  4488. _rotateStart = _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  4489. _zoomStart = _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4490. _panStart = _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4491. _keyPressed = false;
  4492. }
  4493. if ( _state === STATE.NONE ) {
  4494. return;
  4495. } else if ( _state === STATE.ROTATE && !_this.noRotate ) {
  4496. _rotateEnd = _this.getMouseProjectionOnBall( event.clientX, event.clientY );
  4497. } else if ( _state === STATE.ZOOM && !_this.noZoom ) {
  4498. _zoomEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4499. } else if ( _state === STATE.PAN && !_this.noPan ) {
  4500. _panEnd = _this.getMouseOnScreen( event.clientX, event.clientY );
  4501. }
  4502. };
  4503. function mouseup( event ) {
  4504. if ( ! _this.enabled ) return;
  4505. event.preventDefault();
  4506. event.stopPropagation();
  4507. _state = STATE.NONE;
  4508. };
  4509. this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false );
  4510. this.domElement.addEventListener( 'mousemove', mousemove, false );
  4511. this.domElement.addEventListener( 'mousedown', mousedown, false );
  4512. this.domElement.addEventListener( 'mouseup', mouseup, false );
  4513. window.addEventListener( 'keydown', keydown, false );
  4514. window.addEventListener( 'keyup', keyup, false );
  4515. };
  4516. /**
  4517. * @author mr.doob / http://mrdoob.com/
  4518. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Cube.as
  4519. */
  4520. THREE.CubeGeometry = function ( width, height, depth, segmentsWidth, segmentsHeight, segmentsDepth, materials, sides ) {
  4521. THREE.Geometry.call( this );
  4522. var scope = this,
  4523. width_half = width / 2,
  4524. height_half = height / 2,
  4525. depth_half = depth / 2;
  4526. var mpx, mpy, mpz, mnx, mny, mnz;
  4527. if ( materials !== undefined ) {
  4528. if ( materials instanceof Array ) {
  4529. this.materials = materials;
  4530. } else {
  4531. this.materials = [];
  4532. for ( var i = 0; i < 6; i ++ ) {
  4533. this.materials.push( materials );
  4534. }
  4535. }
  4536. mpx = 0; mnx = 1; mpy = 2; mny = 3; mpz = 4; mnz = 5;
  4537. } else {
  4538. this.materials = [];
  4539. }
  4540. this.sides = { px: true, nx: true, py: true, ny: true, pz: true, nz: true };
  4541. if ( sides != undefined ) {
  4542. for ( var s in sides ) {
  4543. if ( this.sides[ s ] !== undefined ) {
  4544. this.sides[ s ] = sides[ s ];
  4545. }
  4546. }
  4547. }
  4548. this.sides.px && buildPlane( 'z', 'y', - 1, - 1, depth, height, width_half, mpx ); // px
  4549. this.sides.nx && buildPlane( 'z', 'y', 1, - 1, depth, height, - width_half, mnx ); // nx
  4550. this.sides.py && buildPlane( 'x', 'z', 1, 1, width, depth, height_half, mpy ); // py
  4551. this.sides.ny && buildPlane( 'x', 'z', 1, - 1, width, depth, - height_half, mny ); // ny
  4552. this.sides.pz && buildPlane( 'x', 'y', 1, - 1, width, height, depth_half, mpz ); // pz
  4553. this.sides.nz && buildPlane( 'x', 'y', - 1, - 1, width, height, - depth_half, mnz ); // nz
  4554. function buildPlane( u, v, udir, vdir, width, height, depth, material ) {
  4555. var w, ix, iy,
  4556. gridX = segmentsWidth || 1,
  4557. gridY = segmentsHeight || 1,
  4558. width_half = width / 2,
  4559. height_half = height / 2,
  4560. offset = scope.vertices.length;
  4561. if ( ( u === 'x' && v === 'y' ) || ( u === 'y' && v === 'x' ) ) {
  4562. w = 'z';
  4563. } else if ( ( u === 'x' && v === 'z' ) || ( u === 'z' && v === 'x' ) ) {
  4564. w = 'y';
  4565. gridY = segmentsDepth || 1;
  4566. } else if ( ( u === 'z' && v === 'y' ) || ( u === 'y' && v === 'z' ) ) {
  4567. w = 'x';
  4568. gridX = segmentsDepth || 1;
  4569. }
  4570. var gridX1 = gridX + 1,
  4571. gridY1 = gridY + 1,
  4572. segment_width = width / gridX,
  4573. segment_height = height / gridY,
  4574. normal = new THREE.Vector3();
  4575. normal[ w ] = depth > 0 ? 1 : - 1;
  4576. for ( iy = 0; iy < gridY1; iy ++ ) {
  4577. for ( ix = 0; ix < gridX1; ix ++ ) {
  4578. var vector = new THREE.Vertex();
  4579. vector[ u ] = ( ix * segment_width - width_half ) * udir;
  4580. vector[ v ] = ( iy * segment_height - height_half ) * vdir;
  4581. vector[ w ] = depth;
  4582. scope.vertices.push( vector );
  4583. }
  4584. }
  4585. for ( iy = 0; iy < gridY; iy++ ) {
  4586. for ( ix = 0; ix < gridX; ix++ ) {
  4587. var a = ix + gridX1 * iy;
  4588. var b = ix + gridX1 * ( iy + 1 );
  4589. var c = ( ix + 1 ) + gridX1 * ( iy + 1 );
  4590. var d = ( ix + 1 ) + gridX1 * iy;
  4591. var face = new THREE.Face4( a + offset, b + offset, c + offset, d + offset );
  4592. face.normal.copy( normal );
  4593. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  4594. face.materialIndex = material;
  4595. scope.faces.push( face );
  4596. scope.faceVertexUvs[ 0 ].push( [
  4597. new THREE.UV( ix / gridX, iy / gridY ),
  4598. new THREE.UV( ix / gridX, ( iy + 1 ) / gridY ),
  4599. new THREE.UV( ( ix + 1 ) / gridX, ( iy + 1 ) / gridY ),
  4600. new THREE.UV( ( ix + 1 ) / gridX, iy / gridY )
  4601. ] );
  4602. }
  4603. }
  4604. }
  4605. this.computeCentroids();
  4606. this.mergeVertices();
  4607. };
  4608. THREE.CubeGeometry.prototype = new THREE.Geometry();
  4609. THREE.CubeGeometry.prototype.constructor = THREE.CubeGeometry;
  4610. /**
  4611. * @author mr.doob / http://mrdoob.com/
  4612. */
  4613. THREE.CylinderGeometry = function ( radiusTop, radiusBottom, height, segmentsRadius, segmentsHeight, openEnded ) {
  4614. THREE.Geometry.call( this );
  4615. radiusTop = radiusTop !== undefined ? radiusTop : 20;
  4616. radiusBottom = radiusBottom !== undefined ? radiusBottom : 20;
  4617. height = height !== undefined ? height : 100;
  4618. var heightHalf = height / 2;
  4619. var segmentsX = segmentsRadius || 8;
  4620. var segmentsY = segmentsHeight || 1;
  4621. var x, y, vertices = [], uvs = [];
  4622. for ( y = 0; y <= segmentsY; y ++ ) {
  4623. var verticesRow = [];
  4624. var uvsRow = [];
  4625. var v = y / segmentsY;
  4626. var radius = v * ( radiusBottom - radiusTop ) + radiusTop;
  4627. for ( x = 0; x <= segmentsX; x ++ ) {
  4628. var u = x / segmentsX;
  4629. var xpos = radius * Math.sin( u * Math.PI * 2 );
  4630. var ypos = - v * height + heightHalf;
  4631. var zpos = radius * Math.cos( u * Math.PI * 2 );
  4632. this.vertices.push( new THREE.Vertex( xpos, ypos, zpos ) );
  4633. verticesRow.push( this.vertices.length - 1 );
  4634. uvsRow.push( new THREE.UV( u, v ) );
  4635. }
  4636. vertices.push( verticesRow );
  4637. uvs.push( uvsRow );
  4638. }
  4639. for ( y = 0; y < segmentsY; y ++ ) {
  4640. for ( x = 0; x < segmentsX; x ++ ) {
  4641. var v1 = vertices[ y ][ x ];
  4642. var v2 = vertices[ y + 1 ][ x ];
  4643. var v3 = vertices[ y + 1 ][ x + 1 ];
  4644. var v4 = vertices[ y ][ x + 1 ];
  4645. // FIXME: These normals aren't right for cones.
  4646. var n1 = this.vertices[ v1 ].clone().setY( 0 ).normalize();
  4647. var n2 = this.vertices[ v2 ].clone().setY( 0 ).normalize();
  4648. var n3 = this.vertices[ v3 ].clone().setY( 0 ).normalize();
  4649. var n4 = this.vertices[ v4 ].clone().setY( 0 ).normalize();
  4650. var uv1 = uvs[ y ][ x ].clone();
  4651. var uv2 = uvs[ y + 1 ][ x ].clone();
  4652. var uv3 = uvs[ y + 1 ][ x + 1 ].clone();
  4653. var uv4 = uvs[ y ][ x + 1 ].clone();
  4654. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  4655. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  4656. }
  4657. }
  4658. // top cap
  4659. if ( !openEnded && radiusTop > 0 ) {
  4660. this.vertices.push( new THREE.Vertex( 0, heightHalf, 0 ) );
  4661. for ( x = 0; x < segmentsX; x ++ ) {
  4662. var v1 = vertices[ 0 ][ x ];
  4663. var v2 = vertices[ 0 ][ x + 1 ];
  4664. var v3 = this.vertices.length - 1;
  4665. var n1 = new THREE.Vector3( 0, 1, 0 );
  4666. var n2 = new THREE.Vector3( 0, 1, 0 );
  4667. var n3 = new THREE.Vector3( 0, 1, 0 );
  4668. var uv1 = uvs[ 0 ][ x ].clone();
  4669. var uv2 = uvs[ 0 ][ x + 1 ].clone();
  4670. var uv3 = new THREE.UV( uv2.u, 0 );
  4671. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  4672. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  4673. }
  4674. }
  4675. // bottom cap
  4676. if ( !openEnded && radiusBottom > 0 ) {
  4677. this.vertices.push( new THREE.Vertex( 0, - heightHalf, 0 ) );
  4678. for ( x = 0; x < segmentsX; x ++ ) {
  4679. var v1 = vertices[ y ][ x + 1 ];
  4680. var v2 = vertices[ y ][ x ];
  4681. var v3 = this.vertices.length - 1;
  4682. var n1 = new THREE.Vector3( 0, - 1, 0 );
  4683. var n2 = new THREE.Vector3( 0, - 1, 0 );
  4684. var n3 = new THREE.Vector3( 0, - 1, 0 );
  4685. var uv1 = uvs[ y ][ x + 1 ].clone();
  4686. var uv2 = uvs[ y ][ x ].clone();
  4687. var uv3 = new THREE.UV( uv2.u, 1 );
  4688. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  4689. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  4690. }
  4691. }
  4692. this.computeCentroids();
  4693. this.computeFaceNormals();
  4694. }
  4695. THREE.CylinderGeometry.prototype = new THREE.Geometry();
  4696. THREE.CylinderGeometry.prototype.constructor = THREE.CylinderGeometry;
  4697. /**
  4698. * @author zz85 / http://www.lab4games.net/zz85/blog
  4699. *
  4700. * Creates extruded geometry from a path shape.
  4701. *
  4702. * parameters = {
  4703. *
  4704. * size: <float>, // size of the text
  4705. * height: <float>, // thickness to extrude text
  4706. * curveSegments: <int>, // number of points on the curves
  4707. * steps: <int>, // number of points for z-side extrusions / used for subdividing segements of extrude spline too
  4708. amount: <int>, // Amount
  4709. *
  4710. * bevelEnabled: <bool>, // turn on bevel
  4711. * bevelThickness: <float>, // how deep into text bevel goes
  4712. * bevelSize: <float>, // how far from text outline is bevel
  4713. * bevelSegments: <int>, // number of bevel layers
  4714. *
  4715. * extrudePath: <THREE.CurvePath> // 2d/3d spline path to extrude shape orthogonality to
  4716. * bendPath: <THREE.CurvePath> // 2d path for bend the shape around x/y plane
  4717. *
  4718. * material: <int> // material index for front and back faces
  4719. * extrudeMaterial: <int> // material index for extrusion and beveled faces
  4720. *
  4721. * }
  4722. **/
  4723. THREE.ExtrudeGeometry = function( shapes, options ) {
  4724. if ( typeof( shapes ) === "undefined" ) {
  4725. shapes = [];
  4726. return;
  4727. }
  4728. THREE.Geometry.call( this );
  4729. shapes = shapes instanceof Array ? shapes : [ shapes ];
  4730. this.shapebb = shapes[ shapes.length - 1 ].getBoundingBox();
  4731. this.addShapeList( shapes, options );
  4732. this.computeCentroids();
  4733. this.computeFaceNormals();
  4734. // can't really use automatic vertex normals
  4735. // as then front and back sides get smoothed too
  4736. // should do separate smoothing just for sides
  4737. //this.computeVertexNormals();
  4738. //console.log( "took", ( Date.now() - startTime ) );
  4739. };
  4740. THREE.ExtrudeGeometry.prototype = new THREE.Geometry();
  4741. THREE.ExtrudeGeometry.prototype.constructor = THREE.ExtrudeGeometry;
  4742. THREE.ExtrudeGeometry.prototype.addShapeList = function(shapes, options) {
  4743. var sl = shapes.length;
  4744. for ( var s = 0; s < sl; s ++ ) {
  4745. var shape = shapes[ s ];
  4746. this.addShape( shape, options );
  4747. }
  4748. };
  4749. THREE.ExtrudeGeometry.prototype.addShape = function( shape, options ) {
  4750. var amount = options.amount !== undefined ? options.amount : 100;
  4751. var bevelThickness = options.bevelThickness !== undefined ? options.bevelThickness : 6; // 10
  4752. var bevelSize = options.bevelSize !== undefined ? options.bevelSize : bevelThickness - 2; // 8
  4753. var bevelSegments = options.bevelSegments !== undefined ? options.bevelSegments : 3;
  4754. var bevelEnabled = options.bevelEnabled !== undefined ? options.bevelEnabled : true; // false
  4755. var curveSegments = options.curveSegments !== undefined ? options.curveSegments : 12;
  4756. var steps = options.steps !== undefined ? options.steps : 1;
  4757. var bendPath = options.bendPath;
  4758. var extrudePath = options.extrudePath;
  4759. var extrudePts, extrudeByPath = false;
  4760. var material = options.material;
  4761. var extrudeMaterial = options.extrudeMaterial;
  4762. var shapebb = this.shapebb;
  4763. //shapebb = shape.getBoundingBox();
  4764. var splineTube, binormal, normal, position2;
  4765. if ( extrudePath ) {
  4766. extrudePts = extrudePath.getSpacedPoints( steps );
  4767. extrudeByPath = true;
  4768. bevelEnabled = false; // bevels not supported for path extrusion
  4769. // SETUP TNB variables
  4770. // Reuse TNB from TubeGeomtry for now.
  4771. // TODO1 - have a .isClosed in spline?
  4772. splineTube = new THREE.TubeGeometry.FrenetFrames(extrudePath, steps, false);
  4773. // console.log(splineTube, 'splineTube', splineTube.normals.length, 'steps', steps, 'extrudePts', extrudePts.length);
  4774. binormal = new THREE.Vector3();
  4775. normal = new THREE.Vector3();
  4776. position2 = new THREE.Vector3();
  4777. }
  4778. // Safeguards if bevels are not enabled
  4779. if ( ! bevelEnabled ) {
  4780. bevelSegments = 0;
  4781. bevelThickness = 0;
  4782. bevelSize = 0;
  4783. }
  4784. // Variables initalization
  4785. var ahole, h, hl; // looping of holes
  4786. var scope = this;
  4787. var bevelPoints = [];
  4788. var shapesOffset = this.vertices.length;
  4789. if ( bendPath ) {
  4790. shape.addWrapPath( bendPath );
  4791. }
  4792. var shapePoints = shape.extractPoints();
  4793. var vertices = shapePoints.shape;
  4794. var holes = shapePoints.holes;
  4795. var reverse = !THREE.Shape.Utils.isClockWise( vertices ) ;
  4796. if ( reverse ) {
  4797. vertices = vertices.reverse();
  4798. // Maybe we should also check if holes are in the opposite direction, just to be safe ...
  4799. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  4800. ahole = holes[ h ];
  4801. if ( THREE.Shape.Utils.isClockWise( ahole ) ) {
  4802. holes[ h ] = ahole.reverse();
  4803. }
  4804. }
  4805. reverse = false; // If vertices are in order now, we shouldn't need to worry about them again (hopefully)!
  4806. }
  4807. var faces = THREE.Shape.Utils.triangulateShape ( vertices, holes );
  4808. //var faces = THREE.Shape.Utils.triangulate2( vertices, holes );
  4809. // Would it be better to move points after triangulation?
  4810. // shapePoints = shape.extractAllPointsWithBend( curveSegments, bendPath );
  4811. // vertices = shapePoints.shape;
  4812. // holes = shapePoints.holes;
  4813. //console.log(faces);
  4814. ////
  4815. /// Handle Vertices
  4816. ////
  4817. var contour = vertices; // vertices has all points but contour has only points of circumference
  4818. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  4819. ahole = holes[ h ];
  4820. vertices = vertices.concat( ahole );
  4821. }
  4822. function scalePt2 ( pt, vec, size ) {
  4823. if ( !vec ) console.log( "die" );
  4824. return vec.clone().multiplyScalar( size ).addSelf( pt );
  4825. }
  4826. var b, bs, t, z,
  4827. vert, vlen = vertices.length,
  4828. face, flen = faces.length,
  4829. cont, clen = contour.length;
  4830. //------
  4831. // Find directions for point movement
  4832. //
  4833. var RAD_TO_DEGREES = 180 / Math.PI;
  4834. function getBevelVec( pt_i, pt_j, pt_k ) {
  4835. // Algorithm 2
  4836. return getBevelVec2( pt_i, pt_j, pt_k );
  4837. }
  4838. function getBevelVec1( pt_i, pt_j, pt_k ) {
  4839. var anglea = Math.atan2( pt_j.y - pt_i.y, pt_j.x - pt_i.x );
  4840. var angleb = Math.atan2( pt_k.y - pt_i.y, pt_k.x - pt_i.x );
  4841. if ( anglea > angleb ) {
  4842. angleb += Math.PI * 2;
  4843. }
  4844. var anglec = ( anglea + angleb ) / 2;
  4845. //console.log('angle1', anglea * RAD_TO_DEGREES,'angle2', angleb * RAD_TO_DEGREES, 'anglec', anglec *RAD_TO_DEGREES);
  4846. var x = - Math.cos( anglec );
  4847. var y = - Math.sin( anglec );
  4848. var vec = new THREE.Vector2( x, y ); //.normalize();
  4849. return vec;
  4850. }
  4851. function getBevelVec2( pt_i, pt_j, pt_k ) {
  4852. var a = THREE.ExtrudeGeometry.__v1,
  4853. b = THREE.ExtrudeGeometry.__v2,
  4854. v_hat = THREE.ExtrudeGeometry.__v3,
  4855. w_hat = THREE.ExtrudeGeometry.__v4,
  4856. p = THREE.ExtrudeGeometry.__v5,
  4857. q = THREE.ExtrudeGeometry.__v6,
  4858. v, w,
  4859. v_dot_w_hat, q_sub_p_dot_w_hat,
  4860. s, intersection;
  4861. // good reading for line-line intersection
  4862. // http://sputsoft.com/blog/2010/03/line-line-intersection.html
  4863. // define a as vector j->i
  4864. // define b as vectot k->i
  4865. a.set( pt_i.x - pt_j.x, pt_i.y - pt_j.y );
  4866. b.set( pt_i.x - pt_k.x, pt_i.y - pt_k.y );
  4867. // get unit vectors
  4868. v = a.normalize();
  4869. w = b.normalize();
  4870. // normals from pt i
  4871. v_hat.set( -v.y, v.x );
  4872. w_hat.set( w.y, -w.x );
  4873. // pts from i
  4874. p.copy( pt_i ).addSelf( v_hat );
  4875. q.copy( pt_i ).addSelf( w_hat );
  4876. if ( p.equals( q ) ) {
  4877. //console.log("Warning: lines are straight");
  4878. return w_hat.clone();
  4879. }
  4880. // Points from j, k. helps prevents points cross overover most of the time
  4881. p.copy( pt_j ).addSelf( v_hat );
  4882. q.copy( pt_k ).addSelf( w_hat );
  4883. v_dot_w_hat = v.dot( w_hat );
  4884. q_sub_p_dot_w_hat = q.subSelf( p ).dot( w_hat );
  4885. // We should not reach these conditions
  4886. if ( v_dot_w_hat === 0 ) {
  4887. console.log( "Either infinite or no solutions!" );
  4888. if ( q_sub_p_dot_w_hat === 0 ) {
  4889. console.log( "Its finite solutions." );
  4890. } else {
  4891. console.log( "Too bad, no solutions." );
  4892. }
  4893. }
  4894. s = q_sub_p_dot_w_hat / v_dot_w_hat;
  4895. if ( s < 0 ) {
  4896. // in case of emergecy, revert to algorithm 1.
  4897. return getBevelVec1( pt_i, pt_j, pt_k );
  4898. }
  4899. intersection = v.multiplyScalar( s ).addSelf( p );
  4900. return intersection.subSelf( pt_i ).clone(); // Don't normalize!, otherwise sharp corners become ugly
  4901. }
  4902. var contourMovements = [];
  4903. for ( var i = 0, il = contour.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  4904. if ( j === il ) j = 0;
  4905. if ( k === il ) k = 0;
  4906. // (j)---(i)---(k)
  4907. // console.log('i,j,k', i, j , k)
  4908. var pt_i = contour[ i ];
  4909. var pt_j = contour[ j ];
  4910. var pt_k = contour[ k ];
  4911. contourMovements[ i ]= getBevelVec( contour[ i ], contour[ j ], contour[ k ] );
  4912. }
  4913. var holesMovements = [], oneHoleMovements, verticesMovements = contourMovements.concat();
  4914. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  4915. ahole = holes[ h ];
  4916. oneHoleMovements = [];
  4917. for ( i = 0, il = ahole.length, j = il - 1, k = i + 1; i < il; i ++, j ++, k ++ ) {
  4918. if ( j === il ) j = 0;
  4919. if ( k === il ) k = 0;
  4920. // (j)---(i)---(k)
  4921. oneHoleMovements[ i ]= getBevelVec( ahole[ i ], ahole[ j ], ahole[ k ] );
  4922. }
  4923. holesMovements.push( oneHoleMovements );
  4924. verticesMovements = verticesMovements.concat( oneHoleMovements );
  4925. }
  4926. // Loop bevelSegments, 1 for the front, 1 for the back
  4927. for ( b = 0; b < bevelSegments; b ++ ) {
  4928. //for ( b = bevelSegments; b > 0; b -- ) {
  4929. t = b / bevelSegments;
  4930. z = bevelThickness * ( 1 - t );
  4931. //z = bevelThickness * t;
  4932. bs = bevelSize * ( Math.sin ( t * Math.PI/2 ) ) ; // curved
  4933. //bs = bevelSize * t ; // linear
  4934. // contract shape
  4935. for ( i = 0, il = contour.length; i < il; i ++ ) {
  4936. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  4937. //vert = scalePt( contour[ i ], contourCentroid, bs, false );
  4938. v( vert.x, vert.y, - z );
  4939. }
  4940. // expand holes
  4941. for ( h = 0, hl = holes.length; h < hl; h++ ) {
  4942. ahole = holes[ h ];
  4943. oneHoleMovements = holesMovements[ h ];
  4944. for ( i = 0, il = ahole.length; i < il; i++ ) {
  4945. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  4946. //vert = scalePt( ahole[ i ], holesCentroids[ h ], bs, true );
  4947. v( vert.x, vert.y, -z );
  4948. }
  4949. }
  4950. }
  4951. bs = bevelSize;
  4952. // Back facing vertices
  4953. for ( i = 0; i < vlen; i ++ ) {
  4954. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  4955. if ( !extrudeByPath ) {
  4956. v( vert.x, vert.y, 0 );
  4957. } else {
  4958. // v( vert.x, vert.y + extrudePts[ 0 ].y, extrudePts[ 0 ].x );
  4959. normal.copy(splineTube.normals[0]).multiplyScalar(vert.x);
  4960. binormal.copy(splineTube.binormals[0]).multiplyScalar(vert.y);
  4961. position2.copy(extrudePts[0]).addSelf(normal).addSelf(binormal);
  4962. v(position2.x, position2.y, position2.z);
  4963. }
  4964. }
  4965. // Add stepped vertices...
  4966. // Including front facing vertices
  4967. var s;
  4968. for ( s = 1; s <= steps; s ++ ) {
  4969. for ( i = 0; i < vlen; i ++ ) {
  4970. vert = bevelEnabled ? scalePt2( vertices[ i ], verticesMovements[ i ], bs ) : vertices[ i ];
  4971. if ( !extrudeByPath ) {
  4972. v( vert.x, vert.y, amount / steps * s );
  4973. } else {
  4974. // v( vert.x, vert.y + extrudePts[ s - 1 ].y, extrudePts[ s - 1 ].x );
  4975. normal.copy(splineTube.normals[s]).multiplyScalar(vert.x);
  4976. binormal.copy(splineTube.binormals[s]).multiplyScalar(vert.y);
  4977. position2.copy(extrudePts[s]).addSelf(normal).addSelf(binormal);
  4978. v(position2.x, position2.y, position2.z );
  4979. }
  4980. }
  4981. }
  4982. // Add bevel segments planes
  4983. //for ( b = 1; b <= bevelSegments; b ++ ) {
  4984. for ( b = bevelSegments - 1; b >= 0; b -- ) {
  4985. t = b / bevelSegments;
  4986. z = bevelThickness * ( 1 - t );
  4987. //bs = bevelSize * ( 1-Math.sin ( ( 1 - t ) * Math.PI/2 ) );
  4988. bs = bevelSize * Math.sin ( t * Math.PI/2 ) ;
  4989. // contract shape
  4990. for ( i = 0, il = contour.length; i < il; i ++ ) {
  4991. vert = scalePt2( contour[ i ], contourMovements[ i ], bs );
  4992. v( vert.x, vert.y, amount + z );
  4993. }
  4994. // expand holes
  4995. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  4996. ahole = holes[ h ];
  4997. oneHoleMovements = holesMovements[ h ];
  4998. for ( i = 0, il = ahole.length; i < il; i++ ) {
  4999. vert = scalePt2( ahole[ i ], oneHoleMovements[ i ], bs );
  5000. if ( !extrudeByPath ) {
  5001. v( vert.x, vert.y, amount + z );
  5002. } else {
  5003. v( vert.x, vert.y + extrudePts[ steps - 1 ].y, extrudePts[ steps - 1 ].x + z );
  5004. }
  5005. }
  5006. }
  5007. }
  5008. // set UV generator
  5009. var uvgen = THREE.ExtrudeGeometry.WorldUVGenerator;
  5010. ////
  5011. /// Handle Faces
  5012. ////
  5013. // Top and bottom faces
  5014. buildLidFaces();
  5015. // Sides faces
  5016. buildSideFaces();
  5017. ///// Internal functions
  5018. function buildLidFaces() {
  5019. if ( bevelEnabled ) {
  5020. var layer = 0 ; // steps + 1
  5021. var offset = vlen * layer;
  5022. // Bottom faces
  5023. for ( i = 0; i < flen; i ++ ) {
  5024. face = faces[ i ];
  5025. f3( face[ 2 ]+ offset, face[ 1 ]+ offset, face[ 0 ] + offset, true );
  5026. }
  5027. layer = steps + bevelSegments * 2;
  5028. offset = vlen * layer;
  5029. // Top faces
  5030. for ( i = 0; i < flen; i ++ ) {
  5031. face = faces[ i ];
  5032. f3( face[ 0 ] + offset, face[ 1 ] + offset, face[ 2 ] + offset, false );
  5033. }
  5034. } else {
  5035. // Bottom faces
  5036. for ( i = 0; i < flen; i++ ) {
  5037. face = faces[ i ];
  5038. f3( face[ 2 ], face[ 1 ], face[ 0 ], true );
  5039. }
  5040. // Top faces
  5041. for ( i = 0; i < flen; i ++ ) {
  5042. face = faces[ i ];
  5043. f3( face[ 0 ] + vlen * steps, face[ 1 ] + vlen * steps, face[ 2 ] + vlen * steps, false );
  5044. }
  5045. }
  5046. }
  5047. // Create faces for the z-sides of the shape
  5048. function buildSideFaces() {
  5049. var layeroffset = 0;
  5050. sidewalls( contour, layeroffset );
  5051. layeroffset += contour.length;
  5052. for ( h = 0, hl = holes.length; h < hl; h ++ ) {
  5053. ahole = holes[ h ];
  5054. sidewalls( ahole, layeroffset );
  5055. //, true
  5056. layeroffset += ahole.length;
  5057. }
  5058. }
  5059. function sidewalls( contour, layeroffset ) {
  5060. var j, k;
  5061. i = contour.length;
  5062. while ( --i >= 0 ) {
  5063. j = i;
  5064. k = i - 1;
  5065. if ( k < 0 ) k = contour.length - 1;
  5066. //console.log('b', i,j, i-1, k,vertices.length);
  5067. var s = 0, sl = steps + bevelSegments * 2;
  5068. for ( s = 0; s < sl; s ++ ) {
  5069. var slen1 = vlen * s;
  5070. var slen2 = vlen * ( s + 1 );
  5071. var a = layeroffset + j + slen1,
  5072. b = layeroffset + k + slen1,
  5073. c = layeroffset + k + slen2,
  5074. d = layeroffset + j + slen2;
  5075. f4( a, b, c, d, contour, s, sl );
  5076. }
  5077. }
  5078. }
  5079. function v( x, y, z ) {
  5080. scope.vertices.push( new THREE.Vertex( x, y, z ) );
  5081. }
  5082. function f3( a, b, c, isBottom ) {
  5083. a += shapesOffset;
  5084. b += shapesOffset;
  5085. c += shapesOffset;
  5086. // normal, color, material
  5087. scope.faces.push( new THREE.Face3( a, b, c, null, null, material ) );
  5088. var uvs = isBottom ? uvgen.generateBottomUV( scope, shape, options, a, b, c)
  5089. : uvgen.generateTopUV( scope, shape, options, a, b, c);
  5090. scope.faceVertexUvs[ 0 ].push(uvs);
  5091. }
  5092. function f4( a, b, c, d, wallContour, stepIndex, stepsLength ) {
  5093. a += shapesOffset;
  5094. b += shapesOffset;
  5095. c += shapesOffset;
  5096. d += shapesOffset;
  5097. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, extrudeMaterial ) );
  5098. var uvs = uvgen.generateSideWallUV( scope, shape, wallContour, options, a, b, c, d, stepIndex, stepsLength);
  5099. scope.faceVertexUvs[ 0 ].push(uvs);
  5100. }
  5101. };
  5102. THREE.ExtrudeGeometry.WorldUVGenerator = {
  5103. generateTopUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  5104. var ax = geometry.vertices[ indexA ].x,
  5105. ay = geometry.vertices[ indexA ].y,
  5106. bx = geometry.vertices[ indexB ].x,
  5107. by = geometry.vertices[ indexB ].y,
  5108. cx = geometry.vertices[ indexC ].x,
  5109. cy = geometry.vertices[ indexC ].y;
  5110. return [
  5111. new THREE.UV( ax, 1 - ay ),
  5112. new THREE.UV( bx, 1 - by ),
  5113. new THREE.UV( cx, 1 - cy )
  5114. ];
  5115. },
  5116. generateBottomUV: function( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC) {
  5117. return this.generateTopUV( geometry, extrudedShape, extrudeOptions, indexA, indexB, indexC );
  5118. },
  5119. generateSideWallUV: function( geometry, extrudedShape, wallContour, extrudeOptions,
  5120. indexA, indexB, indexC, indexD, stepIndex, stepsLength) {
  5121. var ax = geometry.vertices[ indexA ].x,
  5122. ay = geometry.vertices[ indexA ].y,
  5123. az = geometry.vertices[ indexA ].z,
  5124. bx = geometry.vertices[ indexB ].x,
  5125. by = geometry.vertices[ indexB ].y,
  5126. bz = geometry.vertices[ indexB ].z,
  5127. cx = geometry.vertices[ indexC ].x,
  5128. cy = geometry.vertices[ indexC ].y,
  5129. cz = geometry.vertices[ indexC ].z,
  5130. dx = geometry.vertices[ indexD ].x,
  5131. dy = geometry.vertices[ indexD ].y,
  5132. dz = geometry.vertices[ indexD ].z;
  5133. if ( Math.abs( ay - by ) < 0.01 ) {
  5134. return [
  5135. new THREE.UV( ax, az ),
  5136. new THREE.UV( bx, bz ),
  5137. new THREE.UV( cx, cz ),
  5138. new THREE.UV( dx, dz )
  5139. ];
  5140. } else {
  5141. return [
  5142. new THREE.UV( ay, az ),
  5143. new THREE.UV( by, bz ),
  5144. new THREE.UV( cy, cz ),
  5145. new THREE.UV( dy, dz )
  5146. ];
  5147. }
  5148. }
  5149. };
  5150. THREE.ExtrudeGeometry.__v1 = new THREE.Vector2();
  5151. THREE.ExtrudeGeometry.__v2 = new THREE.Vector2();
  5152. THREE.ExtrudeGeometry.__v3 = new THREE.Vector2();
  5153. THREE.ExtrudeGeometry.__v4 = new THREE.Vector2();
  5154. THREE.ExtrudeGeometry.__v5 = new THREE.Vector2();
  5155. THREE.ExtrudeGeometry.__v6 = new THREE.Vector2();
  5156. /**
  5157. * @author astrodud / http://astrodud.isgreat.org/
  5158. * @author zz85 / https://github.com/zz85
  5159. */
  5160. THREE.LatheGeometry = function ( points, steps, angle ) {
  5161. THREE.Geometry.call( this );
  5162. var _steps = steps || 12;
  5163. var _angle = angle || 2 * Math.PI;
  5164. var _newV = [];
  5165. var _matrix = new THREE.Matrix4().makeRotationZ( _angle / _steps );
  5166. for ( var j = 0; j < points.length; j ++ ) {
  5167. _newV[ j ] = points[ j ].clone();
  5168. this.vertices.push( new THREE.Vertex().copy( _newV[ j ] ) );
  5169. }
  5170. var i;
  5171. var il = _steps + 1;
  5172. for ( i = 0; i < il; i ++ ) {
  5173. for ( var j = 0; j < _newV.length; j ++ ) {
  5174. _newV[ j ] = _matrix.multiplyVector3( _newV[ j ].clone() );
  5175. this.vertices.push( new THREE.Vertex().copy( _newV[ j ] ) );
  5176. }
  5177. }
  5178. for ( i = 0; i < _steps; i ++ ) {
  5179. for ( var k = 0, kl = points.length; k < kl - 1; k ++ ) {
  5180. var a = i * kl + k;
  5181. var b = ( ( i + 1 ) % il ) * kl + k;
  5182. var c = ( ( i + 1 ) % il ) * kl + ( k + 1 ) % kl;
  5183. var d = i * kl + ( k + 1 ) % kl;
  5184. this.faces.push( new THREE.Face4( a, b, c, d ) );
  5185. this.faceVertexUvs[ 0 ].push( [
  5186. new THREE.UV( 1 - i / _steps, k / kl ),
  5187. new THREE.UV( 1 - ( i + 1 ) / _steps, k / kl ),
  5188. new THREE.UV( 1 - ( i + 1 ) / _steps, ( k + 1 ) / kl ),
  5189. new THREE.UV( 1 - i / _steps, ( k + 1 ) / kl )
  5190. ] );
  5191. }
  5192. }
  5193. this.computeCentroids();
  5194. this.computeFaceNormals();
  5195. this.computeVertexNormals();
  5196. };
  5197. THREE.LatheGeometry.prototype = new THREE.Geometry();
  5198. THREE.LatheGeometry.prototype.constructor = THREE.LatheGeometry;
  5199. /**
  5200. * @author mr.doob / http://mrdoob.com/
  5201. * based on http://papervision3d.googlecode.com/svn/trunk/as3/trunk/src/org/papervision3d/objects/primitives/Plane.as
  5202. */
  5203. THREE.PlaneGeometry = function ( width, depth, segmentsWidth, segmentsDepth ) {
  5204. THREE.Geometry.call( this );
  5205. var ix, iz,
  5206. width_half = width / 2,
  5207. depth_half = depth / 2,
  5208. gridX = segmentsWidth || 1,
  5209. gridZ = segmentsDepth || 1,
  5210. gridX1 = gridX + 1,
  5211. gridZ1 = gridZ + 1,
  5212. segment_width = width / gridX,
  5213. segment_depth = depth / gridZ,
  5214. normal = new THREE.Vector3( 0, 1, 0 );
  5215. for ( iz = 0; iz < gridZ1; iz ++ ) {
  5216. for ( ix = 0; ix < gridX1; ix ++ ) {
  5217. var x = ix * segment_width - width_half;
  5218. var z = iz * segment_depth - depth_half;
  5219. this.vertices.push( new THREE.Vertex( x, 0, z ) );
  5220. }
  5221. }
  5222. for ( iz = 0; iz < gridZ; iz ++ ) {
  5223. for ( ix = 0; ix < gridX; ix ++ ) {
  5224. var a = ix + gridX1 * iz;
  5225. var b = ix + gridX1 * ( iz + 1 );
  5226. var c = ( ix + 1 ) + gridX1 * ( iz + 1 );
  5227. var d = ( ix + 1 ) + gridX1 * iz;
  5228. var face = new THREE.Face4( a, b, c, d );
  5229. face.normal.copy( normal );
  5230. face.vertexNormals.push( normal.clone(), normal.clone(), normal.clone(), normal.clone() );
  5231. this.faces.push( face );
  5232. this.faceVertexUvs[ 0 ].push( [
  5233. new THREE.UV( ix / gridX, iz / gridZ ),
  5234. new THREE.UV( ix / gridX, ( iz + 1 ) / gridZ ),
  5235. new THREE.UV( ( ix + 1 ) / gridX, ( iz + 1 ) / gridZ ),
  5236. new THREE.UV( ( ix + 1 ) / gridX, iz / gridZ )
  5237. ] );
  5238. }
  5239. }
  5240. this.computeCentroids();
  5241. };
  5242. THREE.PlaneGeometry.prototype = new THREE.Geometry();
  5243. THREE.PlaneGeometry.prototype.constructor = THREE.PlaneGeometry;
  5244. /**
  5245. * @author mr.doob / http://mrdoob.com/
  5246. */
  5247. THREE.SphereGeometry = function ( radius, segmentsWidth, segmentsHeight, phiStart, phiLength, thetaStart, thetaLength ) {
  5248. THREE.Geometry.call( this );
  5249. radius = radius || 50;
  5250. phiStart = phiStart !== undefined ? phiStart : 0;
  5251. phiLength = phiLength !== undefined ? phiLength : Math.PI * 2;
  5252. thetaStart = thetaStart !== undefined ? thetaStart : 0;
  5253. thetaLength = thetaLength !== undefined ? thetaLength : Math.PI;
  5254. var segmentsX = Math.max( 3, Math.floor( segmentsWidth ) || 8 );
  5255. var segmentsY = Math.max( 2, Math.floor( segmentsHeight ) || 6 );
  5256. var x, y, vertices = [], uvs = [];
  5257. for ( y = 0; y <= segmentsY; y ++ ) {
  5258. var verticesRow = [];
  5259. var uvsRow = [];
  5260. for ( x = 0; x <= segmentsX; x ++ ) {
  5261. var u = x / segmentsX;
  5262. var v = y / segmentsY;
  5263. var xpos = - radius * Math.cos( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  5264. var ypos = radius * Math.cos( thetaStart + v * thetaLength );
  5265. var zpos = radius * Math.sin( phiStart + u * phiLength ) * Math.sin( thetaStart + v * thetaLength );
  5266. this.vertices.push( new THREE.Vertex( xpos, ypos, zpos ) );
  5267. verticesRow.push( this.vertices.length - 1 );
  5268. uvsRow.push( new THREE.UV( u, v ) );
  5269. }
  5270. vertices.push( verticesRow );
  5271. uvs.push( uvsRow );
  5272. }
  5273. for ( y = 0; y < segmentsY; y ++ ) {
  5274. for ( x = 0; x < segmentsX; x ++ ) {
  5275. var v1 = vertices[ y ][ x + 1 ];
  5276. var v2 = vertices[ y ][ x ];
  5277. var v3 = vertices[ y + 1 ][ x ];
  5278. var v4 = vertices[ y + 1 ][ x + 1 ];
  5279. var n1 = this.vertices[ v1 ].clone().normalize();
  5280. var n2 = this.vertices[ v2 ].clone().normalize();
  5281. var n3 = this.vertices[ v3 ].clone().normalize();
  5282. var n4 = this.vertices[ v4 ].clone().normalize();
  5283. var uv1 = uvs[ y ][ x + 1 ].clone();
  5284. var uv2 = uvs[ y ][ x ].clone();
  5285. var uv3 = uvs[ y + 1 ][ x ].clone();
  5286. var uv4 = uvs[ y + 1 ][ x + 1 ].clone();
  5287. if ( Math.abs( this.vertices[ v1 ].y ) == radius ) {
  5288. this.faces.push( new THREE.Face3( v1, v3, v4, [ n1, n3, n4 ] ) );
  5289. this.faceVertexUvs[ 0 ].push( [ uv1, uv3, uv4 ] );
  5290. } else if ( Math.abs( this.vertices[ v3 ].y ) == radius ) {
  5291. this.faces.push( new THREE.Face3( v1, v2, v3, [ n1, n2, n3 ] ) );
  5292. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3 ] );
  5293. } else {
  5294. this.faces.push( new THREE.Face4( v1, v2, v3, v4, [ n1, n2, n3, n4 ] ) );
  5295. this.faceVertexUvs[ 0 ].push( [ uv1, uv2, uv3, uv4 ] );
  5296. }
  5297. }
  5298. }
  5299. this.computeCentroids();
  5300. this.computeFaceNormals();
  5301. this.boundingSphere = { radius: radius };
  5302. };
  5303. THREE.SphereGeometry.prototype = new THREE.Geometry();
  5304. THREE.SphereGeometry.prototype.constructor = THREE.SphereGeometry;
  5305. /**
  5306. * @author zz85 / http://www.lab4games.net/zz85/blog
  5307. * @author alteredq / http://alteredqualia.com/
  5308. *
  5309. * For creating 3D text geometry in three.js
  5310. *
  5311. * Text = 3D Text
  5312. *
  5313. * parameters = {
  5314. * size: <float>, // size of the text
  5315. * height: <float>, // thickness to extrude text
  5316. * curveSegments: <int>, // number of points on the curves
  5317. *
  5318. * font: <string>, // font name
  5319. * weight: <string>, // font weight (normal, bold)
  5320. * style: <string>, // font style (normal, italics)
  5321. *
  5322. * bevelEnabled: <bool>, // turn on bevel
  5323. * bevelThickness: <float>, // how deep into text bevel goes
  5324. * bevelSize: <float>, // how far from text outline is bevel
  5325. *
  5326. * bend: <bool> // bend according to hardcoded curve (generates bendPath)
  5327. * bendPath: <curve> // wraps text according to bend Path
  5328. * }
  5329. *
  5330. * It uses techniques used in:
  5331. *
  5332. * typeface.js and canvastext
  5333. * For converting fonts and rendering with javascript
  5334. * http://typeface.neocracy.org
  5335. *
  5336. * Triangulation ported from AS3
  5337. * Simple Polygon Triangulation
  5338. * http://actionsnippet.com/?p=1462
  5339. *
  5340. * A Method to triangulate shapes with holes
  5341. * http://www.sakri.net/blog/2009/06/12/an-approach-to-triangulating-polygons-with-holes/
  5342. *
  5343. */
  5344. /* Usage Examples
  5345. // TextGeometry wrapper
  5346. var text3d = new TextGeometry( text, options );
  5347. // Complete manner
  5348. var textPath = new THREE.TextPath( text, options );
  5349. var textShapes = textPath.toShapes();
  5350. var text3d = new ExtrudeGeometry( textShapes, options );
  5351. */
  5352. THREE.TextGeometry = function ( text, parameters ) {
  5353. var textPath = new THREE.TextPath( text, parameters );
  5354. var textShapes = textPath.toShapes();
  5355. // translate parameters to ExtrudeGeometry API
  5356. parameters.amount = parameters.height !== undefined ? parameters.height : 50;
  5357. // defaults
  5358. if ( parameters.bevelThickness === undefined ) parameters.bevelThickness = 10;
  5359. if ( parameters.bevelSize === undefined ) parameters.bevelSize = 8;
  5360. if ( parameters.bevelEnabled === undefined ) parameters.bevelEnabled = false;
  5361. if ( parameters.bend ) {
  5362. var b = textShapes[ textShapes.length - 1 ].getBoundingBox();
  5363. var max = b.maxX;
  5364. parameters.bendPath = new THREE.QuadraticBezierCurve( new THREE.Vector2( 0, 0 ),
  5365. new THREE.Vector2( max / 2, 120 ),
  5366. new THREE.Vector2( max, 0 ) );
  5367. }
  5368. THREE.ExtrudeGeometry.call( this, textShapes, parameters );
  5369. };
  5370. THREE.TextGeometry.prototype = new THREE.ExtrudeGeometry();
  5371. THREE.TextGeometry.prototype.constructor = THREE.TextGeometry;
  5372. THREE.FontUtils = {
  5373. faces : {},
  5374. // Just for now. face[weight][style]
  5375. face : "helvetiker",
  5376. weight: "normal",
  5377. style : "normal",
  5378. size : 150,
  5379. divisions : 10,
  5380. getFace : function() {
  5381. return this.faces[ this.face ][ this.weight ][ this.style ];
  5382. },
  5383. loadFace : function( data ) {
  5384. var family = data.familyName.toLowerCase();
  5385. var ThreeFont = this;
  5386. ThreeFont.faces[ family ] = ThreeFont.faces[ family ] || {};
  5387. ThreeFont.faces[ family ][ data.cssFontWeight ] = ThreeFont.faces[ family ][ data.cssFontWeight ] || {};
  5388. ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  5389. var face = ThreeFont.faces[ family ][ data.cssFontWeight ][ data.cssFontStyle ] = data;
  5390. return data;
  5391. },
  5392. drawText : function( text ) {
  5393. var characterPts = [], allPts = [];
  5394. // RenderText
  5395. var i, p,
  5396. face = this.getFace(),
  5397. scale = this.size / face.resolution,
  5398. offset = 0,
  5399. chars = String( text ).split( '' ),
  5400. length = chars.length;
  5401. var fontPaths = [];
  5402. for ( i = 0; i < length; i ++ ) {
  5403. var path = new THREE.Path();
  5404. var ret = this.extractGlyphPoints( chars[ i ], face, scale, offset, path );
  5405. offset += ret.offset;
  5406. //characterPts.push( ret.points );
  5407. //allPts = allPts.concat( ret.points );
  5408. fontPaths.push( ret.path );
  5409. }
  5410. // get the width
  5411. var width = offset / 2;
  5412. //
  5413. // for ( p = 0; p < allPts.length; p++ ) {
  5414. //
  5415. // allPts[ p ].x -= width;
  5416. //
  5417. // }
  5418. //var extract = this.extractPoints( allPts, characterPts );
  5419. //extract.contour = allPts;
  5420. //extract.paths = fontPaths;
  5421. //extract.offset = width;
  5422. return { paths : fontPaths, offset : width };
  5423. },
  5424. extractGlyphPoints : function( c, face, scale, offset, path ) {
  5425. var pts = [];
  5426. var i, i2, divisions,
  5427. outline, action, length,
  5428. scaleX, scaleY,
  5429. x, y, cpx, cpy, cpx0, cpy0, cpx1, cpy1, cpx2, cpy2,
  5430. laste,
  5431. glyph = face.glyphs[ c ] || face.glyphs[ '?' ];
  5432. if ( !glyph ) return;
  5433. if ( glyph.o ) {
  5434. outline = glyph._cachedOutline || ( glyph._cachedOutline = glyph.o.split( ' ' ) );
  5435. length = outline.length;
  5436. scaleX = scale;
  5437. scaleY = scale;
  5438. for ( i = 0; i < length; ) {
  5439. action = outline[ i ++ ];
  5440. //console.log( action );
  5441. switch( action ) {
  5442. case 'm':
  5443. // Move To
  5444. x = outline[ i++ ] * scaleX + offset;
  5445. y = outline[ i++ ] * scaleY;
  5446. pts.push( new THREE.Vector2( x, y ) );
  5447. path.moveTo( x, y );
  5448. break;
  5449. case 'l':
  5450. // Line To
  5451. x = outline[ i++ ] * scaleX + offset;
  5452. y = outline[ i++ ] * scaleY;
  5453. pts.push( new THREE.Vector2( x, y ) );
  5454. path.lineTo(x,y);
  5455. break;
  5456. case 'q':
  5457. // QuadraticCurveTo
  5458. cpx = outline[ i++ ] * scaleX + offset;
  5459. cpy = outline[ i++ ] * scaleY;
  5460. cpx1 = outline[ i++ ] * scaleX + offset;
  5461. cpy1 = outline[ i++ ] * scaleY;
  5462. path.quadraticCurveTo(cpx1, cpy1, cpx, cpy);
  5463. laste = pts[ pts.length - 1 ];
  5464. if ( laste ) {
  5465. cpx0 = laste.x;
  5466. cpy0 = laste.y;
  5467. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  5468. var t = i2 / divisions;
  5469. var tx = THREE.Shape.Utils.b2( t, cpx0, cpx1, cpx );
  5470. var ty = THREE.Shape.Utils.b2( t, cpy0, cpy1, cpy );
  5471. pts.push( new THREE.Vector2( tx, ty ) );
  5472. }
  5473. }
  5474. break;
  5475. case 'b':
  5476. // Cubic Bezier Curve
  5477. cpx = outline[ i++ ] * scaleX + offset;
  5478. cpy = outline[ i++ ] * scaleY;
  5479. cpx1 = outline[ i++ ] * scaleX + offset;
  5480. cpy1 = outline[ i++ ] * -scaleY;
  5481. cpx2 = outline[ i++ ] * scaleX + offset;
  5482. cpy2 = outline[ i++ ] * -scaleY;
  5483. path.bezierCurveTo( cpx, cpy, cpx1, cpy1, cpx2, cpy2 );
  5484. laste = pts[ pts.length - 1 ];
  5485. if ( laste ) {
  5486. cpx0 = laste.x;
  5487. cpy0 = laste.y;
  5488. for ( i2 = 1, divisions = this.divisions; i2 <= divisions; i2 ++ ) {
  5489. var t = i2 / divisions;
  5490. var tx = THREE.Shape.Utils.b3( t, cpx0, cpx1, cpx2, cpx );
  5491. var ty = THREE.Shape.Utils.b3( t, cpy0, cpy1, cpy2, cpy );
  5492. pts.push( new THREE.Vector2( tx, ty ) );
  5493. }
  5494. }
  5495. break;
  5496. }
  5497. }
  5498. }
  5499. return { offset: glyph.ha*scale, points:pts, path:path};
  5500. }
  5501. };
  5502. /**
  5503. * This code is a quick port of code written in C++ which was submitted to
  5504. * flipcode.com by John W. Ratcliff // July 22, 2000
  5505. * See original code and more information here:
  5506. * http://www.flipcode.com/archives/Efficient_Polygon_Triangulation.shtml
  5507. *
  5508. * ported to actionscript by Zevan Rosser
  5509. * www.actionsnippet.com
  5510. *
  5511. * ported to javascript by Joshua Koo
  5512. * http://www.lab4games.net/zz85/blog
  5513. *
  5514. */
  5515. ( function( namespace ) {
  5516. var EPSILON = 0.0000000001;
  5517. // takes in an contour array and returns
  5518. var process = function( contour, indices ) {
  5519. var n = contour.length;
  5520. if ( n < 3 ) return null;
  5521. var result = [],
  5522. verts = [],
  5523. vertIndices = [];
  5524. /* we want a counter-clockwise polygon in verts */
  5525. var u, v, w;
  5526. if ( area( contour ) > 0.0 ) {
  5527. for ( v = 0; v < n; v++ ) verts[ v ] = v;
  5528. } else {
  5529. for ( v = 0; v < n; v++ ) verts[ v ] = ( n - 1 ) - v;
  5530. }
  5531. var nv = n;
  5532. /* remove nv - 2 vertices, creating 1 triangle every time */
  5533. var count = 2 * nv; /* error detection */
  5534. for( v = nv - 1; nv > 2; ) {
  5535. /* if we loop, it is probably a non-simple polygon */
  5536. if ( ( count-- ) <= 0 ) {
  5537. //** Triangulate: ERROR - probable bad polygon!
  5538. //throw ( "Warning, unable to triangulate polygon!" );
  5539. //return null;
  5540. // Sometimes warning is fine, especially polygons are triangulated in reverse.
  5541. console.log( "Warning, unable to triangulate polygon!" );
  5542. if ( indices ) return vertIndices;
  5543. return result;
  5544. }
  5545. /* three consecutive vertices in current polygon, <u,v,w> */
  5546. u = v; if ( nv <= u ) u = 0; /* previous */
  5547. v = u + 1; if ( nv <= v ) v = 0; /* new v */
  5548. w = v + 1; if ( nv <= w ) w = 0; /* next */
  5549. if ( snip( contour, u, v, w, nv, verts ) ) {
  5550. var a, b, c, s, t;
  5551. /* true names of the vertices */
  5552. a = verts[ u ];
  5553. b = verts[ v ];
  5554. c = verts[ w ];
  5555. /* output Triangle */
  5556. /*
  5557. result.push( contour[ a ] );
  5558. result.push( contour[ b ] );
  5559. result.push( contour[ c ] );
  5560. */
  5561. result.push( [ contour[ a ],
  5562. contour[ b ],
  5563. contour[ c ] ] );
  5564. vertIndices.push( [ verts[ u ], verts[ v ], verts[ w ] ] );
  5565. /* remove v from the remaining polygon */
  5566. for( s = v, t = v + 1; t < nv; s++, t++ ) {
  5567. verts[ s ] = verts[ t ];
  5568. }
  5569. nv--;
  5570. /* reset error detection counter */
  5571. count = 2 * nv;
  5572. }
  5573. }
  5574. if ( indices ) return vertIndices;
  5575. return result;
  5576. };
  5577. // calculate area of the contour polygon
  5578. var area = function ( contour ) {
  5579. var n = contour.length;
  5580. var a = 0.0;
  5581. for( var p = n - 1, q = 0; q < n; p = q++ ) {
  5582. a += contour[ p ].x * contour[ q ].y - contour[ q ].x * contour[ p ].y;
  5583. }
  5584. return a * 0.5;
  5585. };
  5586. // see if p is inside triangle abc
  5587. var insideTriangle = function( ax, ay,
  5588. bx, by,
  5589. cx, cy,
  5590. px, py ) {
  5591. var aX, aY, bX, bY;
  5592. var cX, cY, apx, apy;
  5593. var bpx, bpy, cpx, cpy;
  5594. var cCROSSap, bCROSScp, aCROSSbp;
  5595. aX = cx - bx; aY = cy - by;
  5596. bX = ax - cx; bY = ay - cy;
  5597. cX = bx - ax; cY = by - ay;
  5598. apx= px -ax; apy= py - ay;
  5599. bpx= px - bx; bpy= py - by;
  5600. cpx= px - cx; cpy= py - cy;
  5601. aCROSSbp = aX*bpy - aY*bpx;
  5602. cCROSSap = cX*apy - cY*apx;
  5603. bCROSScp = bX*cpy - bY*cpx;
  5604. return ( (aCROSSbp >= 0.0) && (bCROSScp >= 0.0) && (cCROSSap >= 0.0) );
  5605. };
  5606. var snip = function ( contour, u, v, w, n, verts ) {
  5607. var p;
  5608. var ax, ay, bx, by;
  5609. var cx, cy, px, py;
  5610. ax = contour[ verts[ u ] ].x;
  5611. ay = contour[ verts[ u ] ].y;
  5612. bx = contour[ verts[ v ] ].x;
  5613. by = contour[ verts[ v ] ].y;
  5614. cx = contour[ verts[ w ] ].x;
  5615. cy = contour[ verts[ w ] ].y;
  5616. if ( EPSILON > (((bx-ax)*(cy-ay)) - ((by-ay)*(cx-ax))) ) return false;
  5617. for ( p = 0; p < n; p++ ) {
  5618. if( (p == u) || (p == v) || (p == w) ) continue;
  5619. px = contour[ verts[ p ] ].x
  5620. py = contour[ verts[ p ] ].y
  5621. if ( insideTriangle( ax, ay, bx, by, cx, cy, px, py ) ) return false;
  5622. }
  5623. return true;
  5624. };
  5625. namespace.Triangulate = process;
  5626. namespace.Triangulate.area = area;
  5627. return namespace;
  5628. })(THREE.FontUtils);
  5629. // To use the typeface.js face files, hook up the API
  5630. self._typeface_js = { faces: THREE.FontUtils.faces, loadFace: THREE.FontUtils.loadFace };
  5631. /**
  5632. * @author oosmoxiecode
  5633. * @author mr.doob / http://mrdoob.com/
  5634. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3DLite/src/away3dlite/primitives/Torus.as?r=2888
  5635. */
  5636. THREE.TorusGeometry = function ( radius, tube, segmentsR, segmentsT, arc ) {
  5637. THREE.Geometry.call( this );
  5638. var scope = this;
  5639. this.radius = radius || 100;
  5640. this.tube = tube || 40;
  5641. this.segmentsR = segmentsR || 8;
  5642. this.segmentsT = segmentsT || 6;
  5643. this.arc = arc || Math.PI * 2;
  5644. var center = new THREE.Vector3(), uvs = [], normals = [];
  5645. for ( var j = 0; j <= this.segmentsR; j ++ ) {
  5646. for ( var i = 0; i <= this.segmentsT; i ++ ) {
  5647. var u = i / this.segmentsT * this.arc;
  5648. var v = j / this.segmentsR * Math.PI * 2;
  5649. center.x = this.radius * Math.cos( u );
  5650. center.y = this.radius * Math.sin( u );
  5651. var vertex = new THREE.Vertex();
  5652. vertex.x = ( this.radius + this.tube * Math.cos( v ) ) * Math.cos( u );
  5653. vertex.y = ( this.radius + this.tube * Math.cos( v ) ) * Math.sin( u );
  5654. vertex.z = this.tube * Math.sin( v );
  5655. this.vertices.push( vertex );
  5656. uvs.push( new THREE.UV( i / this.segmentsT, 1 - j / this.segmentsR ) );
  5657. normals.push( vertex.clone().subSelf( center ).normalize() );
  5658. }
  5659. }
  5660. for ( var j = 1; j <= this.segmentsR; j ++ ) {
  5661. for ( var i = 1; i <= this.segmentsT; i ++ ) {
  5662. var a = ( this.segmentsT + 1 ) * j + i - 1;
  5663. var b = ( this.segmentsT + 1 ) * ( j - 1 ) + i - 1;
  5664. var c = ( this.segmentsT + 1 ) * ( j - 1 ) + i;
  5665. var d = ( this.segmentsT + 1 ) * j + i;
  5666. var face = new THREE.Face4( a, b, c, d, [ normals[ a ], normals[ b ], normals[ c ], normals[ d ] ] );
  5667. face.normal.addSelf( normals[ a ] );
  5668. face.normal.addSelf( normals[ b ] );
  5669. face.normal.addSelf( normals[ c ] );
  5670. face.normal.addSelf( normals[ d ] );
  5671. face.normal.normalize();
  5672. this.faces.push( face );
  5673. this.faceVertexUvs[ 0 ].push( [ uvs[ a ].clone(), uvs[ b ].clone(), uvs[ c ].clone(), uvs[ d ].clone() ] );
  5674. }
  5675. }
  5676. this.computeCentroids();
  5677. };
  5678. THREE.TorusGeometry.prototype = new THREE.Geometry();
  5679. THREE.TorusGeometry.prototype.constructor = THREE.TorusGeometry;
  5680. /**
  5681. * @author oosmoxiecode
  5682. * based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  5683. */
  5684. THREE.TorusKnotGeometry = function ( radius, tube, segmentsR, segmentsT, p, q, heightScale ) {
  5685. THREE.Geometry.call( this );
  5686. var scope = this;
  5687. this.radius = radius || 200;
  5688. this.tube = tube || 40;
  5689. this.segmentsR = segmentsR || 64;
  5690. this.segmentsT = segmentsT || 8;
  5691. this.p = p || 2;
  5692. this.q = q || 3;
  5693. this.heightScale = heightScale || 1;
  5694. this.grid = new Array(this.segmentsR);
  5695. var tang = new THREE.Vector3();
  5696. var n = new THREE.Vector3();
  5697. var bitan = new THREE.Vector3();
  5698. for ( var i = 0; i < this.segmentsR; ++ i ) {
  5699. this.grid[ i ] = new Array( this.segmentsT );
  5700. for ( var j = 0; j < this.segmentsT; ++ j ) {
  5701. var u = i / this.segmentsR * 2 * this.p * Math.PI;
  5702. var v = j / this.segmentsT * 2 * Math.PI;
  5703. var p1 = getPos( u, v, this.q, this.p, this.radius, this.heightScale );
  5704. var p2 = getPos( u + 0.01, v, this.q, this.p, this.radius, this.heightScale );
  5705. var cx, cy;
  5706. tang.sub( p2, p1 );
  5707. n.add( p2, p1 );
  5708. bitan.cross( tang, n );
  5709. n.cross( bitan, tang );
  5710. bitan.normalize();
  5711. n.normalize();
  5712. cx = - this.tube * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  5713. cy = this.tube * Math.sin( v );
  5714. p1.x += cx * n.x + cy * bitan.x;
  5715. p1.y += cx * n.y + cy * bitan.y;
  5716. p1.z += cx * n.z + cy * bitan.z;
  5717. this.grid[ i ][ j ] = vert( p1.x, p1.y, p1.z );
  5718. }
  5719. }
  5720. for ( var i = 0; i < this.segmentsR; ++ i ) {
  5721. for ( var j = 0; j < this.segmentsT; ++ j ) {
  5722. var ip = ( i + 1 ) % this.segmentsR;
  5723. var jp = ( j + 1 ) % this.segmentsT;
  5724. var a = this.grid[ i ][ j ];
  5725. var b = this.grid[ ip ][ j ];
  5726. var c = this.grid[ ip ][ jp ];
  5727. var d = this.grid[ i ][ jp ];
  5728. var uva = new THREE.UV( i / this.segmentsR, j / this.segmentsT );
  5729. var uvb = new THREE.UV( ( i + 1 ) / this.segmentsR, j / this.segmentsT );
  5730. var uvc = new THREE.UV( ( i + 1 ) / this.segmentsR, ( j + 1 ) / this.segmentsT );
  5731. var uvd = new THREE.UV( i / this.segmentsR, ( j + 1 ) / this.segmentsT );
  5732. this.faces.push( new THREE.Face4( a, b, c, d ) );
  5733. this.faceVertexUvs[ 0 ].push( [ uva,uvb,uvc, uvd ] );
  5734. }
  5735. }
  5736. this.computeCentroids();
  5737. this.computeFaceNormals();
  5738. this.computeVertexNormals();
  5739. function vert( x, y, z ) {
  5740. return scope.vertices.push( new THREE.Vertex( x, y, z ) ) - 1;
  5741. }
  5742. function getPos( u, v, in_q, in_p, radius, heightScale ) {
  5743. var cu = Math.cos( u );
  5744. var cv = Math.cos( v );
  5745. var su = Math.sin( u );
  5746. var quOverP = in_q / in_p * u;
  5747. var cs = Math.cos( quOverP );
  5748. var tx = radius * ( 2 + cs ) * 0.5 * cu;
  5749. var ty = radius * ( 2 + cs ) * su * 0.5;
  5750. var tz = heightScale * radius * Math.sin( quOverP ) * 0.5;
  5751. return new THREE.Vector3( tx, ty, tz );
  5752. }
  5753. };
  5754. THREE.TorusKnotGeometry.prototype = new THREE.Geometry();
  5755. THREE.TorusKnotGeometry.prototype.constructor = THREE.TorusKnotGeometry;
  5756. /**
  5757. * @author WestLangley / https://github.com/WestLangley
  5758. * @author zz85 / https://github.com/zz85
  5759. * @author miningold / https://github.com/miningold
  5760. *
  5761. * Modified from the TorusKnotGeometry by @oosmoxiecode
  5762. *
  5763. * Creates a tube which extrudes along a 3d spline
  5764. *
  5765. * Uses parallel transport frames as described in
  5766. * http://www.cs.indiana.edu/pub/techreports/TR425.pdf
  5767. */
  5768. THREE.TubeGeometry = function( path, segments, radius, segmentsRadius, closed, debug ) {
  5769. THREE.Geometry.call( this );
  5770. this.path = path;
  5771. this.segments = segments || 64;
  5772. this.radius = radius || 1;
  5773. this.segmentsRadius = segmentsRadius || 8;
  5774. this.closed = closed || false;
  5775. if ( debug ) this.debug = new THREE.Object3D();
  5776. this.grid = [];
  5777. var scope = this,
  5778. tangent,
  5779. normal,
  5780. binormal,
  5781. numpoints = this.segments + 1,
  5782. x, y, z,
  5783. tx, ty, tz,
  5784. u, v,
  5785. cx, cy,
  5786. pos, pos2 = new THREE.Vector3(),
  5787. i, j,
  5788. ip, jp,
  5789. a, b, c, d,
  5790. uva, uvb, uvc, uvd;
  5791. var frames = new THREE.TubeGeometry.FrenetFrames(path, segments, closed),
  5792. tangents = frames.tangents,
  5793. normals = frames.normals,
  5794. binormals = frames.binormals;
  5795. // proxy internals
  5796. this.tangents = tangents;
  5797. this.normals = normals;
  5798. this.binormals = binormals;
  5799. function vert( x, y, z ) {
  5800. return scope.vertices.push( new THREE.Vertex( x, y, z ) ) - 1;
  5801. }
  5802. // consruct the grid
  5803. for ( i = 0; i < numpoints; i++ ) {
  5804. this.grid[ i ] = [];
  5805. u = i / ( numpoints - 1 );
  5806. pos = path.getPointAt( u );
  5807. tangent = tangents[ i ];
  5808. normal = normals[ i ];
  5809. binormal = binormals[ i ];
  5810. if ( this.debug ) {
  5811. this.debug.add(new THREE.ArrowHelper(tangent, pos, radius, 0x0000ff));
  5812. this.debug.add(new THREE.ArrowHelper(normal, pos, radius, 0xff0000));
  5813. this.debug.add(new THREE.ArrowHelper(binormal, pos, radius, 0x00ff00));
  5814. }
  5815. for ( j = 0; j < this.segmentsRadius; j++ ) {
  5816. v = j / this.segmentsRadius * 2 * Math.PI;
  5817. cx = -this.radius * Math.cos( v ); // TODO: Hack: Negating it so it faces outside.
  5818. cy = this.radius * Math.sin( v );
  5819. pos2.copy( pos );
  5820. pos2.x += cx * normal.x + cy * binormal.x;
  5821. pos2.y += cx * normal.y + cy * binormal.y;
  5822. pos2.z += cx * normal.z + cy * binormal.z;
  5823. this.grid[ i ][ j ] = vert( pos2.x, pos2.y, pos2.z );
  5824. }
  5825. }
  5826. // construct the mesh
  5827. for ( i = 0; i < this.segments; i++ ) {
  5828. for ( j = 0; j < this.segmentsRadius; j++ ) {
  5829. ip = ( closed ) ? (i + 1) % this.segments : i + 1;
  5830. jp = (j + 1) % this.segmentsRadius;
  5831. a = this.grid[ i ][ j ]; // *** NOT NECESSARILY PLANAR ! ***
  5832. b = this.grid[ ip ][ j ];
  5833. c = this.grid[ ip ][ jp ];
  5834. d = this.grid[ i ][ jp ];
  5835. uva = new THREE.UV( i / this.segments, j / this.segmentsRadius );
  5836. uvb = new THREE.UV( ( i + 1 ) / this.segments, j / this.segmentsRadius );
  5837. uvc = new THREE.UV( ( i + 1 ) / this.segments, ( j + 1 ) / this.segmentsRadius );
  5838. uvd = new THREE.UV( i / this.segments, ( j + 1 ) / this.segmentsRadius );
  5839. this.faces.push( new THREE.Face4( a, b, c, d ) );
  5840. this.faceVertexUvs[ 0 ].push( [ uva, uvb, uvc, uvd ] );
  5841. }
  5842. }
  5843. this.computeCentroids();
  5844. this.computeFaceNormals();
  5845. this.computeVertexNormals();
  5846. };
  5847. THREE.TubeGeometry.prototype = new THREE.Geometry();
  5848. THREE.TubeGeometry.prototype.constructor = THREE.TubeGeometry;
  5849. // For computing of Frenet frames, exposing the tangents, normals and binormals the spline
  5850. THREE.TubeGeometry.FrenetFrames = function(path, segments, closed) {
  5851. var
  5852. tangent = new THREE.Vector3(),
  5853. normal = new THREE.Vector3(),
  5854. binormal = new THREE.Vector3(),
  5855. tangents = [],
  5856. normals = [],
  5857. binormals = [],
  5858. vec = new THREE.Vector3(),
  5859. mat = new THREE.Matrix4(),
  5860. numpoints = segments + 1,
  5861. theta,
  5862. epsilon = 0.0001,
  5863. smallest,
  5864. tx, ty, tz,
  5865. i, u, v;
  5866. // expose internals
  5867. this.tangents = tangents;
  5868. this.normals = normals;
  5869. this.binormals = binormals;
  5870. // compute the tangent vectors for each segment on the path
  5871. for ( i = 0; i < numpoints; i++ ) {
  5872. u = i / ( numpoints - 1 );
  5873. tangents[ i ] = path.getTangentAt( u );
  5874. tangents[ i ].normalize();
  5875. }
  5876. initialNormal3();
  5877. function initialNormal1(lastBinormal) {
  5878. // fixed start binormal. Has dangers of 0 vectors
  5879. normals[ 0 ] = new THREE.Vector3();
  5880. binormals[ 0 ] = new THREE.Vector3();
  5881. if (lastBinormal===undefined) lastBinormal = new THREE.Vector3( 0, 0, 1 );
  5882. normals[ 0 ].cross( lastBinormal, tangents[ 0 ] ).normalize();
  5883. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  5884. }
  5885. function initialNormal2() {
  5886. // This uses the Frenet-Serret formula for deriving binormal
  5887. var t2 = path.getTangentAt( epsilon );
  5888. normals[ 0 ] = new THREE.Vector3().sub( t2, tangents[ 0 ] ).normalize();
  5889. binormals[ 0 ] = new THREE.Vector3().cross( tangents[ 0 ], normals[ 0 ] );
  5890. normals[ 0 ].cross( binormals[ 0 ], tangents[ 0 ] ).normalize(); // last binormal x tangent
  5891. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] ).normalize();
  5892. }
  5893. function initialNormal3() {
  5894. // select an initial normal vector perpenicular to the first tangent vector,
  5895. // and in the direction of the smallest tangent xyz component
  5896. normals[ 0 ] = new THREE.Vector3();
  5897. binormals[ 0 ] = new THREE.Vector3();
  5898. smallest = Number.MAX_VALUE;
  5899. tx = Math.abs( tangents[ 0 ].x );
  5900. ty = Math.abs( tangents[ 0 ].y );
  5901. tz = Math.abs( tangents[ 0 ].z );
  5902. if ( tx <= smallest ) {
  5903. smallest = tx;
  5904. normal.set( 1, 0, 0 );
  5905. }
  5906. if ( ty <= smallest ) {
  5907. smallest = ty;
  5908. normal.set( 0, 1, 0 );
  5909. }
  5910. if ( tz <= smallest ) {
  5911. normal.set( 0, 0, 1 );
  5912. }
  5913. vec.cross( tangents[ 0 ], normal ).normalize();
  5914. normals[ 0 ].cross( tangents[ 0 ], vec );
  5915. binormals[ 0 ].cross( tangents[ 0 ], normals[ 0 ] );
  5916. }
  5917. // compute the slowly-varying normal and binormal vectors for each segment on the path
  5918. for ( i = 1; i < numpoints; i++ ) {
  5919. normals[ i ] = normals[ i-1 ].clone();
  5920. binormals[ i ] = binormals[ i-1 ].clone();
  5921. vec.cross( tangents[ i-1 ], tangents[ i ] );
  5922. if ( vec.length() > epsilon ) {
  5923. vec.normalize();
  5924. theta = Math.acos( tangents[ i-1 ].dot( tangents[ i ] ) );
  5925. mat.makeRotationAxis( vec, theta ).multiplyVector3( normals[ i ] );
  5926. }
  5927. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  5928. }
  5929. // if the curve is closed, postprocess the vectors so the first and last normal vectors are the same
  5930. if ( closed ) {
  5931. theta = Math.acos( normals[ 0 ].dot( normals[ numpoints-1 ] ) );
  5932. theta /= ( numpoints - 1 );
  5933. if ( tangents[ 0 ].dot( vec.cross( normals[ 0 ], normals[ numpoints-1 ] ) ) > 0 ) {
  5934. theta = -theta;
  5935. }
  5936. for ( i = 1; i < numpoints; i++ ) {
  5937. // twist a little...
  5938. mat.makeRotationAxis( tangents[ i ], theta * i ).multiplyVector3( normals[ i ] );
  5939. binormals[ i ].cross( tangents[ i ], normals[ i ] );
  5940. }
  5941. }
  5942. };
  5943. /**
  5944. * @author clockworkgeek / https://github.com/clockworkgeek
  5945. * @author timothypratley / https://github.com/timothypratley
  5946. */
  5947. THREE.PolyhedronGeometry = function ( vertices, faces, radius, detail ) {
  5948. THREE.Geometry.call( this );
  5949. radius = radius || 1;
  5950. detail = detail || 0;
  5951. var that = this;
  5952. for ( var i = 0, l = vertices.length; i < l; i ++ ) {
  5953. prepare( new THREE.Vector3( vertices[ i ][ 0 ], vertices[ i ][ 1 ], vertices[ i ][ 2 ] ) );
  5954. }
  5955. var midpoints = [], p = this.vertices;
  5956. for ( var i = 0, l = faces.length; i < l; i ++ ) {
  5957. make( p[ faces[ i ][ 0 ] ], p[ faces[ i ][ 1 ] ], p[ faces[ i ][ 2 ] ], detail );
  5958. }
  5959. this.mergeVertices();
  5960. // Apply radius
  5961. for ( var i = 0, l = this.vertices.length; i < l; i ++ ) {
  5962. this.vertices[ i ].multiplyScalar( radius );
  5963. }
  5964. /**
  5965. * Project vector onto sphere's surface
  5966. */
  5967. function prepare( vector ) {
  5968. var vertex = new THREE.Vertex().copy( vector.normalize() );
  5969. vertex.index = that.vertices.push( vertex ) - 1;
  5970. // Texture coords are equivalent to map coords, calculate angle and convert to fraction of a circle.
  5971. var u = azimuth( vector ) / 2 / Math.PI + 0.5;
  5972. var v = inclination( vector ) / Math.PI + 0.5;
  5973. vertex.uv = new THREE.UV( u, v );
  5974. return vertex;
  5975. }
  5976. /**
  5977. * Approximate a curved face with recursively sub-divided triangles.
  5978. */
  5979. function make( v1, v2, v3, detail ) {
  5980. if ( detail < 1 ) {
  5981. var face = new THREE.Face3( v1.index, v2.index, v3.index, [ v1.clone(), v2.clone(), v3.clone() ] );
  5982. face.centroid.addSelf( v1 ).addSelf( v2 ).addSelf( v3 ).divideScalar( 3 );
  5983. face.normal = face.centroid.clone().normalize();
  5984. that.faces.push( face );
  5985. var azi = azimuth( face.centroid );
  5986. that.faceVertexUvs[ 0 ].push( [
  5987. correctUV( v1.uv, v1, azi ),
  5988. correctUV( v2.uv, v2, azi ),
  5989. correctUV( v3.uv, v3, azi )
  5990. ] );
  5991. }
  5992. else {
  5993. detail -= 1;
  5994. // split triangle into 4 smaller triangles
  5995. make( v1, midpoint( v1, v2 ), midpoint( v1, v3 ), detail ); // top quadrant
  5996. make( midpoint( v1, v2 ), v2, midpoint( v2, v3 ), detail ); // left quadrant
  5997. make( midpoint( v1, v3 ), midpoint( v2, v3 ), v3, detail ); // right quadrant
  5998. make( midpoint( v1, v2 ), midpoint( v2, v3 ), midpoint( v1, v3 ), detail ); // center quadrant
  5999. }
  6000. }
  6001. function midpoint( v1, v2 ) {
  6002. if ( !midpoints[ v1.index ] ) midpoints[ v1.index ] = [];
  6003. if ( !midpoints[ v2.index ] ) midpoints[ v2.index ] = [];
  6004. var mid = midpoints[ v1.index ][ v2.index ];
  6005. if ( mid === undefined ) {
  6006. // generate mean point and project to surface with prepare()
  6007. midpoints[ v1.index ][ v2.index ] = midpoints[ v2.index ][ v1.index ] = mid = prepare(
  6008. new THREE.Vector3().add( v1, v2 ).divideScalar( 2 )
  6009. );
  6010. }
  6011. return mid;
  6012. }
  6013. /**
  6014. * Angle around the Y axis, counter-clockwise when looking from above.
  6015. */
  6016. function azimuth( vector ) {
  6017. return Math.atan2( vector.z, -vector.x );
  6018. }
  6019. /**
  6020. * Angle above the XZ plane.
  6021. */
  6022. function inclination( vector ) {
  6023. return Math.atan2( -vector.y, Math.sqrt( ( vector.x * vector.x ) + ( vector.z * vector.z ) ) );
  6024. }
  6025. /**
  6026. * Texture fixing helper. Spheres have some odd behaviours.
  6027. */
  6028. function correctUV( uv, vector, azimuth ) {
  6029. if ( (azimuth < 0) && (uv.u === 1) ) uv = new THREE.UV( uv.u - 1, uv.v );
  6030. if ( (vector.x === 0) && (vector.z === 0) ) uv = new THREE.UV( azimuth / 2 / Math.PI + 0.5, uv.v );
  6031. return uv;
  6032. }
  6033. this.computeCentroids();
  6034. this.boundingSphere = { radius: radius };
  6035. };
  6036. THREE.PolyhedronGeometry.prototype = new THREE.Geometry();
  6037. THREE.PolyhedronGeometry.prototype.constructor = THREE.PolyhedronGeometry;
  6038. /**
  6039. * @author timothypratley / https://github.com/timothypratley
  6040. */
  6041. THREE.IcosahedronGeometry = function ( radius, detail ) {
  6042. var t = ( 1 + Math.sqrt( 5 ) ) / 2;
  6043. var vertices = [
  6044. [ -1, t, 0 ], [ 1, t, 0 ], [ -1, -t, 0 ], [ 1, -t, 0 ],
  6045. [ 0, -1, t ], [ 0, 1, t ], [ 0, -1, -t ], [ 0, 1, -t ],
  6046. [ t, 0, -1 ], [ t, 0, 1 ], [ -t, 0, -1 ], [ -t, 0, 1 ]
  6047. ];
  6048. var faces = [
  6049. [ 0, 11, 5 ], [ 0, 5, 1 ], [ 0, 1, 7 ], [ 0, 7, 10 ], [ 0, 10, 11 ],
  6050. [ 1, 5, 9 ], [ 5, 11, 4 ], [ 11, 10, 2 ], [ 10, 7, 6 ], [ 7, 1, 8 ],
  6051. [ 3, 9, 4 ], [ 3, 4, 2 ], [ 3, 2, 6 ], [ 3, 6, 8 ], [ 3, 8, 9 ],
  6052. [ 4, 9, 5 ], [ 2, 4, 11 ], [ 6, 2, 10 ], [ 8, 6, 7 ], [ 9, 8, 1 ]
  6053. ];
  6054. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  6055. };
  6056. THREE.IcosahedronGeometry.prototype = new THREE.Geometry();
  6057. THREE.IcosahedronGeometry.prototype.constructor = THREE.IcosahedronGeometry;
  6058. /**
  6059. * @author timothypratley / https://github.com/timothypratley
  6060. */
  6061. THREE.OctahedronGeometry = function ( radius, detail ) {
  6062. var vertices = [
  6063. [ 1, 0, 0 ], [ -1, 0, 0 ], [ 0, 1, 0 ], [ 0, -1, 0 ], [ 0, 0, 1 ], [ 0, 0, -1 ]
  6064. ];
  6065. var faces = [
  6066. [ 0, 2, 4 ], [ 0, 4, 3 ], [ 0, 3, 5 ], [ 0, 5, 2 ], [ 1, 2, 5 ], [ 1, 5, 3 ], [ 1, 3, 4 ], [ 1, 4, 2 ]
  6067. ];
  6068. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  6069. };
  6070. THREE.OctahedronGeometry.prototype = new THREE.Geometry();
  6071. THREE.OctahedronGeometry.prototype.constructor = THREE.OctahedronGeometry;
  6072. /**
  6073. * @author timothypratley / https://github.com/timothypratley
  6074. */
  6075. THREE.TetrahedronGeometry = function ( radius, detail ) {
  6076. var vertices = [
  6077. [ 1, 1, 1 ], [ -1, -1, 1 ], [ -1, 1, -1 ], [ 1, -1, -1 ]
  6078. ];
  6079. var faces = [
  6080. [ 2, 1, 0 ], [ 0, 3, 2 ], [ 1, 3, 0 ], [ 2, 3, 1 ]
  6081. ];
  6082. THREE.PolyhedronGeometry.call( this, vertices, faces, radius, detail );
  6083. };
  6084. THREE.TetrahedronGeometry.prototype = new THREE.Geometry();
  6085. THREE.TetrahedronGeometry.prototype.constructor = THREE.TetrahedronGeometry;
  6086. /**
  6087. * @author sroucheray / http://sroucheray.org/
  6088. * @author mr.doob / http://mrdoob.com/
  6089. */
  6090. THREE.AxisHelper = function () {
  6091. THREE.Object3D.call( this );
  6092. var lineGeometry = new THREE.Geometry();
  6093. lineGeometry.vertices.push( new THREE.Vertex() );
  6094. lineGeometry.vertices.push( new THREE.Vertex( 0, 100, 0 ) );
  6095. var coneGeometry = new THREE.CylinderGeometry( 0, 5, 25, 5, 1 );
  6096. var line, cone;
  6097. // x
  6098. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0xff0000 } ) );
  6099. line.rotation.z = - Math.PI / 2;
  6100. this.add( line );
  6101. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0xff0000 } ) );
  6102. cone.position.x = 100;
  6103. cone.rotation.z = - Math.PI / 2;
  6104. this.add( cone );
  6105. // y
  6106. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x00ff00 } ) );
  6107. this.add( line );
  6108. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x00ff00 } ) );
  6109. cone.position.y = 100;
  6110. this.add( cone );
  6111. // z
  6112. line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : 0x0000ff } ) );
  6113. line.rotation.x = Math.PI / 2;
  6114. this.add( line );
  6115. cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : 0x0000ff } ) );
  6116. cone.position.z = 100;
  6117. cone.rotation.x = Math.PI / 2;
  6118. this.add( cone );
  6119. };
  6120. THREE.AxisHelper.prototype = new THREE.Object3D();
  6121. THREE.AxisHelper.prototype.constructor = THREE.AxisHelper;
  6122. /**
  6123. * @author WestLangley / https://github.com/WestLangley
  6124. * @author zz85 / https://github.com/zz85
  6125. *
  6126. * Creates an arrow for visualizing directions
  6127. *
  6128. * Parameters:
  6129. * dir - Vector3
  6130. * origin - Vector3
  6131. * length - Number
  6132. * hex - color in hex value
  6133. */
  6134. THREE.ArrowHelper = function ( dir, origin, length, hex ) {
  6135. THREE.Object3D.call( this );
  6136. if ( hex === undefined ) hex = 0xffff00;
  6137. if ( length === undefined ) length = 20;
  6138. var lineGeometry = new THREE.Geometry();
  6139. lineGeometry.vertices.push( new THREE.Vertex( 0, 0, 0 ) );
  6140. lineGeometry.vertices.push( new THREE.Vertex( 0, 1, 0 ) );
  6141. this.line = new THREE.Line( lineGeometry, new THREE.LineBasicMaterial( { color : hex } ) );
  6142. this.add( this.line );
  6143. var coneGeometry = new THREE.CylinderGeometry( 0, 0.05, 0.25, 5, 1 );
  6144. this.cone = new THREE.Mesh( coneGeometry, new THREE.MeshBasicMaterial( { color : hex } ) );
  6145. this.cone.position.set( 0, 1, 0 );
  6146. this.add( this.cone );
  6147. if ( origin instanceof THREE.Vector3 ) {
  6148. this.position = origin;
  6149. }
  6150. this.setDirection( dir );
  6151. this.setLength( length );
  6152. };
  6153. THREE.ArrowHelper.prototype = new THREE.Object3D();
  6154. THREE.ArrowHelper.prototype.constructor = THREE.ArrowHelper;
  6155. THREE.ArrowHelper.prototype.setDirection = function( dir ) {
  6156. var axis = new THREE.Vector3( 0, 1, 0 ).crossSelf( dir );
  6157. var radians = Math.acos( new THREE.Vector3( 0, 1, 0 ).dot( dir.clone().normalize() ) );
  6158. this.matrix = new THREE.Matrix4().makeRotationAxis( axis.normalize(), radians );
  6159. this.rotation.getRotationFromMatrix( this.matrix, this.scale );
  6160. };
  6161. THREE.ArrowHelper.prototype.setLength = function( length ) {
  6162. this.scale.set( length, length, length );
  6163. };
  6164. THREE.ArrowHelper.prototype.setColor = function( hex ) {
  6165. this.line.material.color.setHex( hex );
  6166. this.cone.material.color.setHex( hex );
  6167. };
  6168. /**
  6169. * @author alteredq / http://alteredqualia.com/
  6170. *
  6171. * - shows frustum, line of sight and up of the camera
  6172. * - suitable for fast updates
  6173. * - based on frustum visualization in lightgl.js shadowmap example
  6174. * http://evanw.github.com/lightgl.js/tests/shadowmap.html
  6175. */
  6176. THREE.CameraHelper = function ( camera ) {
  6177. THREE.Object3D.call( this );
  6178. var _this = this;
  6179. this.lineGeometry = new THREE.Geometry();
  6180. this.lineMaterial = new THREE.LineBasicMaterial( { color: 0xffffff, vertexColors: THREE.FaceColors } );
  6181. this.pointMap = {};
  6182. // colors
  6183. var hexFrustum = 0xffaa00,
  6184. hexCone = 0xff0000,
  6185. hexUp = 0x00aaff,
  6186. hexTarget = 0xffffff,
  6187. hexCross = 0x333333;
  6188. // near
  6189. addLine( "n1", "n2", hexFrustum );
  6190. addLine( "n2", "n4", hexFrustum );
  6191. addLine( "n4", "n3", hexFrustum );
  6192. addLine( "n3", "n1", hexFrustum );
  6193. // far
  6194. addLine( "f1", "f2", hexFrustum );
  6195. addLine( "f2", "f4", hexFrustum );
  6196. addLine( "f4", "f3", hexFrustum );
  6197. addLine( "f3", "f1", hexFrustum );
  6198. // sides
  6199. addLine( "n1", "f1", hexFrustum );
  6200. addLine( "n2", "f2", hexFrustum );
  6201. addLine( "n3", "f3", hexFrustum );
  6202. addLine( "n4", "f4", hexFrustum );
  6203. // cone
  6204. addLine( "p", "n1", hexCone );
  6205. addLine( "p", "n2", hexCone );
  6206. addLine( "p", "n3", hexCone );
  6207. addLine( "p", "n4", hexCone );
  6208. // up
  6209. addLine( "u1", "u2", hexUp );
  6210. addLine( "u2", "u3", hexUp );
  6211. addLine( "u3", "u1", hexUp );
  6212. // target
  6213. addLine( "c", "t", hexTarget );
  6214. addLine( "p", "c", hexCross );
  6215. // cross
  6216. addLine( "cn1", "cn2", hexCross );
  6217. addLine( "cn3", "cn4", hexCross );
  6218. addLine( "cf1", "cf2", hexCross );
  6219. addLine( "cf3", "cf4", hexCross );
  6220. this.camera = camera;
  6221. function addLine( a, b, hex ) {
  6222. addPoint( a, hex );
  6223. addPoint( b, hex );
  6224. }
  6225. function addPoint( id, hex ) {
  6226. _this.lineGeometry.vertices.push( new THREE.Vertex() );
  6227. _this.lineGeometry.colors.push( new THREE.Color( hex ) );
  6228. if ( _this.pointMap[ id ] === undefined ) _this.pointMap[ id ] = [];
  6229. _this.pointMap[ id ].push( _this.lineGeometry.vertices.length - 1 );
  6230. }
  6231. this.update( camera );
  6232. this.lines = new THREE.Line( this.lineGeometry, this.lineMaterial, THREE.LinePieces );
  6233. this.add( this.lines );
  6234. };
  6235. THREE.CameraHelper.prototype = new THREE.Object3D();
  6236. THREE.CameraHelper.prototype.constructor = THREE.CameraHelper;
  6237. THREE.CameraHelper.prototype.update = function () {
  6238. var camera = this.camera;
  6239. var w = 1;
  6240. var h = 1;
  6241. var _this = this;
  6242. // we need just camera projection matrix
  6243. // world matrix must be identity
  6244. THREE.CameraHelper.__c.projectionMatrix.copy( camera.projectionMatrix );
  6245. // center / target
  6246. setPoint( "c", 0, 0, -1 );
  6247. setPoint( "t", 0, 0, 1 );
  6248. // near
  6249. setPoint( "n1", -w, -h, -1 );
  6250. setPoint( "n2", w, -h, -1 );
  6251. setPoint( "n3", -w, h, -1 );
  6252. setPoint( "n4", w, h, -1 );
  6253. // far
  6254. setPoint( "f1", -w, -h, 1 );
  6255. setPoint( "f2", w, -h, 1 );
  6256. setPoint( "f3", -w, h, 1 );
  6257. setPoint( "f4", w, h, 1 );
  6258. // up
  6259. setPoint( "u1", w * 0.7, h * 1.1, -1 );
  6260. setPoint( "u2", -w * 0.7, h * 1.1, -1 );
  6261. setPoint( "u3", 0, h * 2, -1 );
  6262. // cross
  6263. setPoint( "cf1", -w, 0, 1 );
  6264. setPoint( "cf2", w, 0, 1 );
  6265. setPoint( "cf3", 0, -h, 1 );
  6266. setPoint( "cf4", 0, h, 1 );
  6267. setPoint( "cn1", -w, 0, -1 );
  6268. setPoint( "cn2", w, 0, -1 );
  6269. setPoint( "cn3", 0, -h, -1 );
  6270. setPoint( "cn4", 0, h, -1 );
  6271. function setPoint( point, x, y, z ) {
  6272. THREE.CameraHelper.__v.set( x, y, z );
  6273. THREE.CameraHelper.__projector.unprojectVector( THREE.CameraHelper.__v, THREE.CameraHelper.__c );
  6274. var points = _this.pointMap[ point ];
  6275. if ( points !== undefined ) {
  6276. for ( var i = 0, il = points.length; i < il; i ++ ) {
  6277. var j = points[ i ];
  6278. _this.lineGeometry.vertices[ j ].copy( THREE.CameraHelper.__v );
  6279. }
  6280. }
  6281. }
  6282. this.lineGeometry.__dirtyVertices = true;
  6283. };
  6284. THREE.CameraHelper.__projector = new THREE.Projector();
  6285. THREE.CameraHelper.__v = new THREE.Vector3();
  6286. THREE.CameraHelper.__c = new THREE.Camera();
  6287. /*
  6288. * @author zz85 / http://twitter.com/blurspline / http://www.lab4games.net/zz85/blog
  6289. *
  6290. * Subdivision Geometry Modifier
  6291. * using Catmull-Clark Subdivision Surfaces
  6292. * for creating smooth geometry meshes
  6293. *
  6294. * Note: a modifier modifies vertices and faces of geometry,
  6295. * so use THREE.GeometryUtils.clone() if orignal geoemtry needs to be retained
  6296. *
  6297. * Readings:
  6298. * http://en.wikipedia.org/wiki/Catmull%E2%80%93Clark_subdivision_surface
  6299. * http://www.rorydriscoll.com/2008/08/01/catmull-clark-subdivision-the-basics/
  6300. * http://xrt.wikidot.com/blog:31
  6301. * "Subdivision Surfaces in Character Animation"
  6302. *
  6303. * Supports:
  6304. * Closed and Open geometries.
  6305. *
  6306. * TODO:
  6307. * crease vertex and "semi-sharp" features
  6308. * selective subdivision
  6309. */
  6310. THREE.SubdivisionModifier = function( subdivisions ) {
  6311. this.subdivisions = (subdivisions === undefined ) ? 1 : subdivisions;
  6312. // Settings
  6313. this.useOldVertexColors = false;
  6314. this.supportUVs = true;
  6315. this.debug = false;
  6316. };
  6317. //THREE.SubdivisionModifier.prototype = new THREE.Modifier();
  6318. THREE.SubdivisionModifier.prototype.constructor = THREE.SubdivisionModifier;
  6319. // Applies the "modify" pattern
  6320. THREE.SubdivisionModifier.prototype.modify = function ( geometry ) {
  6321. var repeats = this.subdivisions;
  6322. while ( repeats-- > 0 ) {
  6323. this.smooth( geometry );
  6324. }
  6325. };
  6326. // Performs an iteration of Catmull-Clark Subdivision
  6327. THREE.SubdivisionModifier.prototype.smooth = function ( oldGeometry ) {
  6328. //debug( 'running smooth' );
  6329. // New set of vertices, faces and uvs
  6330. var newVertices = [], newFaces = [], newUVs = [];
  6331. function v( x, y, z ) {
  6332. newVertices.push( new THREE.Vertex( x, y, z ) );
  6333. }
  6334. var scope = this;
  6335. function debug() {
  6336. if (scope.debug) console.log.apply(console, arguments);
  6337. }
  6338. function warn() {
  6339. if (console)
  6340. console.log.apply(console, arguments);
  6341. }
  6342. function f4( a, b, c, d, oldFace, orders, facei ) {
  6343. // TODO move vertex selection over here!
  6344. var newFace = new THREE.Face4( a, b, c, d, null, oldFace.color, oldFace.material );
  6345. if (scope.useOldVertexColors) {
  6346. newFace.vertexColors = [];
  6347. var color, tmpColor, order;
  6348. for (var i=0;i<4;i++) {
  6349. order = orders[i];
  6350. color = new THREE.Color(),
  6351. color.setRGB(0,0,0);
  6352. for (var j=0, jl=0; j<order.length;j++) {
  6353. tmpColor = oldFace.vertexColors[order[j]-1];
  6354. color.r += tmpColor.r;
  6355. color.g += tmpColor.g;
  6356. color.b += tmpColor.b;
  6357. }
  6358. color.r /= order.length;
  6359. color.g /= order.length;
  6360. color.b /= order.length;
  6361. newFace.vertexColors[i] = color;
  6362. }
  6363. }
  6364. newFaces.push( newFace );
  6365. if (scope.supportUVs) {
  6366. var aUv = [
  6367. getUV(a, ''),
  6368. getUV(b, facei),
  6369. getUV(c, facei),
  6370. getUV(d, facei)
  6371. ];
  6372. if (!aUv[0]) debug('a :( ', a+':'+facei);
  6373. else if (!aUv[1]) debug('b :( ', b+':'+facei);
  6374. else if (!aUv[2]) debug('c :( ', c+':'+facei);
  6375. else if (!aUv[3]) debug('d :( ', d+':'+facei);
  6376. else
  6377. newUVs.push( aUv );
  6378. }
  6379. }
  6380. function edge_hash( a, b ) {
  6381. return Math.min( a, b ) + "_" + Math.max( a, b );
  6382. }
  6383. function computeEdgeFaces( geometry ) {
  6384. var i, il, v1, v2, j, k,
  6385. face, faceIndices, faceIndex,
  6386. edge,
  6387. hash,
  6388. edgeFaceMap = {};
  6389. function mapEdgeHash( hash, i ) {
  6390. if ( edgeFaceMap[ hash ] === undefined ) {
  6391. edgeFaceMap[ hash ] = [];
  6392. }
  6393. edgeFaceMap[ hash ].push( i );
  6394. }
  6395. // construct vertex -> face map
  6396. for( i = 0, il = geometry.faces.length; i < il; i ++ ) {
  6397. face = geometry.faces[ i ];
  6398. if ( face instanceof THREE.Face3 ) {
  6399. hash = edge_hash( face.a, face.b );
  6400. mapEdgeHash( hash, i );
  6401. hash = edge_hash( face.b, face.c );
  6402. mapEdgeHash( hash, i );
  6403. hash = edge_hash( face.c, face.a );
  6404. mapEdgeHash( hash, i );
  6405. } else if ( face instanceof THREE.Face4 ) {
  6406. hash = edge_hash( face.a, face.b );
  6407. mapEdgeHash( hash, i );
  6408. hash = edge_hash( face.b, face.c );
  6409. mapEdgeHash( hash, i );
  6410. hash = edge_hash( face.c, face.d );
  6411. mapEdgeHash( hash, i );
  6412. hash = edge_hash( face.d, face.a );
  6413. mapEdgeHash( hash, i );
  6414. }
  6415. }
  6416. // extract faces
  6417. // var edges = [];
  6418. //
  6419. // var numOfEdges = 0;
  6420. // for (i in edgeFaceMap) {
  6421. // numOfEdges++;
  6422. //
  6423. // edge = edgeFaceMap[i];
  6424. // edges.push(edge);
  6425. //
  6426. // }
  6427. //debug('edgeFaceMap', edgeFaceMap, 'geometry.edges',geometry.edges, 'numOfEdges', numOfEdges);
  6428. return edgeFaceMap;
  6429. }
  6430. var originalPoints = oldGeometry.vertices;
  6431. var originalFaces = oldGeometry.faces;
  6432. var newPoints = originalPoints.concat(); // Vertices
  6433. var facePoints = [], edgePoints = {};
  6434. var sharpEdges = {}, sharpVertices = [], sharpFaces = [];
  6435. var uvForVertices = {}; // Stored in {vertex}:{old face} format
  6436. var originalVerticesLength = originalPoints.length;
  6437. function getUV(vertexNo, oldFaceNo) {
  6438. var j,jl;
  6439. var key = vertexNo+':'+oldFaceNo;
  6440. var theUV = uvForVertices[key];
  6441. if (!theUV) {
  6442. if (vertexNo>=originalVerticesLength && vertexNo < (originalVerticesLength + originalFaces.length)) {
  6443. debug('face pt');
  6444. } else {
  6445. debug('edge pt');
  6446. }
  6447. warn('warning, UV not found for', key);
  6448. return null;
  6449. }
  6450. return theUV;
  6451. // Original faces -> Vertex Nos.
  6452. // new Facepoint -> Vertex Nos.
  6453. // edge Points
  6454. }
  6455. function addUV(vertexNo, oldFaceNo, value) {
  6456. var key = vertexNo+':'+oldFaceNo;
  6457. if (!(key in uvForVertices)) {
  6458. uvForVertices[key] = value;
  6459. } else {
  6460. warn('dup vertexNo', vertexNo, 'oldFaceNo', oldFaceNo, 'value', value, 'key', key, uvForVertices[key]);
  6461. }
  6462. }
  6463. // Step 1
  6464. // For each face, add a face point
  6465. // Set each face point to be the centroid of all original points for the respective face.
  6466. // debug(oldGeometry);
  6467. var i, il, j, jl, face;
  6468. // For Uvs
  6469. var uvs = oldGeometry.faceVertexUvs[0];
  6470. var abcd = 'abcd', vertice;
  6471. debug('originalFaces, uvs, originalVerticesLength', originalFaces.length, uvs.length, originalVerticesLength);
  6472. if (scope.supportUVs)
  6473. for (i=0, il = uvs.length; i<il; i++ ) {
  6474. for (j=0,jl=uvs[i].length;j<jl;j++) {
  6475. vertice = originalFaces[i][abcd.charAt(j)];
  6476. addUV(vertice, i, uvs[i][j]);
  6477. }
  6478. }
  6479. if (uvs.length == 0) scope.supportUVs = false;
  6480. // Additional UVs check, if we index original
  6481. var uvCount = 0;
  6482. for (var u in uvForVertices) {
  6483. uvCount++;
  6484. }
  6485. if (!uvCount) {
  6486. scope.supportUVs = false;
  6487. debug('no uvs');
  6488. }
  6489. debug('-- Original Faces + Vertices UVs completed', uvForVertices, 'vs', uvs.length);
  6490. var avgUv ;
  6491. for (i=0, il = originalFaces.length; i<il ;i++) {
  6492. face = originalFaces[ i ];
  6493. facePoints.push( face.centroid );
  6494. newPoints.push( new THREE.Vertex().copy( face.centroid ) );
  6495. if (!scope.supportUVs) continue;
  6496. // Prepare subdivided uv
  6497. avgUv = new THREE.UV();
  6498. if ( face instanceof THREE.Face3 ) {
  6499. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u;
  6500. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v;
  6501. avgUv.u /= 3;
  6502. avgUv.v /= 3;
  6503. } else if ( face instanceof THREE.Face4 ) {
  6504. avgUv.u = getUV( face.a, i ).u + getUV( face.b, i ).u + getUV( face.c, i ).u + getUV( face.d, i ).u;
  6505. avgUv.v = getUV( face.a, i ).v + getUV( face.b, i ).v + getUV( face.c, i ).v + getUV( face.d, i ).v;
  6506. avgUv.u /= 4;
  6507. avgUv.v /= 4;
  6508. }
  6509. addUV(originalVerticesLength + i, '', avgUv);
  6510. }
  6511. debug('-- added UVs for new Faces', uvForVertices);
  6512. // Step 2
  6513. // For each edge, add an edge point.
  6514. // Set each edge point to be the average of the two neighbouring face points and its two original endpoints.
  6515. var edgeFaceMap = computeEdgeFaces ( oldGeometry ); // Edge Hash -> Faces Index
  6516. var edge, faceIndexA, faceIndexB, avg;
  6517. // debug('edgeFaceMap', edgeFaceMap);
  6518. var edgeCount = 0;
  6519. var edgeVertex, edgeVertexA, edgeVertexB;
  6520. ////
  6521. var vertexEdgeMap = {}; // Gives edges connecting from each vertex
  6522. var vertexFaceMap = {}; // Gives faces connecting from each vertex
  6523. function addVertexEdgeMap(vertex, edge) {
  6524. if (vertexEdgeMap[vertex]===undefined) {
  6525. vertexEdgeMap[vertex] = [];
  6526. }
  6527. vertexEdgeMap[vertex].push(edge);
  6528. }
  6529. function addVertexFaceMap(vertex, face, edge) {
  6530. if (vertexFaceMap[vertex]===undefined) {
  6531. vertexFaceMap[vertex] = {};
  6532. }
  6533. vertexFaceMap[vertex][face] = edge;
  6534. // vertexFaceMap[vertex][face] = null;
  6535. }
  6536. // Prepares vertexEdgeMap and vertexFaceMap
  6537. for (i in edgeFaceMap) { // This is for every edge
  6538. edge = edgeFaceMap[i];
  6539. edgeVertex = i.split('_');
  6540. edgeVertexA = edgeVertex[0];
  6541. edgeVertexB = edgeVertex[1];
  6542. // Maps an edgeVertex to connecting edges
  6543. addVertexEdgeMap(edgeVertexA, [edgeVertexA, edgeVertexB] );
  6544. addVertexEdgeMap(edgeVertexB, [edgeVertexA, edgeVertexB] );
  6545. for (j=0,jl=edge.length;j<jl;j++) {
  6546. face = edge[j];
  6547. addVertexFaceMap(edgeVertexA, face, i);
  6548. addVertexFaceMap(edgeVertexB, face, i);
  6549. }
  6550. if (edge.length < 2) {
  6551. // edge is "sharp";
  6552. sharpEdges[i] = true;
  6553. sharpVertices[edgeVertexA] = true;
  6554. sharpVertices[edgeVertexB] = true;
  6555. }
  6556. }
  6557. debug('vertexEdgeMap',vertexEdgeMap, 'vertexFaceMap', vertexFaceMap);
  6558. for (i in edgeFaceMap) {
  6559. edge = edgeFaceMap[i];
  6560. faceIndexA = edge[0]; // face index a
  6561. faceIndexB = edge[1]; // face index b
  6562. edgeVertex = i.split('_');
  6563. edgeVertexA = edgeVertex[0];
  6564. edgeVertexB = edgeVertex[1];
  6565. avg = new THREE.Vector3();
  6566. //debug(i, faceIndexB,facePoints[faceIndexB]);
  6567. if (sharpEdges[i]) {
  6568. //debug('warning, ', i, 'edge has only 1 connecting face', edge);
  6569. // For a sharp edge, average the edge end points.
  6570. avg.addSelf(originalPoints[edgeVertexA]);
  6571. avg.addSelf(originalPoints[edgeVertexB]);
  6572. avg.multiplyScalar(0.5);
  6573. sharpVertices[newPoints.length] = true;
  6574. } else {
  6575. avg.addSelf(facePoints[faceIndexA]);
  6576. avg.addSelf(facePoints[faceIndexB]);
  6577. avg.addSelf(originalPoints[edgeVertexA]);
  6578. avg.addSelf(originalPoints[edgeVertexB]);
  6579. avg.multiplyScalar(0.25);
  6580. }
  6581. edgePoints[i] = originalVerticesLength + originalFaces.length + edgeCount;
  6582. newPoints.push( new THREE.Vertex().copy( avg ) );
  6583. edgeCount ++;
  6584. if (!scope.supportUVs) {
  6585. continue;
  6586. }
  6587. // debug('faceIndexAB', faceIndexA, faceIndexB, sharpEdges[i]);
  6588. // Prepare subdivided uv
  6589. avgUv = new THREE.UV();
  6590. avgUv.u = getUV(edgeVertexA, faceIndexA).u + getUV(edgeVertexB, faceIndexA).u;
  6591. avgUv.v = getUV(edgeVertexA, faceIndexA).v + getUV(edgeVertexB, faceIndexA).v;
  6592. avgUv.u /= 2;
  6593. avgUv.v /= 2;
  6594. addUV(edgePoints[i], faceIndexA, avgUv);
  6595. if (!sharpEdges[i]) {
  6596. avgUv = new THREE.UV();
  6597. avgUv.u = getUV(edgeVertexA, faceIndexB).u + getUV(edgeVertexB, faceIndexB).u;
  6598. avgUv.v = getUV(edgeVertexA, faceIndexB).v + getUV(edgeVertexB, faceIndexB).v;
  6599. avgUv.u /= 2;
  6600. avgUv.v /= 2;
  6601. addUV(edgePoints[i], faceIndexB, avgUv);
  6602. }
  6603. }
  6604. debug('-- Step 2 done');
  6605. // Step 3
  6606. // For each face point, add an edge for every edge of the face,
  6607. // connecting the face point to each edge point for the face.
  6608. var facePt, currentVerticeIndex;
  6609. var hashAB, hashBC, hashCD, hashDA, hashCA;
  6610. var abc123 = ['123', '12', '2', '23'];
  6611. var bca123 = ['123', '23', '3', '31'];
  6612. var cab123 = ['123', '31', '1', '12'];
  6613. var abc1234 = ['1234', '12', '2', '23'];
  6614. var bcd1234 = ['1234', '23', '3', '34'];
  6615. var cda1234 = ['1234', '34', '4', '41'];
  6616. var dab1234 = ['1234', '41', '1', '12'];
  6617. for (i=0, il = facePoints.length; i<il ;i++) { // for every face
  6618. facePt = facePoints[i];
  6619. face = originalFaces[i];
  6620. currentVerticeIndex = originalVerticesLength+ i;
  6621. if ( face instanceof THREE.Face3 ) {
  6622. // create 3 face4s
  6623. hashAB = edge_hash( face.a, face.b );
  6624. hashBC = edge_hash( face.b, face.c );
  6625. hashCA = edge_hash( face.c, face.a );
  6626. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc123, i );
  6627. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCA], face, bca123, i );
  6628. f4( currentVerticeIndex, edgePoints[hashCA], face.a, edgePoints[hashAB], face, cab123, i );
  6629. } else if ( face instanceof THREE.Face4 ) {
  6630. // create 4 face4s
  6631. hashAB = edge_hash( face.a, face.b );
  6632. hashBC = edge_hash( face.b, face.c );
  6633. hashCD = edge_hash( face.c, face.d );
  6634. hashDA = edge_hash( face.d, face.a );
  6635. f4( currentVerticeIndex, edgePoints[hashAB], face.b, edgePoints[hashBC], face, abc1234, i );
  6636. f4( currentVerticeIndex, edgePoints[hashBC], face.c, edgePoints[hashCD], face, bcd1234, i );
  6637. f4( currentVerticeIndex, edgePoints[hashCD], face.d, edgePoints[hashDA], face, cda1234, i );
  6638. f4( currentVerticeIndex, edgePoints[hashDA], face.a, edgePoints[hashAB], face, dab1234, i );
  6639. } else {
  6640. debug('face should be a face!', face);
  6641. }
  6642. }
  6643. newVertices = newPoints;
  6644. // debug('original ', oldGeometry.vertices.length, oldGeometry.faces.length );
  6645. // debug('new points', newPoints.length, 'faces', newFaces.length );
  6646. // Step 4
  6647. // For each original point P,
  6648. // take the average F of all n face points for faces touching P,
  6649. // and take the average R of all n edge midpoints for edges touching P,
  6650. // where each edge midpoint is the average of its two endpoint vertices.
  6651. // Move each original point to the point
  6652. var F = new THREE.Vector3();
  6653. var R = new THREE.Vector3();
  6654. var n;
  6655. for (i=0, il = originalPoints.length; i<il; i++) {
  6656. // (F + 2R + (n-3)P) / n
  6657. if (vertexEdgeMap[i]===undefined) continue;
  6658. F.set(0,0,0);
  6659. R.set(0,0,0);
  6660. var newPos = new THREE.Vector3(0,0,0);
  6661. var f =0;
  6662. for (j in vertexFaceMap[i]) {
  6663. F.addSelf(facePoints[j]);
  6664. f++;
  6665. }
  6666. var sharpEdgeCount = 0;
  6667. n = vertexEdgeMap[i].length;
  6668. for (j=0;j<n;j++) {
  6669. if (
  6670. sharpEdges[
  6671. edge_hash(vertexEdgeMap[i][j][0],vertexEdgeMap[i][j][1])
  6672. ]) {
  6673. sharpEdgeCount++;
  6674. }
  6675. }
  6676. if ( sharpEdgeCount==2 ) {
  6677. continue;
  6678. // Do not move vertex if there's 2 connecting sharp edges.
  6679. }
  6680. /*
  6681. if (sharpEdgeCount>2) {
  6682. // TODO
  6683. }
  6684. */
  6685. F.divideScalar(f);
  6686. for (j=0; j<n;j++) {
  6687. edge = vertexEdgeMap[i][j];
  6688. var midPt = originalPoints[edge[0]].clone().addSelf(originalPoints[edge[1]]).divideScalar(2);
  6689. R.addSelf(midPt);
  6690. // R.addSelf(originalPoints[edge[0]]);
  6691. // R.addSelf(originalPoints[edge[1]]);
  6692. }
  6693. R.divideScalar(n);
  6694. newPos.addSelf(originalPoints[i]);
  6695. newPos.multiplyScalar(n - 3);
  6696. newPos.addSelf(F);
  6697. newPos.addSelf(R.multiplyScalar(2));
  6698. newPos.divideScalar(n);
  6699. newVertices[i] = newPos;
  6700. }
  6701. var newGeometry = oldGeometry; // Let's pretend the old geometry is now new :P
  6702. newGeometry.vertices = newVertices;
  6703. newGeometry.faces = newFaces;
  6704. newGeometry.faceVertexUvs[ 0 ] = newUVs;
  6705. delete newGeometry.__tmpVertices; // makes __tmpVertices undefined :P
  6706. newGeometry.computeCentroids();
  6707. newGeometry.computeFaceNormals();
  6708. newGeometry.computeVertexNormals();
  6709. };
  6710. /**
  6711. * @author alteredq / http://alteredqualia.com/
  6712. */
  6713. THREE.Loader = function ( showStatus ) {
  6714. this.showStatus = showStatus;
  6715. this.statusDomElement = showStatus ? THREE.Loader.prototype.addStatusElement() : null;
  6716. this.onLoadStart = function () {};
  6717. this.onLoadProgress = function() {};
  6718. this.onLoadComplete = function () {};
  6719. };
  6720. THREE.Loader.prototype = {
  6721. constructor: THREE.Loader,
  6722. crossOrigin: 'anonymous',
  6723. addStatusElement: function () {
  6724. var e = document.createElement( "div" );
  6725. e.style.position = "absolute";
  6726. e.style.right = "0px";
  6727. e.style.top = "0px";
  6728. e.style.fontSize = "0.8em";
  6729. e.style.textAlign = "left";
  6730. e.style.background = "rgba(0,0,0,0.25)";
  6731. e.style.color = "#fff";
  6732. e.style.width = "120px";
  6733. e.style.padding = "0.5em 0.5em 0.5em 0.5em";
  6734. e.style.zIndex = 1000;
  6735. e.innerHTML = "Loading ...";
  6736. return e;
  6737. },
  6738. updateProgress: function ( progress ) {
  6739. var message = "Loaded ";
  6740. if ( progress.total ) {
  6741. message += ( 100 * progress.loaded / progress.total ).toFixed(0) + "%";
  6742. } else {
  6743. message += ( progress.loaded / 1000 ).toFixed(2) + " KB";
  6744. }
  6745. this.statusDomElement.innerHTML = message;
  6746. },
  6747. extractUrlBase: function ( url ) {
  6748. var parts = url.split( '/' );
  6749. parts.pop();
  6750. return ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  6751. },
  6752. initMaterials: function ( scope, materials, texturePath ) {
  6753. scope.materials = [];
  6754. for ( var i = 0; i < materials.length; ++ i ) {
  6755. scope.materials[ i ] = THREE.Loader.prototype.createMaterial( materials[ i ], texturePath );
  6756. }
  6757. },
  6758. hasNormals: function ( scope ) {
  6759. var m, i, il = scope.materials.length;
  6760. for( i = 0; i < il; i ++ ) {
  6761. m = scope.materials[ i ];
  6762. if ( m instanceof THREE.ShaderMaterial ) return true;
  6763. }
  6764. return false;
  6765. },
  6766. createMaterial: function ( m, texturePath ) {
  6767. var _this = this;
  6768. function is_pow2( n ) {
  6769. var l = Math.log( n ) / Math.LN2;
  6770. return Math.floor( l ) == l;
  6771. }
  6772. function nearest_pow2( n ) {
  6773. var l = Math.log( n ) / Math.LN2;
  6774. return Math.pow( 2, Math.round( l ) );
  6775. }
  6776. function load_image( where, url ) {
  6777. var image = new Image();
  6778. image.onload = function () {
  6779. if ( !is_pow2( this.width ) || !is_pow2( this.height ) ) {
  6780. var width = nearest_pow2( this.width );
  6781. var height = nearest_pow2( this.height );
  6782. where.image.width = width;
  6783. where.image.height = height;
  6784. where.image.getContext( '2d' ).drawImage( this, 0, 0, width, height );
  6785. } else {
  6786. where.image = this;
  6787. }
  6788. where.needsUpdate = true;
  6789. };
  6790. image.crossOrigin = _this.crossOrigin;
  6791. image.src = url;
  6792. }
  6793. function create_texture( where, name, sourceFile, repeat, offset, wrap ) {
  6794. var texture = document.createElement( 'canvas' );
  6795. where[ name ] = new THREE.Texture( texture );
  6796. where[ name ].sourceFile = sourceFile;
  6797. if( repeat ) {
  6798. where[ name ].repeat.set( repeat[ 0 ], repeat[ 1 ] );
  6799. if ( repeat[ 0 ] != 1 ) where[ name ].wrapS = THREE.RepeatWrapping;
  6800. if ( repeat[ 1 ] != 1 ) where[ name ].wrapT = THREE.RepeatWrapping;
  6801. }
  6802. if ( offset ) {
  6803. where[ name ].offset.set( offset[ 0 ], offset[ 1 ] );
  6804. }
  6805. if ( wrap ) {
  6806. var wrapMap = {
  6807. "repeat" : THREE.RepeatWrapping,
  6808. "mirror" : THREE.MirroredRepeatWrapping
  6809. }
  6810. if ( wrapMap[ wrap[ 0 ] ] !== undefined ) where[ name ].wrapS = wrapMap[ wrap[ 0 ] ];
  6811. if ( wrapMap[ wrap[ 1 ] ] !== undefined ) where[ name ].wrapT = wrapMap[ wrap[ 1 ] ];
  6812. }
  6813. load_image( where[ name ], texturePath + "/" + sourceFile );
  6814. }
  6815. function rgb2hex( rgb ) {
  6816. return ( rgb[ 0 ] * 255 << 16 ) + ( rgb[ 1 ] * 255 << 8 ) + rgb[ 2 ] * 255;
  6817. }
  6818. // defaults
  6819. var mtype = "MeshLambertMaterial";
  6820. var mpars = { color: 0xeeeeee, opacity: 1.0, map: null, lightMap: null, normalMap: null, wireframe: m.wireframe };
  6821. // parameters from model file
  6822. if ( m.shading ) {
  6823. var shading = m.shading.toLowerCase();
  6824. if ( shading === "phong" ) mtype = "MeshPhongMaterial";
  6825. else if ( shading === "basic" ) mtype = "MeshBasicMaterial";
  6826. }
  6827. if ( m.blending !== undefined && THREE[ m.blending ] !== undefined ) {
  6828. mpars.blending = THREE[ m.blending ];
  6829. }
  6830. if ( m.transparent !== undefined || m.opacity < 1.0 ) {
  6831. mpars.transparent = m.transparent;
  6832. }
  6833. if ( m.depthTest !== undefined ) {
  6834. mpars.depthTest = m.depthTest;
  6835. }
  6836. if ( m.depthWrite !== undefined ) {
  6837. mpars.depthWrite = m.depthWrite;
  6838. }
  6839. if ( m.vertexColors !== undefined ) {
  6840. if ( m.vertexColors == "face" ) {
  6841. mpars.vertexColors = THREE.FaceColors;
  6842. } else if ( m.vertexColors ) {
  6843. mpars.vertexColors = THREE.VertexColors;
  6844. }
  6845. }
  6846. // colors
  6847. if ( m.colorDiffuse ) {
  6848. mpars.color = rgb2hex( m.colorDiffuse );
  6849. } else if ( m.DbgColor ) {
  6850. mpars.color = m.DbgColor;
  6851. }
  6852. if ( m.colorSpecular ) {
  6853. mpars.specular = rgb2hex( m.colorSpecular );
  6854. }
  6855. if ( m.colorAmbient ) {
  6856. mpars.ambient = rgb2hex( m.colorAmbient );
  6857. }
  6858. // modifiers
  6859. if ( m.transparency ) {
  6860. mpars.opacity = m.transparency;
  6861. }
  6862. if ( m.specularCoef ) {
  6863. mpars.shininess = m.specularCoef;
  6864. }
  6865. // textures
  6866. if ( m.mapDiffuse && texturePath ) {
  6867. create_texture( mpars, "map", m.mapDiffuse, m.mapDiffuseRepeat, m.mapDiffuseOffset, m.mapDiffuseWrap );
  6868. }
  6869. if ( m.mapLight && texturePath ) {
  6870. create_texture( mpars, "lightMap", m.mapLight, m.mapLightRepeat, m.mapLightOffset, m.mapLightWrap );
  6871. }
  6872. if ( m.mapNormal && texturePath ) {
  6873. create_texture( mpars, "normalMap", m.mapNormal, m.mapNormalRepeat, m.mapNormalOffset, m.mapNormalWrap );
  6874. }
  6875. if ( m.mapSpecular && texturePath ) {
  6876. create_texture( mpars, "specularMap", m.mapSpecular, m.mapSpecularRepeat, m.mapSpecularOffset, m.mapSpecularWrap );
  6877. }
  6878. // special case for normal mapped material
  6879. if ( m.mapNormal ) {
  6880. var shader = THREE.ShaderUtils.lib[ "normal" ];
  6881. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  6882. uniforms[ "tNormal" ].texture = mpars.normalMap;
  6883. if ( m.mapNormalFactor ) {
  6884. uniforms[ "uNormalScale" ].value = m.mapNormalFactor;
  6885. }
  6886. if ( mpars.map ) {
  6887. uniforms[ "tDiffuse" ].texture = mpars.map;
  6888. uniforms[ "enableDiffuse" ].value = true;
  6889. }
  6890. if ( mpars.specularMap ) {
  6891. uniforms[ "tSpecular" ].texture = mpars.specularMap;
  6892. uniforms[ "enableSpecular" ].value = true;
  6893. }
  6894. if ( mpars.lightMap ) {
  6895. uniforms[ "tAO" ].texture = mpars.lightMap;
  6896. uniforms[ "enableAO" ].value = true;
  6897. }
  6898. // for the moment don't handle displacement texture
  6899. uniforms[ "uDiffuseColor" ].value.setHex( mpars.color );
  6900. uniforms[ "uSpecularColor" ].value.setHex( mpars.specular );
  6901. uniforms[ "uAmbientColor" ].value.setHex( mpars.ambient );
  6902. uniforms[ "uShininess" ].value = mpars.shininess;
  6903. if ( mpars.opacity !== undefined ) {
  6904. uniforms[ "uOpacity" ].value = mpars.opacity;
  6905. }
  6906. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  6907. var material = new THREE.ShaderMaterial( parameters );
  6908. } else {
  6909. var material = new THREE[ mtype ]( mpars );
  6910. }
  6911. if ( m.DbgName !== undefined ) material.name = m.DbgName;
  6912. return material;
  6913. }
  6914. };
  6915. /**
  6916. * @author alteredq / http://alteredqualia.com/
  6917. */
  6918. THREE.BinaryLoader = function ( showStatus ) {
  6919. THREE.Loader.call( this, showStatus );
  6920. };
  6921. THREE.BinaryLoader.prototype = new THREE.Loader();
  6922. THREE.BinaryLoader.prototype.constructor = THREE.BinaryLoader;
  6923. THREE.BinaryLoader.prototype.supr = THREE.Loader.prototype;
  6924. // Load models generated by slim OBJ converter with BINARY option (converter_obj_three_slim.py -t binary)
  6925. // - binary models consist of two files: JS and BIN
  6926. // - parameters
  6927. // - url (required)
  6928. // - callback (required)
  6929. // - texturePath (optional: if not specified, textures will be assumed to be in the same folder as JS model file)
  6930. // - binaryPath (optional: if not specified, binary file will be assumed to be in the same folder as JS model file)
  6931. THREE.BinaryLoader.prototype.load = function( url, callback, texturePath, binaryPath ) {
  6932. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  6933. binaryPath = binaryPath ? binaryPath : this.extractUrlBase( url );
  6934. var callbackProgress = this.showProgress ? THREE.Loader.prototype.updateProgress : null;
  6935. this.onLoadStart();
  6936. // #1 load JS part via web worker
  6937. this.loadAjaxJSON( this, url, callback, texturePath, binaryPath, callbackProgress );
  6938. };
  6939. THREE.BinaryLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, binaryPath, callbackProgress ) {
  6940. var xhr = new XMLHttpRequest();
  6941. xhr.onreadystatechange = function () {
  6942. if ( xhr.readyState == 4 ) {
  6943. if ( xhr.status == 200 || xhr.status == 0 ) {
  6944. var json = JSON.parse( xhr.responseText );
  6945. context.loadAjaxBuffers( json, callback, binaryPath, texturePath, callbackProgress );
  6946. } else {
  6947. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6948. }
  6949. }
  6950. };
  6951. xhr.open( "GET", url, true );
  6952. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  6953. xhr.setRequestHeader( "Content-Type", "text/plain" );
  6954. xhr.send( null );
  6955. };
  6956. THREE.BinaryLoader.prototype.loadAjaxBuffers = function ( json, callback, binaryPath, texturePath, callbackProgress ) {
  6957. var xhr = new XMLHttpRequest(),
  6958. url = binaryPath + "/" + json.buffers;
  6959. var length = 0;
  6960. xhr.onreadystatechange = function () {
  6961. if ( xhr.readyState == 4 ) {
  6962. if ( xhr.status == 200 || xhr.status == 0 ) {
  6963. THREE.BinaryLoader.prototype.createBinModel( xhr.response, callback, texturePath, json.materials );
  6964. } else {
  6965. console.error( "THREE.BinaryLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  6966. }
  6967. } else if ( xhr.readyState == 3 ) {
  6968. if ( callbackProgress ) {
  6969. if ( length == 0 ) {
  6970. length = xhr.getResponseHeader( "Content-Length" );
  6971. }
  6972. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  6973. }
  6974. } else if ( xhr.readyState == 2 ) {
  6975. length = xhr.getResponseHeader( "Content-Length" );
  6976. }
  6977. };
  6978. xhr.open( "GET", url, true );
  6979. xhr.responseType = "arraybuffer";
  6980. xhr.send( null );
  6981. };
  6982. // Binary AJAX parser
  6983. THREE.BinaryLoader.prototype.createBinModel = function ( data, callback, texturePath, materials ) {
  6984. var Model = function ( texturePath ) {
  6985. var scope = this,
  6986. currentOffset = 0,
  6987. md,
  6988. normals = [],
  6989. uvs = [],
  6990. start_tri_flat, start_tri_smooth, start_tri_flat_uv, start_tri_smooth_uv,
  6991. start_quad_flat, start_quad_smooth, start_quad_flat_uv, start_quad_smooth_uv,
  6992. tri_size, quad_size,
  6993. len_tri_flat, len_tri_smooth, len_tri_flat_uv, len_tri_smooth_uv,
  6994. len_quad_flat, len_quad_smooth, len_quad_flat_uv, len_quad_smooth_uv;
  6995. THREE.Geometry.call( this );
  6996. THREE.Loader.prototype.initMaterials( scope, materials, texturePath );
  6997. md = parseMetaData( data, currentOffset );
  6998. currentOffset += md.header_bytes;
  6999. /*
  7000. md.vertex_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  7001. md.material_index_bytes = Uint16Array.BYTES_PER_ELEMENT;
  7002. md.normal_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  7003. md.uv_index_bytes = Uint32Array.BYTES_PER_ELEMENT;
  7004. */
  7005. // buffers sizes
  7006. tri_size = md.vertex_index_bytes * 3 + md.material_index_bytes;
  7007. quad_size = md.vertex_index_bytes * 4 + md.material_index_bytes;
  7008. len_tri_flat = md.ntri_flat * ( tri_size );
  7009. len_tri_smooth = md.ntri_smooth * ( tri_size + md.normal_index_bytes * 3 );
  7010. len_tri_flat_uv = md.ntri_flat_uv * ( tri_size + md.uv_index_bytes * 3 );
  7011. len_tri_smooth_uv = md.ntri_smooth_uv * ( tri_size + md.normal_index_bytes * 3 + md.uv_index_bytes * 3 );
  7012. len_quad_flat = md.nquad_flat * ( quad_size );
  7013. len_quad_smooth = md.nquad_smooth * ( quad_size + md.normal_index_bytes * 4 );
  7014. len_quad_flat_uv = md.nquad_flat_uv * ( quad_size + md.uv_index_bytes * 4 );
  7015. len_quad_smooth_uv = md.nquad_smooth_uv * ( quad_size + md.normal_index_bytes * 4 + md.uv_index_bytes * 4 );
  7016. // read buffers
  7017. currentOffset += init_vertices( currentOffset );
  7018. currentOffset += init_normals( currentOffset );
  7019. currentOffset += handlePadding( md.nnormals * 3 );
  7020. currentOffset += init_uvs( currentOffset );
  7021. start_tri_flat = currentOffset;
  7022. start_tri_smooth = start_tri_flat + len_tri_flat + handlePadding( md.ntri_flat * 2 );
  7023. start_tri_flat_uv = start_tri_smooth + len_tri_smooth + handlePadding( md.ntri_smooth * 2 );
  7024. start_tri_smooth_uv = start_tri_flat_uv + len_tri_flat_uv + handlePadding( md.ntri_flat_uv * 2 );
  7025. start_quad_flat = start_tri_smooth_uv + len_tri_smooth_uv + handlePadding( md.ntri_smooth_uv * 2 );
  7026. start_quad_smooth = start_quad_flat + len_quad_flat + handlePadding( md.nquad_flat * 2 );
  7027. start_quad_flat_uv = start_quad_smooth + len_quad_smooth + handlePadding( md.nquad_smooth * 2 );
  7028. start_quad_smooth_uv= start_quad_flat_uv + len_quad_flat_uv + handlePadding( md.nquad_flat_uv * 2 );
  7029. // have to first process faces with uvs
  7030. // so that face and uv indices match
  7031. init_triangles_flat_uv( start_tri_flat_uv );
  7032. init_triangles_smooth_uv( start_tri_smooth_uv );
  7033. init_quads_flat_uv( start_quad_flat_uv );
  7034. init_quads_smooth_uv( start_quad_smooth_uv );
  7035. // now we can process untextured faces
  7036. init_triangles_flat( start_tri_flat );
  7037. init_triangles_smooth( start_tri_smooth );
  7038. init_quads_flat( start_quad_flat );
  7039. init_quads_smooth( start_quad_smooth );
  7040. this.computeCentroids();
  7041. this.computeFaceNormals();
  7042. if ( THREE.Loader.prototype.hasNormals( this ) ) this.computeTangents();
  7043. function handlePadding( n ) {
  7044. return ( n % 4 ) ? ( 4 - n % 4 ) : 0;
  7045. };
  7046. function parseMetaData( data, offset ) {
  7047. var metaData = {
  7048. 'signature' :parseString( data, offset, 12 ),
  7049. 'header_bytes' :parseUChar8( data, offset + 12 ),
  7050. 'vertex_coordinate_bytes' :parseUChar8( data, offset + 13 ),
  7051. 'normal_coordinate_bytes' :parseUChar8( data, offset + 14 ),
  7052. 'uv_coordinate_bytes' :parseUChar8( data, offset + 15 ),
  7053. 'vertex_index_bytes' :parseUChar8( data, offset + 16 ),
  7054. 'normal_index_bytes' :parseUChar8( data, offset + 17 ),
  7055. 'uv_index_bytes' :parseUChar8( data, offset + 18 ),
  7056. 'material_index_bytes' :parseUChar8( data, offset + 19 ),
  7057. 'nvertices' :parseUInt32( data, offset + 20 ),
  7058. 'nnormals' :parseUInt32( data, offset + 20 + 4*1 ),
  7059. 'nuvs' :parseUInt32( data, offset + 20 + 4*2 ),
  7060. 'ntri_flat' :parseUInt32( data, offset + 20 + 4*3 ),
  7061. 'ntri_smooth' :parseUInt32( data, offset + 20 + 4*4 ),
  7062. 'ntri_flat_uv' :parseUInt32( data, offset + 20 + 4*5 ),
  7063. 'ntri_smooth_uv' :parseUInt32( data, offset + 20 + 4*6 ),
  7064. 'nquad_flat' :parseUInt32( data, offset + 20 + 4*7 ),
  7065. 'nquad_smooth' :parseUInt32( data, offset + 20 + 4*8 ),
  7066. 'nquad_flat_uv' :parseUInt32( data, offset + 20 + 4*9 ),
  7067. 'nquad_smooth_uv' :parseUInt32( data, offset + 20 + 4*10 )
  7068. };
  7069. /*
  7070. console.log( "signature: " + metaData.signature );
  7071. console.log( "header_bytes: " + metaData.header_bytes );
  7072. console.log( "vertex_coordinate_bytes: " + metaData.vertex_coordinate_bytes );
  7073. console.log( "normal_coordinate_bytes: " + metaData.normal_coordinate_bytes );
  7074. console.log( "uv_coordinate_bytes: " + metaData.uv_coordinate_bytes );
  7075. console.log( "vertex_index_bytes: " + metaData.vertex_index_bytes );
  7076. console.log( "normal_index_bytes: " + metaData.normal_index_bytes );
  7077. console.log( "uv_index_bytes: " + metaData.uv_index_bytes );
  7078. console.log( "material_index_bytes: " + metaData.material_index_bytes );
  7079. console.log( "nvertices: " + metaData.nvertices );
  7080. console.log( "nnormals: " + metaData.nnormals );
  7081. console.log( "nuvs: " + metaData.nuvs );
  7082. console.log( "ntri_flat: " + metaData.ntri_flat );
  7083. console.log( "ntri_smooth: " + metaData.ntri_smooth );
  7084. console.log( "ntri_flat_uv: " + metaData.ntri_flat_uv );
  7085. console.log( "ntri_smooth_uv: " + metaData.ntri_smooth_uv );
  7086. console.log( "nquad_flat: " + metaData.nquad_flat );
  7087. console.log( "nquad_smooth: " + metaData.nquad_smooth );
  7088. console.log( "nquad_flat_uv: " + metaData.nquad_flat_uv );
  7089. console.log( "nquad_smooth_uv: " + metaData.nquad_smooth_uv );
  7090. var total = metaData.header_bytes
  7091. + metaData.nvertices * metaData.vertex_coordinate_bytes * 3
  7092. + metaData.nnormals * metaData.normal_coordinate_bytes * 3
  7093. + metaData.nuvs * metaData.uv_coordinate_bytes * 2
  7094. + metaData.ntri_flat * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes )
  7095. + metaData.ntri_smooth * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 )
  7096. + metaData.ntri_flat_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.uv_index_bytes*3 )
  7097. + metaData.ntri_smooth_uv * ( metaData.vertex_index_bytes*3 + metaData.material_index_bytes + metaData.normal_index_bytes*3 + metaData.uv_index_bytes*3 )
  7098. + metaData.nquad_flat * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes )
  7099. + metaData.nquad_smooth * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 )
  7100. + metaData.nquad_flat_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.uv_index_bytes*4 )
  7101. + metaData.nquad_smooth_uv * ( metaData.vertex_index_bytes*4 + metaData.material_index_bytes + metaData.normal_index_bytes*4 + metaData.uv_index_bytes*4 );
  7102. console.log( "total bytes: " + total );
  7103. */
  7104. return metaData;
  7105. };
  7106. function parseString( data, offset, length ) {
  7107. var charArray = new Uint8Array( data, offset, length );
  7108. var text = "";
  7109. for ( var i = 0; i < length; i ++ ) {
  7110. text += String.fromCharCode( charArray[ offset + i ] );
  7111. }
  7112. return text;
  7113. };
  7114. function parseUChar8( data, offset ) {
  7115. var charArray = new Uint8Array( data, offset, 1 );
  7116. return charArray[ 0 ];
  7117. };
  7118. function parseUInt32( data, offset ) {
  7119. var intArray = new Uint32Array( data, offset, 1 );
  7120. return intArray[ 0 ];
  7121. };
  7122. function init_vertices( start ) {
  7123. var nElements = md.nvertices;
  7124. var coordArray = new Float32Array( data, start, nElements * 3 );
  7125. var i, x, y, z;
  7126. for( i = 0; i < nElements; i ++ ) {
  7127. x = coordArray[ i * 3 ];
  7128. y = coordArray[ i * 3 + 1 ];
  7129. z = coordArray[ i * 3 + 2 ];
  7130. vertex( scope, x, y, z );
  7131. }
  7132. return nElements * 3 * Float32Array.BYTES_PER_ELEMENT;
  7133. };
  7134. function init_normals( start ) {
  7135. var nElements = md.nnormals;
  7136. if ( nElements ) {
  7137. var normalArray = new Int8Array( data, start, nElements * 3 );
  7138. var i, x, y, z;
  7139. for( i = 0; i < nElements; i ++ ) {
  7140. x = normalArray[ i * 3 ];
  7141. y = normalArray[ i * 3 + 1 ];
  7142. z = normalArray[ i * 3 + 2 ];
  7143. normals.push( x/127, y/127, z/127 );
  7144. }
  7145. }
  7146. return nElements * 3 * Int8Array.BYTES_PER_ELEMENT;
  7147. };
  7148. function init_uvs( start ) {
  7149. var nElements = md.nuvs;
  7150. if ( nElements ) {
  7151. var uvArray = new Float32Array( data, start, nElements * 2 );
  7152. var i, u, v;
  7153. for( i = 0; i < nElements; i ++ ) {
  7154. u = uvArray[ i * 2 ];
  7155. v = uvArray[ i * 2 + 1 ];
  7156. uvs.push( u, v );
  7157. }
  7158. }
  7159. return nElements * 2 * Float32Array.BYTES_PER_ELEMENT;
  7160. };
  7161. function init_uvs3( nElements, offset ) {
  7162. var i, uva, uvb, uvc, u1, u2, u3, v1, v2, v3;
  7163. var uvIndexBuffer = new Uint32Array( data, offset, 3 * nElements );
  7164. for( i = 0; i < nElements; i ++ ) {
  7165. uva = uvIndexBuffer[ i * 3 ];
  7166. uvb = uvIndexBuffer[ i * 3 + 1 ];
  7167. uvc = uvIndexBuffer[ i * 3 + 2 ];
  7168. u1 = uvs[ uva*2 ];
  7169. v1 = uvs[ uva*2 + 1 ];
  7170. u2 = uvs[ uvb*2 ];
  7171. v2 = uvs[ uvb*2 + 1 ];
  7172. u3 = uvs[ uvc*2 ];
  7173. v3 = uvs[ uvc*2 + 1 ];
  7174. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  7175. }
  7176. };
  7177. function init_uvs4( nElements, offset ) {
  7178. var i, uva, uvb, uvc, uvd, u1, u2, u3, u4, v1, v2, v3, v4;
  7179. var uvIndexBuffer = new Uint32Array( data, offset, 4 * nElements );
  7180. for( i = 0; i < nElements; i ++ ) {
  7181. uva = uvIndexBuffer[ i * 4 ];
  7182. uvb = uvIndexBuffer[ i * 4 + 1 ];
  7183. uvc = uvIndexBuffer[ i * 4 + 2 ];
  7184. uvd = uvIndexBuffer[ i * 4 + 3 ];
  7185. u1 = uvs[ uva*2 ];
  7186. v1 = uvs[ uva*2 + 1 ];
  7187. u2 = uvs[ uvb*2 ];
  7188. v2 = uvs[ uvb*2 + 1 ];
  7189. u3 = uvs[ uvc*2 ];
  7190. v3 = uvs[ uvc*2 + 1 ];
  7191. u4 = uvs[ uvd*2 ];
  7192. v4 = uvs[ uvd*2 + 1 ];
  7193. uv4( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3, u4, v4 );
  7194. }
  7195. };
  7196. function init_faces3_flat( nElements, offsetVertices, offsetMaterials ) {
  7197. var i, a, b, c, m;
  7198. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  7199. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  7200. for( i = 0; i < nElements; i ++ ) {
  7201. a = vertexIndexBuffer[ i * 3 ];
  7202. b = vertexIndexBuffer[ i * 3 + 1 ];
  7203. c = vertexIndexBuffer[ i * 3 + 2 ];
  7204. m = materialIndexBuffer[ i ];
  7205. f3( scope, a, b, c, m );
  7206. }
  7207. };
  7208. function init_faces4_flat( nElements, offsetVertices, offsetMaterials ) {
  7209. var i, a, b, c, d, m;
  7210. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  7211. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  7212. for( i = 0; i < nElements; i ++ ) {
  7213. a = vertexIndexBuffer[ i * 4 ];
  7214. b = vertexIndexBuffer[ i * 4 + 1 ];
  7215. c = vertexIndexBuffer[ i * 4 + 2 ];
  7216. d = vertexIndexBuffer[ i * 4 + 3 ];
  7217. m = materialIndexBuffer[ i ];
  7218. f4( scope, a, b, c, d, m );
  7219. }
  7220. };
  7221. function init_faces3_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  7222. var i, a, b, c, m;
  7223. var na, nb, nc;
  7224. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 3 * nElements );
  7225. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 3 * nElements );
  7226. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  7227. for( i = 0; i < nElements; i ++ ) {
  7228. a = vertexIndexBuffer[ i * 3 ];
  7229. b = vertexIndexBuffer[ i * 3 + 1 ];
  7230. c = vertexIndexBuffer[ i * 3 + 2 ];
  7231. na = normalIndexBuffer[ i * 3 ];
  7232. nb = normalIndexBuffer[ i * 3 + 1 ];
  7233. nc = normalIndexBuffer[ i * 3 + 2 ];
  7234. m = materialIndexBuffer[ i ];
  7235. f3n( scope, normals, a, b, c, m, na, nb, nc );
  7236. }
  7237. };
  7238. function init_faces4_smooth( nElements, offsetVertices, offsetNormals, offsetMaterials ) {
  7239. var i, a, b, c, d, m;
  7240. var na, nb, nc, nd;
  7241. var vertexIndexBuffer = new Uint32Array( data, offsetVertices, 4 * nElements );
  7242. var normalIndexBuffer = new Uint32Array( data, offsetNormals, 4 * nElements );
  7243. var materialIndexBuffer = new Uint16Array( data, offsetMaterials, nElements );
  7244. for( i = 0; i < nElements; i ++ ) {
  7245. a = vertexIndexBuffer[ i * 4 ];
  7246. b = vertexIndexBuffer[ i * 4 + 1 ];
  7247. c = vertexIndexBuffer[ i * 4 + 2 ];
  7248. d = vertexIndexBuffer[ i * 4 + 3 ];
  7249. na = normalIndexBuffer[ i * 4 ];
  7250. nb = normalIndexBuffer[ i * 4 + 1 ];
  7251. nc = normalIndexBuffer[ i * 4 + 2 ];
  7252. nd = normalIndexBuffer[ i * 4 + 3 ];
  7253. m = materialIndexBuffer[ i ];
  7254. f4n( scope, normals, a, b, c, d, m, na, nb, nc, nd );
  7255. }
  7256. };
  7257. function init_triangles_flat( start ) {
  7258. var nElements = md.ntri_flat;
  7259. if ( nElements ) {
  7260. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7261. init_faces3_flat( nElements, start, offsetMaterials );
  7262. }
  7263. };
  7264. function init_triangles_flat_uv( start ) {
  7265. var nElements = md.ntri_flat_uv;
  7266. if ( nElements ) {
  7267. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7268. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7269. init_faces3_flat( nElements, start, offsetMaterials );
  7270. init_uvs3( nElements, offsetUvs );
  7271. }
  7272. };
  7273. function init_triangles_smooth( start ) {
  7274. var nElements = md.ntri_smooth;
  7275. if ( nElements ) {
  7276. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7277. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7278. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  7279. }
  7280. };
  7281. function init_triangles_smooth_uv( start ) {
  7282. var nElements = md.ntri_smooth_uv;
  7283. if ( nElements ) {
  7284. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7285. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7286. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 3;
  7287. init_faces3_smooth( nElements, start, offsetNormals, offsetMaterials );
  7288. init_uvs3( nElements, offsetUvs );
  7289. }
  7290. };
  7291. function init_quads_flat( start ) {
  7292. var nElements = md.nquad_flat;
  7293. if ( nElements ) {
  7294. var offsetMaterials = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7295. init_faces4_flat( nElements, start, offsetMaterials );
  7296. }
  7297. };
  7298. function init_quads_flat_uv( start ) {
  7299. var nElements = md.nquad_flat_uv;
  7300. if ( nElements ) {
  7301. var offsetUvs = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7302. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7303. init_faces4_flat( nElements, start, offsetMaterials );
  7304. init_uvs4( nElements, offsetUvs );
  7305. }
  7306. };
  7307. function init_quads_smooth( start ) {
  7308. var nElements = md.nquad_smooth;
  7309. if ( nElements ) {
  7310. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7311. var offsetMaterials = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7312. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  7313. }
  7314. };
  7315. function init_quads_smooth_uv( start ) {
  7316. var nElements = md.nquad_smooth_uv;
  7317. if ( nElements ) {
  7318. var offsetNormals = start + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7319. var offsetUvs = offsetNormals + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7320. var offsetMaterials = offsetUvs + nElements * Uint32Array.BYTES_PER_ELEMENT * 4;
  7321. init_faces4_smooth( nElements, start, offsetNormals, offsetMaterials );
  7322. init_uvs4( nElements, offsetUvs );
  7323. }
  7324. };
  7325. };
  7326. function vertex ( scope, x, y, z ) {
  7327. scope.vertices.push( new THREE.Vertex( x, y, z ) );
  7328. };
  7329. function f3 ( scope, a, b, c, mi ) {
  7330. scope.faces.push( new THREE.Face3( a, b, c, null, null, mi ) );
  7331. };
  7332. function f4 ( scope, a, b, c, d, mi ) {
  7333. scope.faces.push( new THREE.Face4( a, b, c, d, null, null, mi ) );
  7334. };
  7335. function f3n ( scope, normals, a, b, c, mi, na, nb, nc ) {
  7336. var nax = normals[ na*3 ],
  7337. nay = normals[ na*3 + 1 ],
  7338. naz = normals[ na*3 + 2 ],
  7339. nbx = normals[ nb*3 ],
  7340. nby = normals[ nb*3 + 1 ],
  7341. nbz = normals[ nb*3 + 2 ],
  7342. ncx = normals[ nc*3 ],
  7343. ncy = normals[ nc*3 + 1 ],
  7344. ncz = normals[ nc*3 + 2 ];
  7345. scope.faces.push( new THREE.Face3( a, b, c,
  7346. [new THREE.Vector3( nax, nay, naz ),
  7347. new THREE.Vector3( nbx, nby, nbz ),
  7348. new THREE.Vector3( ncx, ncy, ncz )],
  7349. null,
  7350. mi ) );
  7351. };
  7352. function f4n ( scope, normals, a, b, c, d, mi, na, nb, nc, nd ) {
  7353. var nax = normals[ na*3 ],
  7354. nay = normals[ na*3 + 1 ],
  7355. naz = normals[ na*3 + 2 ],
  7356. nbx = normals[ nb*3 ],
  7357. nby = normals[ nb*3 + 1 ],
  7358. nbz = normals[ nb*3 + 2 ],
  7359. ncx = normals[ nc*3 ],
  7360. ncy = normals[ nc*3 + 1 ],
  7361. ncz = normals[ nc*3 + 2 ],
  7362. ndx = normals[ nd*3 ],
  7363. ndy = normals[ nd*3 + 1 ],
  7364. ndz = normals[ nd*3 + 2 ];
  7365. scope.faces.push( new THREE.Face4( a, b, c, d,
  7366. [new THREE.Vector3( nax, nay, naz ),
  7367. new THREE.Vector3( nbx, nby, nbz ),
  7368. new THREE.Vector3( ncx, ncy, ncz ),
  7369. new THREE.Vector3( ndx, ndy, ndz )],
  7370. null,
  7371. mi ) );
  7372. };
  7373. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  7374. var uv = [];
  7375. uv.push( new THREE.UV( u1, v1 ) );
  7376. uv.push( new THREE.UV( u2, v2 ) );
  7377. uv.push( new THREE.UV( u3, v3 ) );
  7378. where.push( uv );
  7379. };
  7380. function uv4 ( where, u1, v1, u2, v2, u3, v3, u4, v4 ) {
  7381. var uv = [];
  7382. uv.push( new THREE.UV( u1, v1 ) );
  7383. uv.push( new THREE.UV( u2, v2 ) );
  7384. uv.push( new THREE.UV( u3, v3 ) );
  7385. uv.push( new THREE.UV( u4, v4 ) );
  7386. where.push( uv );
  7387. };
  7388. Model.prototype = new THREE.Geometry();
  7389. Model.prototype.constructor = Model;
  7390. callback( new Model( texturePath ) );
  7391. };
  7392. /**
  7393. * @author Tim Knip / http://www.floorplanner.com/ / tim at floorplanner.com
  7394. */
  7395. THREE.ColladaLoader = function () {
  7396. var COLLADA = null;
  7397. var scene = null;
  7398. var daeScene;
  7399. var readyCallbackFunc = null;
  7400. var sources = {};
  7401. var images = {};
  7402. var animations = {};
  7403. var controllers = {};
  7404. var geometries = {};
  7405. var materials = {};
  7406. var effects = {};
  7407. var cameras = {};
  7408. var animData;
  7409. var visualScenes;
  7410. var baseUrl;
  7411. var morphs;
  7412. var skins;
  7413. var flip_uv = true;
  7414. var preferredShading = THREE.SmoothShading;
  7415. var options = {
  7416. // Force Geometry to always be centered at the local origin of the
  7417. // containing Mesh.
  7418. centerGeometry: false,
  7419. // Axis conversion is done for geometries, animations, and controllers.
  7420. // If we ever pull cameras or lights out of the COLLADA file, they'll
  7421. // need extra work.
  7422. convertUpAxis: false,
  7423. subdivideFaces: true,
  7424. upAxis: 'Y'
  7425. };
  7426. // TODO: support unit conversion as well
  7427. var colladaUnit = 1.0;
  7428. var colladaUp = 'Y';
  7429. var upConversion = null;
  7430. var TO_RADIANS = Math.PI / 180;
  7431. function load ( url, readyCallback, progressCallback ) {
  7432. var length = 0;
  7433. if ( document.implementation && document.implementation.createDocument ) {
  7434. var req = new XMLHttpRequest();
  7435. if ( req.overrideMimeType ) req.overrideMimeType( "text/xml" );
  7436. req.onreadystatechange = function() {
  7437. if( req.readyState == 4 ) {
  7438. if( req.status == 0 || req.status == 200 ) {
  7439. if ( req.responseXML ) {
  7440. readyCallbackFunc = readyCallback;
  7441. parse( req.responseXML, undefined, url );
  7442. } else {
  7443. console.error( "ColladaLoader: Empty or non-existing file (" + url + ")" );
  7444. }
  7445. }
  7446. } else if ( req.readyState == 3 ) {
  7447. if ( progressCallback ) {
  7448. if ( length == 0 ) {
  7449. length = req.getResponseHeader( "Content-Length" );
  7450. }
  7451. progressCallback( { total: length, loaded: req.responseText.length } );
  7452. }
  7453. }
  7454. }
  7455. req.open( "GET", url, true );
  7456. req.send( null );
  7457. } else {
  7458. alert( "Don't know how to parse XML!" );
  7459. }
  7460. };
  7461. function parse( doc, callBack, url ) {
  7462. COLLADA = doc;
  7463. callBack = callBack || readyCallbackFunc;
  7464. if ( url !== undefined ) {
  7465. var parts = url.split( '/' );
  7466. parts.pop();
  7467. baseUrl = ( parts.length < 1 ? '.' : parts.join( '/' ) ) + '/';
  7468. }
  7469. parseAsset();
  7470. setUpConversion();
  7471. images = parseLib( "//dae:library_images/dae:image", _Image, "image" );
  7472. materials = parseLib( "//dae:library_materials/dae:material", Material, "material") ;
  7473. effects = parseLib( "//dae:library_effects/dae:effect", Effect, "effect" );
  7474. geometries = parseLib( "//dae:library_geometries/dae:geometry", Geometry, "geometry" );
  7475. cameras = parseLib( ".//dae:library_cameras/dae:camera", Camera, "camera" );
  7476. controllers = parseLib( "//dae:library_controllers/dae:controller", Controller, "controller" );
  7477. animations = parseLib( "//dae:library_animations/dae:animation", Animation, "animation" );
  7478. visualScenes = parseLib( ".//dae:library_visual_scenes/dae:visual_scene", VisualScene, "visual_scene" );
  7479. morphs = [];
  7480. skins = [];
  7481. daeScene = parseScene();
  7482. scene = new THREE.Object3D();
  7483. for ( var i = 0; i < daeScene.nodes.length; i ++ ) {
  7484. scene.add( createSceneGraph( daeScene.nodes[ i ] ) );
  7485. }
  7486. createAnimations();
  7487. var result = {
  7488. scene: scene,
  7489. morphs: morphs,
  7490. skins: skins,
  7491. animations: animData,
  7492. dae: {
  7493. images: images,
  7494. materials: materials,
  7495. cameras: cameras,
  7496. effects: effects,
  7497. geometries: geometries,
  7498. controllers: controllers,
  7499. animations: animations,
  7500. visualScenes: visualScenes,
  7501. scene: daeScene
  7502. }
  7503. };
  7504. if ( callBack ) {
  7505. callBack( result );
  7506. }
  7507. return result;
  7508. };
  7509. function setPreferredShading ( shading ) {
  7510. preferredShading = shading;
  7511. };
  7512. function parseAsset () {
  7513. var elements = COLLADA.evaluate( '//dae:asset', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  7514. var element = elements.iterateNext();
  7515. if ( element && element.childNodes ) {
  7516. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  7517. var child = element.childNodes[ i ];
  7518. switch ( child.nodeName ) {
  7519. case 'unit':
  7520. var meter = child.getAttribute( 'meter' );
  7521. if ( meter ) {
  7522. colladaUnit = parseFloat( meter );
  7523. }
  7524. break;
  7525. case 'up_axis':
  7526. colladaUp = child.textContent.charAt(0);
  7527. break;
  7528. }
  7529. }
  7530. }
  7531. };
  7532. function parseLib ( q, classSpec, prefix ) {
  7533. var elements = COLLADA.evaluate(q, COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null) ;
  7534. var lib = {};
  7535. var element = elements.iterateNext();
  7536. var i = 0;
  7537. while ( element ) {
  7538. var daeElement = ( new classSpec() ).parse( element );
  7539. if ( !daeElement.id || daeElement.id.length == 0 ) daeElement.id = prefix + ( i ++ );
  7540. lib[ daeElement.id ] = daeElement;
  7541. element = elements.iterateNext();
  7542. }
  7543. return lib;
  7544. };
  7545. function parseScene() {
  7546. var sceneElement = COLLADA.evaluate( './/dae:scene/dae:instance_visual_scene', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  7547. if ( sceneElement ) {
  7548. var url = sceneElement.getAttribute( 'url' ).replace( /^#/, '' );
  7549. return visualScenes[ url.length > 0 ? url : 'visual_scene0' ];
  7550. } else {
  7551. return null;
  7552. }
  7553. };
  7554. function createAnimations() {
  7555. animData = [];
  7556. // fill in the keys
  7557. recurseHierarchy( scene );
  7558. };
  7559. function recurseHierarchy( node ) {
  7560. var n = daeScene.getChildById( node.name, true ),
  7561. newData = null;
  7562. if ( n && n.keys ) {
  7563. newData = {
  7564. fps: 60,
  7565. hierarchy: [ {
  7566. node: n,
  7567. keys: n.keys,
  7568. sids: n.sids
  7569. } ],
  7570. node: node,
  7571. name: 'animation_' + node.name,
  7572. length: 0
  7573. };
  7574. animData.push(newData);
  7575. for ( var i = 0, il = n.keys.length; i < il; i++ ) {
  7576. newData.length = Math.max( newData.length, n.keys[i].time );
  7577. }
  7578. } else {
  7579. newData = {
  7580. hierarchy: [ {
  7581. keys: [],
  7582. sids: []
  7583. } ]
  7584. }
  7585. }
  7586. for ( var i = 0, il = node.children.length; i < il; i++ ) {
  7587. var d = recurseHierarchy( node.children[i] );
  7588. for ( var j = 0, jl = d.hierarchy.length; j < jl; j ++ ) {
  7589. newData.hierarchy.push( {
  7590. keys: [],
  7591. sids: []
  7592. } );
  7593. }
  7594. }
  7595. return newData;
  7596. };
  7597. function calcAnimationBounds () {
  7598. var start = 1000000;
  7599. var end = -start;
  7600. var frames = 0;
  7601. for ( var id in animations ) {
  7602. var animation = animations[ id ];
  7603. for ( var i = 0; i < animation.sampler.length; i ++ ) {
  7604. var sampler = animation.sampler[ i ];
  7605. sampler.create();
  7606. start = Math.min( start, sampler.startTime );
  7607. end = Math.max( end, sampler.endTime );
  7608. frames = Math.max( frames, sampler.input.length );
  7609. }
  7610. }
  7611. return { start:start, end:end, frames:frames };
  7612. };
  7613. function createMorph ( geometry, ctrl ) {
  7614. var morphCtrl = ctrl instanceof InstanceController ? controllers[ ctrl.url ] : ctrl;
  7615. if ( !morphCtrl || !morphCtrl.morph ) {
  7616. console.log("could not find morph controller!");
  7617. return;
  7618. }
  7619. var morph = morphCtrl.morph;
  7620. for ( var i = 0; i < morph.targets.length; i ++ ) {
  7621. var target_id = morph.targets[ i ];
  7622. var daeGeometry = geometries[ target_id ];
  7623. if ( !daeGeometry.mesh ||
  7624. !daeGeometry.mesh.primitives ||
  7625. !daeGeometry.mesh.primitives.length ) {
  7626. continue;
  7627. }
  7628. var target = daeGeometry.mesh.primitives[ 0 ].geometry;
  7629. if ( target.vertices.length === geometry.vertices.length ) {
  7630. geometry.morphTargets.push( { name: "target_1", vertices: target.vertices } );
  7631. }
  7632. }
  7633. geometry.morphTargets.push( { name: "target_Z", vertices: geometry.vertices } );
  7634. };
  7635. function createSkin ( geometry, ctrl, applyBindShape ) {
  7636. var skinCtrl = controllers[ ctrl.url ];
  7637. if ( !skinCtrl || !skinCtrl.skin ) {
  7638. console.log( "could not find skin controller!" );
  7639. return;
  7640. }
  7641. if ( !ctrl.skeleton || !ctrl.skeleton.length ) {
  7642. console.log( "could not find the skeleton for the skin!" );
  7643. return;
  7644. }
  7645. var skin = skinCtrl.skin;
  7646. var skeleton = daeScene.getChildById( ctrl.skeleton[ 0 ] );
  7647. var hierarchy = [];
  7648. applyBindShape = applyBindShape !== undefined ? applyBindShape : true;
  7649. var bones = [];
  7650. geometry.skinWeights = [];
  7651. geometry.skinIndices = [];
  7652. //createBones( geometry.bones, skin, hierarchy, skeleton, null, -1 );
  7653. //createWeights( skin, geometry.bones, geometry.skinIndices, geometry.skinWeights );
  7654. /*
  7655. geometry.animation = {
  7656. name: 'take_001',
  7657. fps: 30,
  7658. length: 2,
  7659. JIT: true,
  7660. hierarchy: hierarchy
  7661. };
  7662. */
  7663. if ( applyBindShape ) {
  7664. for ( var i = 0; i < geometry.vertices.length; i ++ ) {
  7665. skin.bindShapeMatrix.multiplyVector3( geometry.vertices[ i ] );
  7666. }
  7667. }
  7668. };
  7669. function setupSkeleton ( node, bones, frame, parent ) {
  7670. node.world = node.world || new THREE.Matrix4();
  7671. node.world.copy( node.matrix );
  7672. if ( node.channels && node.channels.length ) {
  7673. var channel = node.channels[ 0 ];
  7674. var m = channel.sampler.output[ frame ];
  7675. if ( m instanceof THREE.Matrix4 ) {
  7676. node.world.copy( m );
  7677. }
  7678. }
  7679. if ( parent ) {
  7680. node.world.multiply( parent, node.world );
  7681. }
  7682. bones.push( node );
  7683. for ( var i = 0; i < node.nodes.length; i ++ ) {
  7684. setupSkeleton( node.nodes[ i ], bones, frame, node.world );
  7685. }
  7686. };
  7687. function setupSkinningMatrices ( bones, skin ) {
  7688. // FIXME: this is dumb...
  7689. for ( var i = 0; i < bones.length; i ++ ) {
  7690. var bone = bones[ i ];
  7691. var found = -1;
  7692. if ( bone.type != 'JOINT' ) continue;
  7693. for ( var j = 0; j < skin.joints.length; j ++ ) {
  7694. if ( bone.sid == skin.joints[ j ] ) {
  7695. found = j;
  7696. break;
  7697. }
  7698. }
  7699. if ( found >= 0 ) {
  7700. var inv = skin.invBindMatrices[ found ];
  7701. bone.invBindMatrix = inv;
  7702. bone.skinningMatrix = new THREE.Matrix4();
  7703. bone.skinningMatrix.multiply(bone.world, inv); // (IBMi * JMi)
  7704. bone.weights = [];
  7705. for ( var j = 0; j < skin.weights.length; j ++ ) {
  7706. for (var k = 0; k < skin.weights[ j ].length; k ++) {
  7707. var w = skin.weights[ j ][ k ];
  7708. if ( w.joint == found ) {
  7709. bone.weights.push( w );
  7710. }
  7711. }
  7712. }
  7713. } else {
  7714. throw 'ColladaLoader: Could not find joint \'' + bone.sid + '\'.';
  7715. }
  7716. }
  7717. };
  7718. function applySkin ( geometry, instanceCtrl, frame ) {
  7719. var skinController = controllers[ instanceCtrl.url ];
  7720. frame = frame !== undefined ? frame : 40;
  7721. if ( !skinController || !skinController.skin ) {
  7722. console.log( 'ColladaLoader: Could not find skin controller.' );
  7723. return;
  7724. }
  7725. if ( !instanceCtrl.skeleton || !instanceCtrl.skeleton.length ) {
  7726. console.log( 'ColladaLoader: Could not find the skeleton for the skin. ' );
  7727. return;
  7728. }
  7729. var animationBounds = calcAnimationBounds();
  7730. var skeleton = daeScene.getChildById( instanceCtrl.skeleton[0], true ) ||
  7731. daeScene.getChildBySid( instanceCtrl.skeleton[0], true );
  7732. var i, j, w, vidx, weight;
  7733. var v = new THREE.Vector3(), o, s;
  7734. // move vertices to bind shape
  7735. for ( i = 0; i < geometry.vertices.length; i ++ ) {
  7736. skinController.skin.bindShapeMatrix.multiplyVector3( geometry.vertices[i] );
  7737. }
  7738. // process animation, or simply pose the rig if no animation
  7739. for ( frame = 0; frame < animationBounds.frames; frame ++ ) {
  7740. var bones = [];
  7741. var skinned = [];
  7742. // zero skinned vertices
  7743. for ( i = 0; i < geometry.vertices.length; i++ ) {
  7744. skinned.push( new THREE.Vertex() );
  7745. }
  7746. // process the frame and setup the rig with a fresh
  7747. // transform, possibly from the bone's animation channel(s)
  7748. setupSkeleton( skeleton, bones, frame );
  7749. setupSkinningMatrices( bones, skinController.skin );
  7750. // skin 'm
  7751. for ( i = 0; i < bones.length; i ++ ) {
  7752. if ( bones[ i ].type != 'JOINT' ) continue;
  7753. for ( j = 0; j < bones[ i ].weights.length; j ++ ) {
  7754. w = bones[ i ].weights[ j ];
  7755. vidx = w.index;
  7756. weight = w.weight;
  7757. o = geometry.vertices[vidx];
  7758. s = skinned[vidx];
  7759. v.x = o.x;
  7760. v.y = o.y;
  7761. v.z = o.z;
  7762. bones[i].skinningMatrix.multiplyVector3(v);
  7763. s.x += (v.x * weight);
  7764. s.y += (v.y * weight);
  7765. s.z += (v.z * weight);
  7766. }
  7767. }
  7768. geometry.morphTargets.push( { name: "target_" + frame, vertices: skinned } );
  7769. }
  7770. };
  7771. function createSceneGraph ( node, parent ) {
  7772. var obj = new THREE.Object3D();
  7773. var skinned = false;
  7774. var skinController;
  7775. var morphController;
  7776. var i, j;
  7777. // FIXME: controllers
  7778. for ( i = 0; i < node.controllers.length; i ++ ) {
  7779. var controller = controllers[ node.controllers[ i ].url ];
  7780. switch ( controller.type ) {
  7781. case 'skin':
  7782. if ( geometries[ controller.skin.source ] ) {
  7783. var inst_geom = new InstanceGeometry();
  7784. inst_geom.url = controller.skin.source;
  7785. inst_geom.instance_material = node.controllers[ i ].instance_material;
  7786. node.geometries.push( inst_geom );
  7787. skinned = true;
  7788. skinController = node.controllers[ i ];
  7789. } else if ( controllers[ controller.skin.source ] ) {
  7790. // urgh: controller can be chained
  7791. // handle the most basic case...
  7792. var second = controllers[ controller.skin.source ];
  7793. morphController = second;
  7794. // skinController = node.controllers[i];
  7795. if ( second.morph && geometries[ second.morph.source ] ) {
  7796. var inst_geom = new InstanceGeometry();
  7797. inst_geom.url = second.morph.source;
  7798. inst_geom.instance_material = node.controllers[ i ].instance_material;
  7799. node.geometries.push( inst_geom );
  7800. }
  7801. }
  7802. break;
  7803. case 'morph':
  7804. if ( geometries[ controller.morph.source ] ) {
  7805. var inst_geom = new InstanceGeometry();
  7806. inst_geom.url = controller.morph.source;
  7807. inst_geom.instance_material = node.controllers[ i ].instance_material;
  7808. node.geometries.push( inst_geom );
  7809. morphController = node.controllers[ i ];
  7810. }
  7811. console.log( 'ColladaLoader: Morph-controller partially supported.' );
  7812. default:
  7813. break;
  7814. }
  7815. }
  7816. // FIXME: multi-material mesh?
  7817. // geometries
  7818. for ( i = 0; i < node.geometries.length; i ++ ) {
  7819. var instance_geometry = node.geometries[i];
  7820. var instance_materials = instance_geometry.instance_material;
  7821. var geometry = geometries[instance_geometry.url];
  7822. var used_materials = {};
  7823. var used_materials_array = [];
  7824. var num_materials = 0;
  7825. var first_material;
  7826. if ( geometry ) {
  7827. if ( !geometry.mesh || !geometry.mesh.primitives )
  7828. continue;
  7829. if ( obj.name.length == 0 ) {
  7830. obj.name = geometry.id;
  7831. }
  7832. // collect used fx for this geometry-instance
  7833. if ( instance_materials ) {
  7834. for ( j = 0; j < instance_materials.length; j ++ ) {
  7835. var instance_material = instance_materials[ j ];
  7836. var mat = materials[ instance_material.target ];
  7837. var effect_id = mat.instance_effect.url;
  7838. var shader = effects[ effect_id ].shader;
  7839. shader.material.opacity = !shader.material.opacity ? 1 : shader.material.opacity;
  7840. used_materials[ instance_material.symbol ] = num_materials;
  7841. used_materials_array.push( shader.material )
  7842. first_material = shader.material;
  7843. first_material.name = mat.name == null || mat.name === '' ? mat.id : mat.name;
  7844. num_materials ++;
  7845. }
  7846. }
  7847. var mesh;
  7848. var material = first_material || new THREE.MeshLambertMaterial( { color: 0xdddddd, shading: THREE.FlatShading } );
  7849. var geom = geometry.mesh.geometry3js;
  7850. if ( num_materials > 1 ) {
  7851. material = new THREE.MeshFaceMaterial();
  7852. geom.materials = used_materials_array;
  7853. for ( j = 0; j < geom.faces.length; j ++ ) {
  7854. var face = geom.faces[ j ];
  7855. face.materialIndex = used_materials[ face.daeMaterial ]
  7856. }
  7857. }
  7858. if ( skinController !== undefined) {
  7859. applySkin( geom, skinController );
  7860. material.morphTargets = true;
  7861. mesh = new THREE.SkinnedMesh( geom, material );
  7862. mesh.skeleton = skinController.skeleton;
  7863. mesh.skinController = controllers[ skinController.url ];
  7864. mesh.skinInstanceController = skinController;
  7865. mesh.name = 'skin_' + skins.length;
  7866. skins.push( mesh );
  7867. } else if ( morphController !== undefined ) {
  7868. createMorph( geom, morphController );
  7869. material.morphTargets = true;
  7870. mesh = new THREE.Mesh( geom, material );
  7871. mesh.name = 'morph_' + morphs.length;
  7872. morphs.push( mesh );
  7873. } else {
  7874. mesh = new THREE.Mesh( geom, material );
  7875. // mesh.geom.name = geometry.id;
  7876. }
  7877. node.geometries.length > 1 ? obj.add( mesh ) : obj = mesh;
  7878. }
  7879. }
  7880. for ( i = 0; i < node.cameras.length; i ++ ) {
  7881. var instance_camera = node.cameras[i];
  7882. var cparams = cameras[instance_camera.url];
  7883. obj = new THREE.PerspectiveCamera(cparams.fov, cparams.aspect_ratio, cparams.znear, cparams.zfar);
  7884. }
  7885. obj.name = node.id || "";
  7886. obj.matrix = node.matrix;
  7887. var props = node.matrix.decompose();
  7888. obj.position = props[ 0 ];
  7889. obj.quaternion = props[ 1 ];
  7890. obj.useQuaternion = true;
  7891. obj.scale = props[ 2 ];
  7892. if ( options.centerGeometry && obj.geometry ) {
  7893. var delta = THREE.GeometryUtils.center( obj.geometry );
  7894. obj.quaternion.multiplyVector3( delta.multiplySelf( obj.scale ) );
  7895. obj.position.subSelf( delta );
  7896. }
  7897. for ( i = 0; i < node.nodes.length; i ++ ) {
  7898. obj.add( createSceneGraph( node.nodes[i], node ) );
  7899. }
  7900. return obj;
  7901. };
  7902. function getJointId( skin, id ) {
  7903. for ( var i = 0; i < skin.joints.length; i ++ ) {
  7904. if ( skin.joints[ i ] == id ) {
  7905. return i;
  7906. }
  7907. }
  7908. };
  7909. function getLibraryNode( id ) {
  7910. return COLLADA.evaluate( './/dae:library_nodes//dae:node[@id=\'' + id + '\']', COLLADA, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null ).iterateNext();
  7911. };
  7912. function getChannelsForNode (node ) {
  7913. var channels = [];
  7914. var startTime = 1000000;
  7915. var endTime = -1000000;
  7916. for ( var id in animations ) {
  7917. var animation = animations[id];
  7918. for ( var i = 0; i < animation.channel.length; i ++ ) {
  7919. var channel = animation.channel[i];
  7920. var sampler = animation.sampler[i];
  7921. var id = channel.target.split('/')[0];
  7922. if ( id == node.id ) {
  7923. sampler.create();
  7924. channel.sampler = sampler;
  7925. startTime = Math.min(startTime, sampler.startTime);
  7926. endTime = Math.max(endTime, sampler.endTime);
  7927. channels.push(channel);
  7928. }
  7929. }
  7930. }
  7931. if ( channels.length ) {
  7932. node.startTime = startTime;
  7933. node.endTime = endTime;
  7934. }
  7935. return channels;
  7936. };
  7937. function calcFrameDuration( node ) {
  7938. var minT = 10000000;
  7939. for ( var i = 0; i < node.channels.length; i ++ ) {
  7940. var sampler = node.channels[i].sampler;
  7941. for ( var j = 0; j < sampler.input.length - 1; j ++ ) {
  7942. var t0 = sampler.input[ j ];
  7943. var t1 = sampler.input[ j + 1 ];
  7944. minT = Math.min( minT, t1 - t0 );
  7945. }
  7946. }
  7947. return minT;
  7948. };
  7949. function calcMatrixAt( node, t ) {
  7950. var animated = {};
  7951. var i, j;
  7952. for ( i = 0; i < node.channels.length; i ++ ) {
  7953. var channel = node.channels[ i ];
  7954. animated[ channel.sid ] = channel;
  7955. }
  7956. var matrix = new THREE.Matrix4();
  7957. for ( i = 0; i < node.transforms.length; i ++ ) {
  7958. var transform = node.transforms[ i ];
  7959. var channel = animated[ transform.sid ];
  7960. if ( channel !== undefined ) {
  7961. var sampler = channel.sampler;
  7962. var value;
  7963. for ( j = 0; j < sampler.input.length - 1; j ++ ) {
  7964. if ( sampler.input[ j + 1 ] > t ) {
  7965. value = sampler.output[ j ];
  7966. //console.log(value.flatten)
  7967. break;
  7968. }
  7969. }
  7970. if ( value !== undefined ) {
  7971. if ( value instanceof THREE.Matrix4 ) {
  7972. matrix = matrix.multiply( matrix, value );
  7973. } else {
  7974. // FIXME: handle other types
  7975. matrix = matrix.multiply( matrix, transform.matrix );
  7976. }
  7977. } else {
  7978. matrix = matrix.multiply( matrix, transform.matrix );
  7979. }
  7980. } else {
  7981. matrix = matrix.multiply( matrix, transform.matrix );
  7982. }
  7983. }
  7984. return matrix;
  7985. };
  7986. function bakeAnimations ( node ) {
  7987. if ( node.channels && node.channels.length ) {
  7988. var keys = [],
  7989. sids = [];
  7990. for ( var i = 0, il = node.channels.length; i < il; i++ ) {
  7991. var channel = node.channels[i],
  7992. fullSid = channel.fullSid,
  7993. sampler = channel.sampler,
  7994. input = sampler.input,
  7995. transform = node.getTransformBySid( channel.sid ),
  7996. member;
  7997. if ( channel.arrIndices ) {
  7998. member = [];
  7999. for ( var j = 0, jl = channel.arrIndices.length; j < jl; j++ ) {
  8000. member[ j ] = getConvertedIndex( channel.arrIndices[ j ] );
  8001. }
  8002. } else {
  8003. member = getConvertedMember( channel.member );
  8004. }
  8005. if ( transform ) {
  8006. if ( sids.indexOf( fullSid ) === -1 ) {
  8007. sids.push( fullSid );
  8008. }
  8009. for ( var j = 0, jl = input.length; j < jl; j++ ) {
  8010. var time = input[j],
  8011. data = sampler.getData( transform.type, j ),
  8012. key = findKey( keys, time );
  8013. if ( !key ) {
  8014. key = new Key( time );
  8015. var timeNdx = findTimeNdx( keys, time );
  8016. keys.splice( timeNdx == -1 ? keys.length : timeNdx, 0, key );
  8017. }
  8018. key.addTarget( fullSid, transform, member, data );
  8019. }
  8020. } else {
  8021. console.log( 'Could not find transform "' + channel.sid + '" in node ' + node.id );
  8022. }
  8023. }
  8024. // post process
  8025. for ( var i = 0; i < sids.length; i++ ) {
  8026. var sid = sids[ i ];
  8027. for ( var j = 0; j < keys.length; j++ ) {
  8028. var key = keys[ j ];
  8029. if ( !key.hasTarget( sid ) ) {
  8030. interpolateKeys( keys, key, j, sid );
  8031. }
  8032. }
  8033. }
  8034. node.keys = keys;
  8035. node.sids = sids;
  8036. }
  8037. };
  8038. function findKey ( keys, time) {
  8039. var retVal = null;
  8040. for ( var i = 0, il = keys.length; i < il && retVal == null; i++ ) {
  8041. var key = keys[i];
  8042. if ( key.time === time ) {
  8043. retVal = key;
  8044. } else if ( key.time > time ) {
  8045. break;
  8046. }
  8047. }
  8048. return retVal;
  8049. };
  8050. function findTimeNdx ( keys, time) {
  8051. var ndx = -1;
  8052. for ( var i = 0, il = keys.length; i < il && ndx == -1; i++ ) {
  8053. var key = keys[i];
  8054. if ( key.time >= time ) {
  8055. ndx = i;
  8056. }
  8057. }
  8058. return ndx;
  8059. };
  8060. function interpolateKeys ( keys, key, ndx, fullSid ) {
  8061. var prevKey = getPrevKeyWith( keys, fullSid, ndx ? ndx-1 : 0 ),
  8062. nextKey = getNextKeyWith( keys, fullSid, ndx+1 );
  8063. if ( prevKey && nextKey ) {
  8064. var scale = (key.time - prevKey.time) / (nextKey.time - prevKey.time),
  8065. prevTarget = prevKey.getTarget( fullSid ),
  8066. nextData = nextKey.getTarget( fullSid ).data,
  8067. prevData = prevTarget.data,
  8068. data;
  8069. if ( prevTarget.type === 'matrix' ) {
  8070. data = prevData;
  8071. } else if ( prevData.length ) {
  8072. data = [];
  8073. for ( var i = 0; i < prevData.length; ++i ) {
  8074. data[ i ] = prevData[ i ] + ( nextData[ i ] - prevData[ i ] ) * scale;
  8075. }
  8076. } else {
  8077. data = prevData + ( nextData - prevData ) * scale;
  8078. }
  8079. key.addTarget( fullSid, prevTarget.transform, prevTarget.member, data );
  8080. }
  8081. };
  8082. // Get next key with given sid
  8083. function getNextKeyWith( keys, fullSid, ndx ) {
  8084. for ( ; ndx < keys.length; ndx++ ) {
  8085. var key = keys[ ndx ];
  8086. if ( key.hasTarget( fullSid ) ) {
  8087. return key;
  8088. }
  8089. }
  8090. return null;
  8091. };
  8092. // Get previous key with given sid
  8093. function getPrevKeyWith( keys, fullSid, ndx ) {
  8094. ndx = ndx >= 0 ? ndx : ndx + keys.length;
  8095. for ( ; ndx >= 0; ndx-- ) {
  8096. var key = keys[ ndx ];
  8097. if ( key.hasTarget( fullSid ) ) {
  8098. return key;
  8099. }
  8100. }
  8101. return null;
  8102. };
  8103. function _Image() {
  8104. this.id = "";
  8105. this.init_from = "";
  8106. };
  8107. _Image.prototype.parse = function(element) {
  8108. this.id = element.getAttribute('id');
  8109. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8110. var child = element.childNodes[ i ];
  8111. if ( child.nodeName == 'init_from' ) {
  8112. this.init_from = child.textContent;
  8113. }
  8114. }
  8115. return this;
  8116. };
  8117. function Controller() {
  8118. this.id = "";
  8119. this.name = "";
  8120. this.type = "";
  8121. this.skin = null;
  8122. this.morph = null;
  8123. };
  8124. Controller.prototype.parse = function( element ) {
  8125. this.id = element.getAttribute('id');
  8126. this.name = element.getAttribute('name');
  8127. this.type = "none";
  8128. for ( var i = 0; i < element.childNodes.length; i++ ) {
  8129. var child = element.childNodes[ i ];
  8130. switch ( child.nodeName ) {
  8131. case 'skin':
  8132. this.skin = (new Skin()).parse(child);
  8133. this.type = child.nodeName;
  8134. break;
  8135. case 'morph':
  8136. this.morph = (new Morph()).parse(child);
  8137. this.type = child.nodeName;
  8138. break;
  8139. default:
  8140. break;
  8141. }
  8142. }
  8143. return this;
  8144. };
  8145. function Morph() {
  8146. this.method = null;
  8147. this.source = null;
  8148. this.targets = null;
  8149. this.weights = null;
  8150. };
  8151. Morph.prototype.parse = function( element ) {
  8152. var sources = {};
  8153. var inputs = [];
  8154. var i;
  8155. this.method = element.getAttribute( 'method' );
  8156. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  8157. for ( i = 0; i < element.childNodes.length; i ++ ) {
  8158. var child = element.childNodes[ i ];
  8159. if ( child.nodeType != 1 ) continue;
  8160. switch ( child.nodeName ) {
  8161. case 'source':
  8162. var source = ( new Source() ).parse( child );
  8163. sources[ source.id ] = source;
  8164. break;
  8165. case 'targets':
  8166. inputs = this.parseInputs( child );
  8167. break;
  8168. default:
  8169. console.log( child.nodeName );
  8170. break;
  8171. }
  8172. }
  8173. for ( i = 0; i < inputs.length; i ++ ) {
  8174. var input = inputs[ i ];
  8175. var source = sources[ input.source ];
  8176. switch ( input.semantic ) {
  8177. case 'MORPH_TARGET':
  8178. this.targets = source.read();
  8179. break;
  8180. case 'MORPH_WEIGHT':
  8181. this.weights = source.read();
  8182. break;
  8183. default:
  8184. break;
  8185. }
  8186. }
  8187. return this;
  8188. };
  8189. Morph.prototype.parseInputs = function(element) {
  8190. var inputs = [];
  8191. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8192. var child = element.childNodes[i];
  8193. if ( child.nodeType != 1) continue;
  8194. switch ( child.nodeName ) {
  8195. case 'input':
  8196. inputs.push( (new Input()).parse(child) );
  8197. break;
  8198. default:
  8199. break;
  8200. }
  8201. }
  8202. return inputs;
  8203. };
  8204. function Skin() {
  8205. this.source = "";
  8206. this.bindShapeMatrix = null;
  8207. this.invBindMatrices = [];
  8208. this.joints = [];
  8209. this.weights = [];
  8210. };
  8211. Skin.prototype.parse = function( element ) {
  8212. var sources = {};
  8213. var joints, weights;
  8214. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  8215. this.invBindMatrices = [];
  8216. this.joints = [];
  8217. this.weights = [];
  8218. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8219. var child = element.childNodes[i];
  8220. if ( child.nodeType != 1 ) continue;
  8221. switch ( child.nodeName ) {
  8222. case 'bind_shape_matrix':
  8223. var f = _floats(child.textContent);
  8224. this.bindShapeMatrix = getConvertedMat4( f );
  8225. break;
  8226. case 'source':
  8227. var src = new Source().parse(child);
  8228. sources[ src.id ] = src;
  8229. break;
  8230. case 'joints':
  8231. joints = child;
  8232. break;
  8233. case 'vertex_weights':
  8234. weights = child;
  8235. break;
  8236. default:
  8237. console.log( child.nodeName );
  8238. break;
  8239. }
  8240. }
  8241. this.parseJoints( joints, sources );
  8242. this.parseWeights( weights, sources );
  8243. return this;
  8244. };
  8245. Skin.prototype.parseJoints = function ( element, sources ) {
  8246. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8247. var child = element.childNodes[ i ];
  8248. if ( child.nodeType != 1 ) continue;
  8249. switch ( child.nodeName ) {
  8250. case 'input':
  8251. var input = ( new Input() ).parse( child );
  8252. var source = sources[ input.source ];
  8253. if ( input.semantic == 'JOINT' ) {
  8254. this.joints = source.read();
  8255. } else if ( input.semantic == 'INV_BIND_MATRIX' ) {
  8256. this.invBindMatrices = source.read();
  8257. }
  8258. break;
  8259. default:
  8260. break;
  8261. }
  8262. }
  8263. };
  8264. Skin.prototype.parseWeights = function ( element, sources ) {
  8265. var v, vcount, inputs = [];
  8266. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8267. var child = element.childNodes[ i ];
  8268. if ( child.nodeType != 1 ) continue;
  8269. switch ( child.nodeName ) {
  8270. case 'input':
  8271. inputs.push( ( new Input() ).parse( child ) );
  8272. break;
  8273. case 'v':
  8274. v = _ints( child.textContent );
  8275. break;
  8276. case 'vcount':
  8277. vcount = _ints( child.textContent );
  8278. break;
  8279. default:
  8280. break;
  8281. }
  8282. }
  8283. var index = 0;
  8284. for ( var i = 0; i < vcount.length; i ++ ) {
  8285. var numBones = vcount[i];
  8286. var vertex_weights = [];
  8287. for ( var j = 0; j < numBones; j++ ) {
  8288. var influence = {};
  8289. for ( var k = 0; k < inputs.length; k ++ ) {
  8290. var input = inputs[ k ];
  8291. var value = v[ index + input.offset ];
  8292. switch ( input.semantic ) {
  8293. case 'JOINT':
  8294. influence.joint = value;//this.joints[value];
  8295. break;
  8296. case 'WEIGHT':
  8297. influence.weight = sources[ input.source ].data[ value ];
  8298. break;
  8299. default:
  8300. break;
  8301. }
  8302. }
  8303. vertex_weights.push( influence );
  8304. index += inputs.length;
  8305. }
  8306. for ( var j = 0; j < vertex_weights.length; j ++ ) {
  8307. vertex_weights[ j ].index = i;
  8308. }
  8309. this.weights.push( vertex_weights );
  8310. }
  8311. };
  8312. function VisualScene () {
  8313. this.id = "";
  8314. this.name = "";
  8315. this.nodes = [];
  8316. this.scene = new THREE.Object3D();
  8317. };
  8318. VisualScene.prototype.getChildById = function( id, recursive ) {
  8319. for ( var i = 0; i < this.nodes.length; i ++ ) {
  8320. var node = this.nodes[ i ].getChildById( id, recursive );
  8321. if ( node ) {
  8322. return node;
  8323. }
  8324. }
  8325. return null;
  8326. };
  8327. VisualScene.prototype.getChildBySid = function( sid, recursive ) {
  8328. for ( var i = 0; i < this.nodes.length; i ++ ) {
  8329. var node = this.nodes[ i ].getChildBySid( sid, recursive );
  8330. if ( node ) {
  8331. return node;
  8332. }
  8333. }
  8334. return null;
  8335. };
  8336. VisualScene.prototype.parse = function( element ) {
  8337. this.id = element.getAttribute( 'id' );
  8338. this.name = element.getAttribute( 'name' );
  8339. this.nodes = [];
  8340. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8341. var child = element.childNodes[ i ];
  8342. if ( child.nodeType != 1 ) continue;
  8343. switch ( child.nodeName ) {
  8344. case 'node':
  8345. this.nodes.push( ( new Node() ).parse( child ) );
  8346. break;
  8347. default:
  8348. break;
  8349. }
  8350. }
  8351. return this;
  8352. };
  8353. function Node() {
  8354. this.id = "";
  8355. this.name = "";
  8356. this.sid = "";
  8357. this.nodes = [];
  8358. this.controllers = [];
  8359. this.transforms = [];
  8360. this.geometries = [];
  8361. this.channels = [];
  8362. this.matrix = new THREE.Matrix4();
  8363. };
  8364. Node.prototype.getChannelForTransform = function( transformSid ) {
  8365. for ( var i = 0; i < this.channels.length; i ++ ) {
  8366. var channel = this.channels[i];
  8367. var parts = channel.target.split('/');
  8368. var id = parts.shift();
  8369. var sid = parts.shift();
  8370. var dotSyntax = (sid.indexOf(".") >= 0);
  8371. var arrSyntax = (sid.indexOf("(") >= 0);
  8372. var arrIndices;
  8373. var member;
  8374. if ( dotSyntax ) {
  8375. parts = sid.split(".");
  8376. sid = parts.shift();
  8377. member = parts.shift();
  8378. } else if ( arrSyntax ) {
  8379. arrIndices = sid.split("(");
  8380. sid = arrIndices.shift();
  8381. for ( var j = 0; j < arrIndices.length; j ++ ) {
  8382. arrIndices[ j ] = parseInt( arrIndices[ j ].replace( /\)/, '' ) );
  8383. }
  8384. }
  8385. if ( sid == transformSid ) {
  8386. channel.info = { sid: sid, dotSyntax: dotSyntax, arrSyntax: arrSyntax, arrIndices: arrIndices };
  8387. return channel;
  8388. }
  8389. }
  8390. return null;
  8391. };
  8392. Node.prototype.getChildById = function ( id, recursive ) {
  8393. if ( this.id == id ) {
  8394. return this;
  8395. }
  8396. if ( recursive ) {
  8397. for ( var i = 0; i < this.nodes.length; i ++ ) {
  8398. var n = this.nodes[ i ].getChildById( id, recursive );
  8399. if ( n ) {
  8400. return n;
  8401. }
  8402. }
  8403. }
  8404. return null;
  8405. };
  8406. Node.prototype.getChildBySid = function ( sid, recursive ) {
  8407. if ( this.sid == sid ) {
  8408. return this;
  8409. }
  8410. if ( recursive ) {
  8411. for ( var i = 0; i < this.nodes.length; i ++ ) {
  8412. var n = this.nodes[ i ].getChildBySid( sid, recursive );
  8413. if ( n ) {
  8414. return n;
  8415. }
  8416. }
  8417. }
  8418. return null;
  8419. };
  8420. Node.prototype.getTransformBySid = function ( sid ) {
  8421. for ( var i = 0; i < this.transforms.length; i ++ ) {
  8422. if ( this.transforms[ i ].sid == sid ) return this.transforms[ i ];
  8423. }
  8424. return null;
  8425. };
  8426. Node.prototype.parse = function( element ) {
  8427. var url;
  8428. this.id = element.getAttribute('id');
  8429. this.sid = element.getAttribute('sid');
  8430. this.name = element.getAttribute('name');
  8431. this.type = element.getAttribute('type');
  8432. this.type = this.type == 'JOINT' ? this.type : 'NODE';
  8433. this.nodes = [];
  8434. this.transforms = [];
  8435. this.geometries = [];
  8436. this.cameras = [];
  8437. this.controllers = [];
  8438. this.matrix = new THREE.Matrix4();
  8439. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8440. var child = element.childNodes[ i ];
  8441. if ( child.nodeType != 1 ) continue;
  8442. switch ( child.nodeName ) {
  8443. case 'node':
  8444. this.nodes.push( ( new Node() ).parse( child ) );
  8445. break;
  8446. case 'instance_camera':
  8447. this.cameras.push( ( new InstanceCamera() ).parse( child ) );
  8448. break;
  8449. case 'instance_controller':
  8450. this.controllers.push( ( new InstanceController() ).parse( child ) );
  8451. break;
  8452. case 'instance_geometry':
  8453. this.geometries.push( ( new InstanceGeometry() ).parse( child ) );
  8454. break;
  8455. case 'instance_light':
  8456. break;
  8457. case 'instance_node':
  8458. url = child.getAttribute( 'url' ).replace( /^#/, '' );
  8459. var iNode = getLibraryNode( url );
  8460. if ( iNode ) {
  8461. this.nodes.push( ( new Node() ).parse( iNode )) ;
  8462. }
  8463. break;
  8464. case 'rotate':
  8465. case 'translate':
  8466. case 'scale':
  8467. case 'matrix':
  8468. case 'lookat':
  8469. case 'skew':
  8470. this.transforms.push( ( new Transform() ).parse( child ) );
  8471. break;
  8472. case 'extra':
  8473. break;
  8474. default:
  8475. console.log( child.nodeName );
  8476. break;
  8477. }
  8478. }
  8479. this.channels = getChannelsForNode( this );
  8480. bakeAnimations( this );
  8481. this.updateMatrix();
  8482. return this;
  8483. };
  8484. Node.prototype.updateMatrix = function () {
  8485. this.matrix.identity();
  8486. for ( var i = 0; i < this.transforms.length; i ++ ) {
  8487. this.transforms[ i ].apply( this.matrix );
  8488. }
  8489. };
  8490. function Transform () {
  8491. this.sid = "";
  8492. this.type = "";
  8493. this.data = [];
  8494. this.obj = null;
  8495. };
  8496. Transform.prototype.parse = function ( element ) {
  8497. this.sid = element.getAttribute( 'sid' );
  8498. this.type = element.nodeName;
  8499. this.data = _floats( element.textContent );
  8500. this.convert();
  8501. return this;
  8502. };
  8503. Transform.prototype.convert = function () {
  8504. switch ( this.type ) {
  8505. case 'matrix':
  8506. this.obj = getConvertedMat4( this.data );
  8507. break;
  8508. case 'rotate':
  8509. this.angle = this.data[3] * TO_RADIANS;
  8510. case 'translate':
  8511. fixCoords( this.data, -1 );
  8512. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  8513. break;
  8514. case 'scale':
  8515. fixCoords( this.data, 1 );
  8516. this.obj = new THREE.Vector3( this.data[ 0 ], this.data[ 1 ], this.data[ 2 ] );
  8517. break;
  8518. default:
  8519. console.log( 'Can not convert Transform of type ' + this.type );
  8520. break;
  8521. }
  8522. };
  8523. Transform.prototype.apply = function ( matrix ) {
  8524. switch ( this.type ) {
  8525. case 'matrix':
  8526. matrix.multiplySelf( this.obj );
  8527. break;
  8528. case 'translate':
  8529. matrix.translate( this.obj );
  8530. break;
  8531. case 'rotate':
  8532. matrix.rotateByAxis( this.obj, this.angle );
  8533. break;
  8534. case 'scale':
  8535. matrix.scale( this.obj );
  8536. break;
  8537. }
  8538. };
  8539. Transform.prototype.update = function ( data, member ) {
  8540. var members = [ 'X', 'Y', 'Z', 'ANGLE' ];
  8541. switch ( this.type ) {
  8542. case 'matrix':
  8543. if ( ! member ) {
  8544. this.obj.copy( data );
  8545. } else if ( member.length === 1 ) {
  8546. switch ( member[ 0 ] ) {
  8547. case 0:
  8548. this.obj.n11 = data[ 0 ];
  8549. this.obj.n21 = data[ 1 ];
  8550. this.obj.n31 = data[ 2 ];
  8551. this.obj.n41 = data[ 3 ];
  8552. break;
  8553. case 1:
  8554. this.obj.n12 = data[ 0 ];
  8555. this.obj.n22 = data[ 1 ];
  8556. this.obj.n32 = data[ 2 ];
  8557. this.obj.n42 = data[ 3 ];
  8558. break;
  8559. case 2:
  8560. this.obj.n13 = data[ 0 ];
  8561. this.obj.n23 = data[ 1 ];
  8562. this.obj.n33 = data[ 2 ];
  8563. this.obj.n43 = data[ 3 ];
  8564. break;
  8565. case 3:
  8566. this.obj.n14 = data[ 0 ];
  8567. this.obj.n24 = data[ 1 ];
  8568. this.obj.n34 = data[ 2 ];
  8569. this.obj.n44 = data[ 3 ];
  8570. break;
  8571. }
  8572. } else if ( member.length === 2 ) {
  8573. var propName = 'n' + ( member[ 0 ] + 1 ) + ( member[ 1 ] + 1 );
  8574. this.obj[ propName ] = data;
  8575. } else {
  8576. console.log('Incorrect addressing of matrix in transform.');
  8577. }
  8578. break;
  8579. case 'translate':
  8580. case 'scale':
  8581. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  8582. member = members[ member[ 0 ] ];
  8583. }
  8584. switch ( member ) {
  8585. case 'X':
  8586. this.obj.x = data;
  8587. break;
  8588. case 'Y':
  8589. this.obj.y = data;
  8590. break;
  8591. case 'Z':
  8592. this.obj.z = data;
  8593. break;
  8594. default:
  8595. this.obj.x = data[ 0 ];
  8596. this.obj.y = data[ 1 ];
  8597. this.obj.z = data[ 2 ];
  8598. break;
  8599. }
  8600. break;
  8601. case 'rotate':
  8602. if ( Object.prototype.toString.call( member ) === '[object Array]' ) {
  8603. member = members[ member[ 0 ] ];
  8604. }
  8605. switch ( member ) {
  8606. case 'X':
  8607. this.obj.x = data;
  8608. break;
  8609. case 'Y':
  8610. this.obj.y = data;
  8611. break;
  8612. case 'Z':
  8613. this.obj.z = data;
  8614. break;
  8615. case 'ANGLE':
  8616. this.angle = data * TO_RADIANS;
  8617. break;
  8618. default:
  8619. this.obj.x = data[ 0 ];
  8620. this.obj.y = data[ 1 ];
  8621. this.obj.z = data[ 2 ];
  8622. this.angle = data[ 3 ] * TO_RADIANS;
  8623. break;
  8624. }
  8625. break;
  8626. }
  8627. };
  8628. function InstanceController() {
  8629. this.url = "";
  8630. this.skeleton = [];
  8631. this.instance_material = [];
  8632. };
  8633. InstanceController.prototype.parse = function ( element ) {
  8634. this.url = element.getAttribute('url').replace(/^#/, '');
  8635. this.skeleton = [];
  8636. this.instance_material = [];
  8637. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8638. var child = element.childNodes[i];
  8639. if (child.nodeType != 1) continue;
  8640. switch ( child.nodeName ) {
  8641. case 'skeleton':
  8642. this.skeleton.push( child.textContent.replace(/^#/, '') );
  8643. break;
  8644. case 'bind_material':
  8645. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  8646. if ( instances ) {
  8647. var instance = instances.iterateNext();
  8648. while ( instance ) {
  8649. this.instance_material.push((new InstanceMaterial()).parse(instance));
  8650. instance = instances.iterateNext();
  8651. }
  8652. }
  8653. break;
  8654. case 'extra':
  8655. break;
  8656. default:
  8657. break;
  8658. }
  8659. }
  8660. return this;
  8661. };
  8662. function InstanceMaterial () {
  8663. this.symbol = "";
  8664. this.target = "";
  8665. };
  8666. InstanceMaterial.prototype.parse = function ( element ) {
  8667. this.symbol = element.getAttribute('symbol');
  8668. this.target = element.getAttribute('target').replace(/^#/, '');
  8669. return this;
  8670. };
  8671. function InstanceGeometry() {
  8672. this.url = "";
  8673. this.instance_material = [];
  8674. };
  8675. InstanceGeometry.prototype.parse = function ( element ) {
  8676. this.url = element.getAttribute('url').replace(/^#/, '');
  8677. this.instance_material = [];
  8678. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8679. var child = element.childNodes[i];
  8680. if ( child.nodeType != 1 ) continue;
  8681. if ( child.nodeName == 'bind_material' ) {
  8682. var instances = COLLADA.evaluate( './/dae:instance_material', child, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  8683. if ( instances ) {
  8684. var instance = instances.iterateNext();
  8685. while ( instance ) {
  8686. this.instance_material.push( (new InstanceMaterial()).parse(instance) );
  8687. instance = instances.iterateNext();
  8688. }
  8689. }
  8690. break;
  8691. }
  8692. }
  8693. return this;
  8694. };
  8695. function Geometry() {
  8696. this.id = "";
  8697. this.mesh = null;
  8698. };
  8699. Geometry.prototype.parse = function ( element ) {
  8700. this.id = element.getAttribute('id');
  8701. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8702. var child = element.childNodes[i];
  8703. switch ( child.nodeName ) {
  8704. case 'mesh':
  8705. this.mesh = (new Mesh(this)).parse(child);
  8706. break;
  8707. case 'extra':
  8708. // console.log( child );
  8709. break;
  8710. default:
  8711. break;
  8712. }
  8713. }
  8714. return this;
  8715. };
  8716. function Mesh( geometry ) {
  8717. this.geometry = geometry.id;
  8718. this.primitives = [];
  8719. this.vertices = null;
  8720. this.geometry3js = null;
  8721. };
  8722. Mesh.prototype.parse = function( element ) {
  8723. this.primitives = [];
  8724. var i, j;
  8725. for ( i = 0; i < element.childNodes.length; i ++ ) {
  8726. var child = element.childNodes[ i ];
  8727. switch ( child.nodeName ) {
  8728. case 'source':
  8729. _source( child );
  8730. break;
  8731. case 'vertices':
  8732. this.vertices = ( new Vertices() ).parse( child );
  8733. break;
  8734. case 'triangles':
  8735. this.primitives.push( ( new Triangles().parse( child ) ) );
  8736. break;
  8737. case 'polygons':
  8738. this.primitives.push( ( new Polygons().parse( child ) ) );
  8739. break;
  8740. case 'polylist':
  8741. this.primitives.push( ( new Polylist().parse( child ) ) );
  8742. break;
  8743. default:
  8744. break;
  8745. }
  8746. }
  8747. this.geometry3js = new THREE.Geometry();
  8748. var vertexData = sources[ this.vertices.input['POSITION'].source ].data;
  8749. for ( i = 0; i < vertexData.length; i += 3 ) {
  8750. var v = new THREE.Vertex().copy( getConvertedVec3( vertexData, i ) );
  8751. this.geometry3js.vertices.push( v );
  8752. }
  8753. for ( i = 0; i < this.primitives.length; i ++ ) {
  8754. var primitive = this.primitives[ i ];
  8755. primitive.setVertices( this.vertices );
  8756. this.handlePrimitive( primitive, this.geometry3js );
  8757. }
  8758. this.geometry3js.computeCentroids();
  8759. this.geometry3js.computeFaceNormals();
  8760. if ( this.geometry3js.calcNormals ) {
  8761. this.geometry3js.computeVertexNormals();
  8762. delete this.geometry3js.calcNormals;
  8763. }
  8764. this.geometry3js.computeBoundingBox();
  8765. return this;
  8766. };
  8767. Mesh.prototype.handlePrimitive = function( primitive, geom ) {
  8768. var j, k, pList = primitive.p, inputs = primitive.inputs;
  8769. var input, index, idx32;
  8770. var source, numParams;
  8771. var vcIndex = 0, vcount = 3, maxOffset = 0;
  8772. var texture_sets = [];
  8773. for ( j = 0; j < inputs.length; j ++ ) {
  8774. input = inputs[ j ];
  8775. var offset = input.offset + 1;
  8776. maxOffset = (maxOffset < offset)? offset : maxOffset;
  8777. switch ( input.semantic ) {
  8778. case 'TEXCOORD':
  8779. texture_sets.push( input.set );
  8780. break;
  8781. }
  8782. }
  8783. for ( var pCount = 0; pCount < pList.length; ++pCount ) {
  8784. var p = pList[pCount], i = 0;
  8785. while ( i < p.length ) {
  8786. var vs = [];
  8787. var ns = [];
  8788. var ts = {};
  8789. var cs = [];
  8790. if ( primitive.vcount ) {
  8791. vcount = primitive.vcount.length ? primitive.vcount[ vcIndex ++ ] : primitive.vcount;
  8792. } else {
  8793. vcount = p.length / maxOffset;
  8794. }
  8795. for ( j = 0; j < vcount; j ++ ) {
  8796. for ( k = 0; k < inputs.length; k ++ ) {
  8797. input = inputs[ k ];
  8798. source = sources[ input.source ];
  8799. index = p[ i + ( j * maxOffset ) + input.offset ];
  8800. numParams = source.accessor.params.length;
  8801. idx32 = index * numParams;
  8802. switch ( input.semantic ) {
  8803. case 'VERTEX':
  8804. vs.push( index );
  8805. break;
  8806. case 'NORMAL':
  8807. ns.push( getConvertedVec3( source.data, idx32 ) );
  8808. break;
  8809. case 'TEXCOORD':
  8810. if ( ts[ input.set ] === undefined ) ts[ input.set ] = [];
  8811. // invert the V
  8812. ts[ input.set ].push( new THREE.UV( source.data[ idx32 ], 1.0 - source.data[ idx32 + 1 ] ) );
  8813. break;
  8814. case 'COLOR':
  8815. cs.push( new THREE.Color().setRGB( source.data[ idx32 ], source.data[ idx32 + 1 ], source.data[ idx32 + 2 ] ) );
  8816. break;
  8817. default:
  8818. break;
  8819. }
  8820. }
  8821. }
  8822. var face = null, faces = [], uv, uvArr;
  8823. if ( ns.length == 0 ) {
  8824. // check the vertices source
  8825. input = this.vertices.input.NORMAL;
  8826. if ( input ) {
  8827. source = sources[ input.source ];
  8828. numParams = source.accessor.params.length;
  8829. for ( var ndx = 0, len = vs.length; ndx < len; ndx++ ) {
  8830. ns.push( getConvertedVec3( source.data, vs[ ndx ] * numParams ) );
  8831. }
  8832. }
  8833. else {
  8834. geom.calcNormals = true;
  8835. }
  8836. }
  8837. if ( vcount === 3 ) {
  8838. faces.push( new THREE.Face3( vs[0], vs[1], vs[2], ns, cs.length ? cs : new THREE.Color() ) );
  8839. } else if ( vcount === 4 ) {
  8840. faces.push( new THREE.Face4( vs[0], vs[1], vs[2], vs[3], ns, cs.length ? cs : new THREE.Color() ) );
  8841. } else if ( vcount > 4 && options.subdivideFaces ) {
  8842. var clr = cs.length ? cs : new THREE.Color(),
  8843. vec1, vec2, vec3, v1, v2, norm;
  8844. // subdivide into multiple Face3s
  8845. for ( k = 1; k < vcount-1; ) {
  8846. // FIXME: normals don't seem to be quite right
  8847. faces.push( new THREE.Face3( vs[0], vs[k], vs[k+1], [ ns[0], ns[k++], ns[k] ], clr ) );
  8848. }
  8849. }
  8850. if ( faces.length ) {
  8851. for (var ndx = 0, len = faces.length; ndx < len; ndx++) {
  8852. face = faces[ndx];
  8853. face.daeMaterial = primitive.material;
  8854. geom.faces.push( face );
  8855. for ( k = 0; k < texture_sets.length; k++ ) {
  8856. uv = ts[ texture_sets[k] ];
  8857. if ( vcount > 4 ) {
  8858. // Grab the right UVs for the vertices in this face
  8859. uvArr = [ uv[0], uv[ndx+1], uv[ndx+2] ];
  8860. } else if ( vcount === 4 ) {
  8861. uvArr = [ uv[0], uv[1], uv[2], uv[3] ];
  8862. } else {
  8863. uvArr = [ uv[0], uv[1], uv[2] ];
  8864. }
  8865. if ( !geom.faceVertexUvs[k] ) {
  8866. geom.faceVertexUvs[k] = [];
  8867. }
  8868. geom.faceVertexUvs[k].push( uvArr );
  8869. }
  8870. }
  8871. } else {
  8872. console.log( 'dropped face with vcount ' + vcount + ' for geometry with id: ' + geom.id );
  8873. }
  8874. i += maxOffset * vcount;
  8875. }
  8876. }
  8877. };
  8878. function Polygons () {
  8879. this.material = "";
  8880. this.count = 0;
  8881. this.inputs = [];
  8882. this.vcount = null;
  8883. this.p = [];
  8884. this.geometry = new THREE.Geometry();
  8885. };
  8886. Polygons.prototype.setVertices = function ( vertices ) {
  8887. for ( var i = 0; i < this.inputs.length; i ++ ) {
  8888. if ( this.inputs[ i ].source == vertices.id ) {
  8889. this.inputs[ i ].source = vertices.input[ 'POSITION' ].source;
  8890. }
  8891. }
  8892. };
  8893. Polygons.prototype.parse = function ( element ) {
  8894. this.material = element.getAttribute( 'material' );
  8895. this.count = _attr_as_int( element, 'count', 0 );
  8896. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8897. var child = element.childNodes[ i ];
  8898. switch ( child.nodeName ) {
  8899. case 'input':
  8900. this.inputs.push( ( new Input() ).parse( element.childNodes[ i ] ) );
  8901. break;
  8902. case 'vcount':
  8903. this.vcount = _ints( child.textContent );
  8904. break;
  8905. case 'p':
  8906. this.p.push( _ints( child.textContent ) );
  8907. break;
  8908. case 'ph':
  8909. console.warn( 'polygon holes not yet supported!' );
  8910. break;
  8911. default:
  8912. break;
  8913. }
  8914. }
  8915. return this;
  8916. };
  8917. function Polylist () {
  8918. Polygons.call( this );
  8919. this.vcount = [];
  8920. };
  8921. Polylist.prototype = new Polygons();
  8922. Polylist.prototype.constructor = Polylist;
  8923. function Triangles () {
  8924. Polygons.call( this );
  8925. this.vcount = 3;
  8926. };
  8927. Triangles.prototype = new Polygons();
  8928. Triangles.prototype.constructor = Triangles;
  8929. function Accessor() {
  8930. this.source = "";
  8931. this.count = 0;
  8932. this.stride = 0;
  8933. this.params = [];
  8934. };
  8935. Accessor.prototype.parse = function ( element ) {
  8936. this.params = [];
  8937. this.source = element.getAttribute( 'source' );
  8938. this.count = _attr_as_int( element, 'count', 0 );
  8939. this.stride = _attr_as_int( element, 'stride', 0 );
  8940. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8941. var child = element.childNodes[ i ];
  8942. if ( child.nodeName == 'param' ) {
  8943. var param = {};
  8944. param[ 'name' ] = child.getAttribute( 'name' );
  8945. param[ 'type' ] = child.getAttribute( 'type' );
  8946. this.params.push( param );
  8947. }
  8948. }
  8949. return this;
  8950. };
  8951. function Vertices() {
  8952. this.input = {};
  8953. };
  8954. Vertices.prototype.parse = function ( element ) {
  8955. this.id = element.getAttribute('id');
  8956. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8957. if ( element.childNodes[i].nodeName == 'input' ) {
  8958. var input = ( new Input() ).parse( element.childNodes[ i ] );
  8959. this.input[ input.semantic ] = input;
  8960. }
  8961. }
  8962. return this;
  8963. };
  8964. function Input () {
  8965. this.semantic = "";
  8966. this.offset = 0;
  8967. this.source = "";
  8968. this.set = 0;
  8969. };
  8970. Input.prototype.parse = function ( element ) {
  8971. this.semantic = element.getAttribute('semantic');
  8972. this.source = element.getAttribute('source').replace(/^#/, '');
  8973. this.set = _attr_as_int(element, 'set', -1);
  8974. this.offset = _attr_as_int(element, 'offset', 0);
  8975. if ( this.semantic == 'TEXCOORD' && this.set < 0 ) {
  8976. this.set = 0;
  8977. }
  8978. return this;
  8979. };
  8980. function Source ( id ) {
  8981. this.id = id;
  8982. this.type = null;
  8983. };
  8984. Source.prototype.parse = function ( element ) {
  8985. this.id = element.getAttribute( 'id' );
  8986. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  8987. var child = element.childNodes[i];
  8988. switch ( child.nodeName ) {
  8989. case 'bool_array':
  8990. this.data = _bools( child.textContent );
  8991. this.type = child.nodeName;
  8992. break;
  8993. case 'float_array':
  8994. this.data = _floats( child.textContent );
  8995. this.type = child.nodeName;
  8996. break;
  8997. case 'int_array':
  8998. this.data = _ints( child.textContent );
  8999. this.type = child.nodeName;
  9000. break;
  9001. case 'IDREF_array':
  9002. case 'Name_array':
  9003. this.data = _strings( child.textContent );
  9004. this.type = child.nodeName;
  9005. break;
  9006. case 'technique_common':
  9007. for ( var j = 0; j < child.childNodes.length; j ++ ) {
  9008. if ( child.childNodes[ j ].nodeName == 'accessor' ) {
  9009. this.accessor = ( new Accessor() ).parse( child.childNodes[ j ] );
  9010. break;
  9011. }
  9012. }
  9013. break;
  9014. default:
  9015. // console.log(child.nodeName);
  9016. break;
  9017. }
  9018. }
  9019. return this;
  9020. };
  9021. Source.prototype.read = function () {
  9022. var result = [];
  9023. //for (var i = 0; i < this.accessor.params.length; i++) {
  9024. var param = this.accessor.params[ 0 ];
  9025. //console.log(param.name + " " + param.type);
  9026. switch ( param.type ) {
  9027. case 'IDREF':
  9028. case 'Name': case 'name':
  9029. case 'float':
  9030. return this.data;
  9031. case 'float4x4':
  9032. for ( var j = 0; j < this.data.length; j += 16 ) {
  9033. var s = this.data.slice( j, j + 16 );
  9034. var m = getConvertedMat4( s );
  9035. result.push( m );
  9036. }
  9037. break;
  9038. default:
  9039. console.log( 'ColladaLoader: Source: Read dont know how to read ' + param.type + '.' );
  9040. break;
  9041. }
  9042. //}
  9043. return result;
  9044. };
  9045. function Material () {
  9046. this.id = "";
  9047. this.name = "";
  9048. this.instance_effect = null;
  9049. };
  9050. Material.prototype.parse = function ( element ) {
  9051. this.id = element.getAttribute( 'id' );
  9052. this.name = element.getAttribute( 'name' );
  9053. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9054. if ( element.childNodes[ i ].nodeName == 'instance_effect' ) {
  9055. this.instance_effect = ( new InstanceEffect() ).parse( element.childNodes[ i ] );
  9056. break;
  9057. }
  9058. }
  9059. return this;
  9060. };
  9061. function ColorOrTexture () {
  9062. this.color = new THREE.Color( 0 );
  9063. this.color.setRGB( Math.random(), Math.random(), Math.random() );
  9064. this.color.a = 1.0;
  9065. this.texture = null;
  9066. this.texcoord = null;
  9067. this.texOpts = null;
  9068. };
  9069. ColorOrTexture.prototype.isColor = function () {
  9070. return ( this.texture == null );
  9071. };
  9072. ColorOrTexture.prototype.isTexture = function () {
  9073. return ( this.texture != null );
  9074. };
  9075. ColorOrTexture.prototype.parse = function ( element ) {
  9076. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9077. var child = element.childNodes[ i ];
  9078. if ( child.nodeType != 1 ) continue;
  9079. switch ( child.nodeName ) {
  9080. case 'color':
  9081. var rgba = _floats( child.textContent );
  9082. this.color = new THREE.Color(0);
  9083. this.color.setRGB( rgba[0], rgba[1], rgba[2] );
  9084. this.color.a = rgba[3];
  9085. break;
  9086. case 'texture':
  9087. this.texture = child.getAttribute('texture');
  9088. this.texcoord = child.getAttribute('texcoord');
  9089. // Defaults from:
  9090. // https://collada.org/mediawiki/index.php/Maya_texture_placement_MAYA_extension
  9091. this.texOpts = {
  9092. offsetU: 0,
  9093. offsetV: 0,
  9094. repeatU: 1,
  9095. repeatV: 1,
  9096. wrapU: 1,
  9097. wrapV: 1,
  9098. };
  9099. this.parseTexture( child );
  9100. break;
  9101. default:
  9102. break;
  9103. }
  9104. }
  9105. return this;
  9106. };
  9107. ColorOrTexture.prototype.parseTexture = function ( element ) {
  9108. if ( ! element.childNodes ) return this;
  9109. // This should be supported by Maya, 3dsMax, and MotionBuilder
  9110. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'extra' ) {
  9111. element = element.childNodes[1];
  9112. if ( element.childNodes[1] && element.childNodes[1].nodeName === 'technique' ) {
  9113. element = element.childNodes[1];
  9114. }
  9115. }
  9116. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9117. var child = element.childNodes[ i ];
  9118. switch ( child.nodeName ) {
  9119. case 'offsetU':
  9120. case 'offsetV':
  9121. case 'repeatU':
  9122. case 'repeatV':
  9123. this.texOpts[ child.nodeName ] = parseFloat( child.textContent );
  9124. break;
  9125. case 'wrapU':
  9126. case 'wrapV':
  9127. this.texOpts[ child.nodeName ] = parseInt( child.textContent );
  9128. break;
  9129. default:
  9130. this.texOpts[ child.nodeName ] = child.textContent;
  9131. break;
  9132. }
  9133. }
  9134. return this;
  9135. };
  9136. function Shader ( type, effect ) {
  9137. this.type = type;
  9138. this.effect = effect;
  9139. this.material = null;
  9140. };
  9141. Shader.prototype.parse = function ( element ) {
  9142. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9143. var child = element.childNodes[ i ];
  9144. if ( child.nodeType != 1 ) continue;
  9145. switch ( child.nodeName ) {
  9146. case 'ambient':
  9147. case 'emission':
  9148. case 'diffuse':
  9149. case 'specular':
  9150. case 'transparent':
  9151. this[ child.nodeName ] = ( new ColorOrTexture() ).parse( child );
  9152. break;
  9153. case 'shininess':
  9154. case 'reflectivity':
  9155. case 'transparency':
  9156. var f = evaluateXPath( child, './/dae:float' );
  9157. if ( f.length > 0 )
  9158. this[ child.nodeName ] = parseFloat( f[ 0 ].textContent );
  9159. break;
  9160. default:
  9161. break;
  9162. }
  9163. }
  9164. this.create();
  9165. return this;
  9166. };
  9167. Shader.prototype.create = function() {
  9168. var props = {};
  9169. var transparent = ( this['transparency'] !== undefined && this['transparency'] < 1.0 );
  9170. for ( var prop in this ) {
  9171. switch ( prop ) {
  9172. case 'ambient':
  9173. case 'emission':
  9174. case 'diffuse':
  9175. case 'specular':
  9176. var cot = this[prop];
  9177. if ( cot instanceof ColorOrTexture ) {
  9178. if ( cot.isTexture() ) {
  9179. if ( this.effect.sampler && this.effect.surface ) {
  9180. if ( this.effect.sampler.source == this.effect.surface.sid ) {
  9181. var image = images[this.effect.surface.init_from];
  9182. if ( image ) {
  9183. var texture = THREE.ImageUtils.loadTexture(baseUrl + image.init_from);
  9184. texture.wrapS = cot.texOpts.wrapU ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  9185. texture.wrapT = cot.texOpts.wrapV ? THREE.RepeatWrapping : THREE.ClampToEdgeWrapping;
  9186. texture.offset.x = cot.texOpts.offsetU;
  9187. texture.offset.y = cot.texOpts.offsetV;
  9188. texture.repeat.x = cot.texOpts.repeatU;
  9189. texture.repeat.y = cot.texOpts.repeatV;
  9190. props['map'] = texture;
  9191. // Texture with baked lighting?
  9192. if ( prop == 'emission' ) props[ 'emissive' ] = 0xffffff;
  9193. }
  9194. }
  9195. }
  9196. } else if ( prop == 'diffuse' || !transparent ) {
  9197. if ( prop == 'emission' ) {
  9198. props[ 'emissive' ] = cot.color.getHex();
  9199. } else {
  9200. props[ prop ] = cot.color.getHex();
  9201. }
  9202. }
  9203. }
  9204. break;
  9205. case 'shininess':
  9206. case 'reflectivity':
  9207. props[ prop ] = this[ prop ];
  9208. break;
  9209. case 'transparency':
  9210. if ( transparent ) {
  9211. props[ 'transparent' ] = true;
  9212. props[ 'opacity' ] = this[ prop ];
  9213. transparent = true;
  9214. }
  9215. break;
  9216. default:
  9217. break;
  9218. }
  9219. }
  9220. props[ 'shading' ] = preferredShading;
  9221. switch ( this.type ) {
  9222. case 'constant':
  9223. props.color = props.emission;
  9224. this.material = new THREE.MeshBasicMaterial( props );
  9225. break;
  9226. case 'phong':
  9227. case 'blinn':
  9228. props.color = props.diffuse;
  9229. this.material = new THREE.MeshPhongMaterial( props );
  9230. break;
  9231. case 'lambert':
  9232. default:
  9233. props.color = props.diffuse;
  9234. this.material = new THREE.MeshLambertMaterial( props );
  9235. break;
  9236. }
  9237. return this.material;
  9238. };
  9239. function Surface ( effect ) {
  9240. this.effect = effect;
  9241. this.init_from = null;
  9242. this.format = null;
  9243. };
  9244. Surface.prototype.parse = function ( element ) {
  9245. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9246. var child = element.childNodes[ i ];
  9247. if ( child.nodeType != 1 ) continue;
  9248. switch ( child.nodeName ) {
  9249. case 'init_from':
  9250. this.init_from = child.textContent;
  9251. break;
  9252. case 'format':
  9253. this.format = child.textContent;
  9254. break;
  9255. default:
  9256. console.log( "unhandled Surface prop: " + child.nodeName );
  9257. break;
  9258. }
  9259. }
  9260. return this;
  9261. };
  9262. function Sampler2D ( effect ) {
  9263. this.effect = effect;
  9264. this.source = null;
  9265. this.wrap_s = null;
  9266. this.wrap_t = null;
  9267. this.minfilter = null;
  9268. this.magfilter = null;
  9269. this.mipfilter = null;
  9270. };
  9271. Sampler2D.prototype.parse = function ( element ) {
  9272. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9273. var child = element.childNodes[ i ];
  9274. if ( child.nodeType != 1 ) continue;
  9275. switch ( child.nodeName ) {
  9276. case 'source':
  9277. this.source = child.textContent;
  9278. break;
  9279. case 'minfilter':
  9280. this.minfilter = child.textContent;
  9281. break;
  9282. case 'magfilter':
  9283. this.magfilter = child.textContent;
  9284. break;
  9285. case 'mipfilter':
  9286. this.mipfilter = child.textContent;
  9287. break;
  9288. case 'wrap_s':
  9289. this.wrap_s = child.textContent;
  9290. break;
  9291. case 'wrap_t':
  9292. this.wrap_t = child.textContent;
  9293. break;
  9294. default:
  9295. console.log( "unhandled Sampler2D prop: " + child.nodeName );
  9296. break;
  9297. }
  9298. }
  9299. return this;
  9300. };
  9301. function Effect () {
  9302. this.id = "";
  9303. this.name = "";
  9304. this.shader = null;
  9305. this.surface = null;
  9306. this.sampler = null;
  9307. };
  9308. Effect.prototype.create = function () {
  9309. if ( this.shader == null ) {
  9310. return null;
  9311. }
  9312. };
  9313. Effect.prototype.parse = function ( element ) {
  9314. this.id = element.getAttribute( 'id' );
  9315. this.name = element.getAttribute( 'name' );
  9316. this.shader = null;
  9317. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9318. var child = element.childNodes[ i ];
  9319. if ( child.nodeType != 1 ) continue;
  9320. switch ( child.nodeName ) {
  9321. case 'profile_COMMON':
  9322. this.parseTechnique( this.parseProfileCOMMON( child ) );
  9323. break;
  9324. default:
  9325. break;
  9326. }
  9327. }
  9328. return this;
  9329. };
  9330. Effect.prototype.parseNewparam = function ( element ) {
  9331. var sid = element.getAttribute( 'sid' );
  9332. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9333. var child = element.childNodes[ i ];
  9334. if ( child.nodeType != 1 ) continue;
  9335. switch ( child.nodeName ) {
  9336. case 'surface':
  9337. this.surface = ( new Surface( this ) ).parse( child );
  9338. this.surface.sid = sid;
  9339. break;
  9340. case 'sampler2D':
  9341. this.sampler = ( new Sampler2D( this ) ).parse( child );
  9342. this.sampler.sid = sid;
  9343. break;
  9344. case 'extra':
  9345. break;
  9346. default:
  9347. console.log( child.nodeName );
  9348. break;
  9349. }
  9350. }
  9351. };
  9352. Effect.prototype.parseProfileCOMMON = function ( element ) {
  9353. var technique;
  9354. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9355. var child = element.childNodes[ i ];
  9356. if ( child.nodeType != 1 ) continue;
  9357. switch ( child.nodeName ) {
  9358. case 'profile_COMMON':
  9359. this.parseProfileCOMMON( child );
  9360. break;
  9361. case 'technique':
  9362. technique = child;
  9363. break;
  9364. case 'newparam':
  9365. this.parseNewparam( child );
  9366. break;
  9367. case 'image':
  9368. var _image = ( new _Image() ).parse( child );
  9369. images[ _image.id ] = _image;
  9370. break;
  9371. case 'extra':
  9372. break;
  9373. default:
  9374. console.log( child.nodeName );
  9375. break;
  9376. }
  9377. }
  9378. return technique;
  9379. };
  9380. Effect.prototype.parseTechnique= function ( element ) {
  9381. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9382. var child = element.childNodes[i];
  9383. if ( child.nodeType != 1 ) continue;
  9384. switch ( child.nodeName ) {
  9385. case 'constant':
  9386. case 'lambert':
  9387. case 'blinn':
  9388. case 'phong':
  9389. this.shader = ( new Shader( child.nodeName, this ) ).parse( child );
  9390. break;
  9391. default:
  9392. break;
  9393. }
  9394. }
  9395. };
  9396. function InstanceEffect () {
  9397. this.url = "";
  9398. };
  9399. InstanceEffect.prototype.parse = function ( element ) {
  9400. this.url = element.getAttribute( 'url' ).replace( /^#/, '' );
  9401. return this;
  9402. };
  9403. function Animation() {
  9404. this.id = "";
  9405. this.name = "";
  9406. this.source = {};
  9407. this.sampler = [];
  9408. this.channel = [];
  9409. };
  9410. Animation.prototype.parse = function ( element ) {
  9411. this.id = element.getAttribute( 'id' );
  9412. this.name = element.getAttribute( 'name' );
  9413. this.source = {};
  9414. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9415. var child = element.childNodes[ i ];
  9416. if ( child.nodeType != 1 ) continue;
  9417. switch ( child.nodeName ) {
  9418. case 'animation':
  9419. var anim = ( new Animation() ).parse( child );
  9420. for ( var src in anim.source ) {
  9421. this.source[ src ] = anim.source[ src ];
  9422. }
  9423. for ( var j = 0; j < anim.channel.length; j ++ ) {
  9424. this.channel.push( anim.channel[ j ] );
  9425. this.sampler.push( anim.sampler[ j ] );
  9426. }
  9427. break;
  9428. case 'source':
  9429. var src = ( new Source() ).parse( child );
  9430. this.source[ src.id ] = src;
  9431. break;
  9432. case 'sampler':
  9433. this.sampler.push( ( new Sampler( this ) ).parse( child ) );
  9434. break;
  9435. case 'channel':
  9436. this.channel.push( ( new Channel( this ) ).parse( child ) );
  9437. break;
  9438. default:
  9439. break;
  9440. }
  9441. }
  9442. return this;
  9443. };
  9444. function Channel( animation ) {
  9445. this.animation = animation;
  9446. this.source = "";
  9447. this.target = "";
  9448. this.fullSid = null;
  9449. this.sid = null;
  9450. this.dotSyntax = null;
  9451. this.arrSyntax = null;
  9452. this.arrIndices = null;
  9453. this.member = null;
  9454. };
  9455. Channel.prototype.parse = function ( element ) {
  9456. this.source = element.getAttribute( 'source' ).replace( /^#/, '' );
  9457. this.target = element.getAttribute( 'target' );
  9458. var parts = this.target.split( '/' );
  9459. var id = parts.shift();
  9460. var sid = parts.shift();
  9461. var dotSyntax = ( sid.indexOf(".") >= 0 );
  9462. var arrSyntax = ( sid.indexOf("(") >= 0 );
  9463. if ( dotSyntax ) {
  9464. parts = sid.split(".");
  9465. this.sid = parts.shift();
  9466. this.member = parts.shift();
  9467. } else if ( arrSyntax ) {
  9468. var arrIndices = sid.split("(");
  9469. this.sid = arrIndices.shift();
  9470. for (var j = 0; j < arrIndices.length; j ++ ) {
  9471. arrIndices[j] = parseInt( arrIndices[j].replace(/\)/, '') );
  9472. }
  9473. this.arrIndices = arrIndices;
  9474. } else {
  9475. this.sid = sid;
  9476. }
  9477. this.fullSid = sid;
  9478. this.dotSyntax = dotSyntax;
  9479. this.arrSyntax = arrSyntax;
  9480. return this;
  9481. };
  9482. function Sampler ( animation ) {
  9483. this.id = "";
  9484. this.animation = animation;
  9485. this.inputs = [];
  9486. this.input = null;
  9487. this.output = null;
  9488. this.strideOut = null;
  9489. this.interpolation = null;
  9490. this.startTime = null;
  9491. this.endTime = null;
  9492. this.duration = 0;
  9493. };
  9494. Sampler.prototype.parse = function ( element ) {
  9495. this.id = element.getAttribute( 'id' );
  9496. this.inputs = [];
  9497. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9498. var child = element.childNodes[ i ];
  9499. if ( child.nodeType != 1 ) continue;
  9500. switch ( child.nodeName ) {
  9501. case 'input':
  9502. this.inputs.push( (new Input()).parse( child ) );
  9503. break;
  9504. default:
  9505. break;
  9506. }
  9507. }
  9508. return this;
  9509. };
  9510. Sampler.prototype.create = function () {
  9511. for ( var i = 0; i < this.inputs.length; i ++ ) {
  9512. var input = this.inputs[ i ];
  9513. var source = this.animation.source[ input.source ];
  9514. switch ( input.semantic ) {
  9515. case 'INPUT':
  9516. this.input = source.read();
  9517. break;
  9518. case 'OUTPUT':
  9519. this.output = source.read();
  9520. this.strideOut = source.accessor.stride;
  9521. break;
  9522. case 'INTERPOLATION':
  9523. this.interpolation = source.read();
  9524. break;
  9525. case 'IN_TANGENT':
  9526. break;
  9527. case 'OUT_TANGENT':
  9528. break;
  9529. default:
  9530. console.log(input.semantic);
  9531. break;
  9532. }
  9533. }
  9534. this.startTime = 0;
  9535. this.endTime = 0;
  9536. this.duration = 0;
  9537. if ( this.input.length ) {
  9538. this.startTime = 100000000;
  9539. this.endTime = -100000000;
  9540. for ( var i = 0; i < this.input.length; i ++ ) {
  9541. this.startTime = Math.min( this.startTime, this.input[ i ] );
  9542. this.endTime = Math.max( this.endTime, this.input[ i ] );
  9543. }
  9544. this.duration = this.endTime - this.startTime;
  9545. }
  9546. };
  9547. Sampler.prototype.getData = function ( type, ndx ) {
  9548. var data;
  9549. if ( type === 'matrix' && this.strideOut === 16 ) {
  9550. data = this.output[ ndx ];
  9551. } else if ( this.strideOut > 1 ) {
  9552. data = [];
  9553. ndx *= this.strideOut;
  9554. for ( var i = 0; i < this.strideOut; ++i ) {
  9555. data[ i ] = this.output[ ndx + i ];
  9556. }
  9557. if ( this.strideOut === 3 ) {
  9558. switch ( type ) {
  9559. case 'rotate':
  9560. case 'translate':
  9561. fixCoords( data, -1 );
  9562. break;
  9563. case 'scale':
  9564. fixCoords( data, 1 );
  9565. break;
  9566. }
  9567. } else if ( this.strideOut === 4 && type === 'matrix' ) {
  9568. fixCoords( data, -1 );
  9569. }
  9570. } else {
  9571. data = this.output[ ndx ];
  9572. }
  9573. return data;
  9574. };
  9575. function Key ( time ) {
  9576. this.targets = [];
  9577. this.time = time;
  9578. };
  9579. Key.prototype.addTarget = function ( fullSid, transform, member, data ) {
  9580. this.targets.push( {
  9581. sid: fullSid,
  9582. member: member,
  9583. transform: transform,
  9584. data: data
  9585. } );
  9586. };
  9587. Key.prototype.apply = function ( opt_sid ) {
  9588. for ( var i = 0; i < this.targets.length; ++i ) {
  9589. var target = this.targets[ i ];
  9590. if ( !opt_sid || target.sid === opt_sid ) {
  9591. target.transform.update( target.data, target.member );
  9592. }
  9593. }
  9594. };
  9595. Key.prototype.getTarget = function ( fullSid ) {
  9596. for ( var i = 0; i < this.targets.length; ++i ) {
  9597. if ( this.targets[ i ].sid === fullSid ) {
  9598. return this.targets[ i ];
  9599. }
  9600. }
  9601. return null;
  9602. };
  9603. Key.prototype.hasTarget = function ( fullSid ) {
  9604. for ( var i = 0; i < this.targets.length; ++i ) {
  9605. if ( this.targets[ i ].sid === fullSid ) {
  9606. return true;
  9607. }
  9608. }
  9609. return false;
  9610. };
  9611. // TODO: Currently only doing linear interpolation. Should support full COLLADA spec.
  9612. Key.prototype.interpolate = function ( nextKey, time ) {
  9613. for ( var i = 0; i < this.targets.length; ++i ) {
  9614. var target = this.targets[ i ],
  9615. nextTarget = nextKey.getTarget( target.sid ),
  9616. data;
  9617. if ( target.transform.type !== 'matrix' && nextTarget ) {
  9618. var scale = ( time - this.time ) / ( nextKey.time - this.time ),
  9619. nextData = nextTarget.data,
  9620. prevData = target.data;
  9621. // check scale error
  9622. if ( scale < 0 || scale > 1 ) {
  9623. console.log( "Key.interpolate: Warning! Scale out of bounds:" + scale );
  9624. scale = scale < 0 ? 0 : 1;
  9625. }
  9626. if ( prevData.length ) {
  9627. data = [];
  9628. for ( var j = 0; j < prevData.length; ++j ) {
  9629. data[ j ] = prevData[ j ] + ( nextData[ j ] - prevData[ j ] ) * scale;
  9630. }
  9631. } else {
  9632. data = prevData + ( nextData - prevData ) * scale;
  9633. }
  9634. } else {
  9635. data = target.data;
  9636. }
  9637. target.transform.update( data, target.member );
  9638. }
  9639. };
  9640. function Camera() {
  9641. this.id = "";
  9642. this.name = "";
  9643. this.technique = "";
  9644. };
  9645. Camera.prototype.parse = function ( element ) {
  9646. this.id = element.getAttribute( 'id' );
  9647. this.name = element.getAttribute( 'name' );
  9648. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9649. var child = element.childNodes[ i ];
  9650. if ( child.nodeType != 1 ) continue;
  9651. switch ( child.nodeName ) {
  9652. case 'optics':
  9653. this.parseOptics( child );
  9654. break;
  9655. default:
  9656. break;
  9657. }
  9658. }
  9659. return this;
  9660. };
  9661. Camera.prototype.parseOptics = function ( element ) {
  9662. for ( var i = 0; i < element.childNodes.length; i ++ ) {
  9663. if ( element.childNodes[ i ].nodeName == 'technique_common' ) {
  9664. var technique = element.childNodes[ i ];
  9665. for ( var j = 0; j < technique.childNodes.length; j ++ ) {
  9666. this.technique = technique.childNodes[ j ].nodeName;
  9667. if ( this.technique == 'perspective' ) {
  9668. var perspective = technique.childNodes[ j ];
  9669. for ( var k = 0; k < perspective.childNodes.length; k ++ ) {
  9670. var param = perspective.childNodes[ k ];
  9671. switch ( param.nodeName ) {
  9672. case 'yfov':
  9673. this.yfov = param.textContent;
  9674. break;
  9675. case 'xfov':
  9676. this.xfov = param.textContent;
  9677. break;
  9678. case 'znear':
  9679. this.znear = param.textContent;
  9680. break;
  9681. case 'zfar':
  9682. this.zfar = param.textContent;
  9683. break;
  9684. case 'aspect_ratio':
  9685. this.aspect_ratio = param.textContent;
  9686. break;
  9687. }
  9688. }
  9689. } else if ( this.technique == 'orthographic' ) {
  9690. var orthographic = technique.childNodes[ j ];
  9691. for ( var k = 0; k < orthographic.childNodes.length; k ++ ) {
  9692. var param = orthographic.childNodes[ k ];
  9693. switch ( param.nodeName ) {
  9694. case 'xmag':
  9695. this.xmag = param.textContent;
  9696. break;
  9697. case 'ymag':
  9698. this.ymag = param.textContent;
  9699. break;
  9700. case 'znear':
  9701. this.znear = param.textContent;
  9702. break;
  9703. case 'zfar':
  9704. this.zfar = param.textContent;
  9705. break;
  9706. case 'aspect_ratio':
  9707. this.aspect_ratio = param.textContent;
  9708. break;
  9709. }
  9710. }
  9711. }
  9712. }
  9713. }
  9714. }
  9715. return this;
  9716. };
  9717. function InstanceCamera() {
  9718. this.url = "";
  9719. };
  9720. InstanceCamera.prototype.parse = function ( element ) {
  9721. this.url = element.getAttribute('url').replace(/^#/, '');
  9722. return this;
  9723. };
  9724. function _source( element ) {
  9725. var id = element.getAttribute( 'id' );
  9726. if ( sources[ id ] != undefined ) {
  9727. return sources[ id ];
  9728. }
  9729. sources[ id ] = ( new Source(id )).parse( element );
  9730. return sources[ id ];
  9731. };
  9732. function _nsResolver( nsPrefix ) {
  9733. if ( nsPrefix == "dae" ) {
  9734. return "http://www.collada.org/2005/11/COLLADASchema";
  9735. }
  9736. return null;
  9737. };
  9738. function _bools( str ) {
  9739. var raw = _strings( str );
  9740. var data = [];
  9741. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  9742. data.push( (raw[i] == 'true' || raw[i] == '1') ? true : false );
  9743. }
  9744. return data;
  9745. };
  9746. function _floats( str ) {
  9747. var raw = _strings(str);
  9748. var data = [];
  9749. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  9750. data.push( parseFloat( raw[ i ] ) );
  9751. }
  9752. return data;
  9753. };
  9754. function _ints( str ) {
  9755. var raw = _strings( str );
  9756. var data = [];
  9757. for ( var i = 0, l = raw.length; i < l; i ++ ) {
  9758. data.push( parseInt( raw[ i ], 10 ) );
  9759. }
  9760. return data;
  9761. };
  9762. function _strings( str ) {
  9763. return ( str.length > 0 ) ? _trimString( str ).split( /\s+/ ) : [];
  9764. };
  9765. function _trimString( str ) {
  9766. return str.replace( /^\s+/, "" ).replace( /\s+$/, "" );
  9767. };
  9768. function _attr_as_float( element, name, defaultValue ) {
  9769. if ( element.hasAttribute( name ) ) {
  9770. return parseFloat( element.getAttribute( name ) );
  9771. } else {
  9772. return defaultValue;
  9773. }
  9774. };
  9775. function _attr_as_int( element, name, defaultValue ) {
  9776. if ( element.hasAttribute( name ) ) {
  9777. return parseInt( element.getAttribute( name ), 10) ;
  9778. } else {
  9779. return defaultValue;
  9780. }
  9781. };
  9782. function _attr_as_string( element, name, defaultValue ) {
  9783. if ( element.hasAttribute( name ) ) {
  9784. return element.getAttribute( name );
  9785. } else {
  9786. return defaultValue;
  9787. }
  9788. };
  9789. function _format_float( f, num ) {
  9790. if ( f === undefined ) {
  9791. var s = '0.';
  9792. while ( s.length < num + 2 ) {
  9793. s += '0';
  9794. }
  9795. return s;
  9796. }
  9797. num = num || 2;
  9798. var parts = f.toString().split( '.' );
  9799. parts[ 1 ] = parts.length > 1 ? parts[ 1 ].substr( 0, num ) : "0";
  9800. while( parts[ 1 ].length < num ) {
  9801. parts[ 1 ] += '0';
  9802. }
  9803. return parts.join( '.' );
  9804. };
  9805. function evaluateXPath( node, query ) {
  9806. var instances = COLLADA.evaluate( query, node, _nsResolver, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null );
  9807. var inst = instances.iterateNext();
  9808. var result = [];
  9809. while ( inst ) {
  9810. result.push( inst );
  9811. inst = instances.iterateNext();
  9812. }
  9813. return result;
  9814. };
  9815. // Up axis conversion
  9816. function setUpConversion() {
  9817. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  9818. upConversion = null;
  9819. } else {
  9820. switch ( colladaUp ) {
  9821. case 'X':
  9822. upConversion = options.upAxis === 'Y' ? 'XtoY' : 'XtoZ';
  9823. break;
  9824. case 'Y':
  9825. upConversion = options.upAxis === 'X' ? 'YtoX' : 'YtoZ';
  9826. break;
  9827. case 'Z':
  9828. upConversion = options.upAxis === 'X' ? 'ZtoX' : 'ZtoY';
  9829. break;
  9830. }
  9831. }
  9832. };
  9833. function fixCoords( data, sign ) {
  9834. if ( !options.convertUpAxis || colladaUp === options.upAxis ) {
  9835. return;
  9836. }
  9837. switch ( upConversion ) {
  9838. case 'XtoY':
  9839. var tmp = data[ 0 ];
  9840. data[ 0 ] = sign * data[ 1 ];
  9841. data[ 1 ] = tmp;
  9842. break;
  9843. case 'XtoZ':
  9844. var tmp = data[ 2 ];
  9845. data[ 2 ] = data[ 1 ];
  9846. data[ 1 ] = data[ 0 ];
  9847. data[ 0 ] = tmp;
  9848. break;
  9849. case 'YtoX':
  9850. var tmp = data[ 0 ];
  9851. data[ 0 ] = data[ 1 ];
  9852. data[ 1 ] = sign * tmp;
  9853. break;
  9854. case 'YtoZ':
  9855. var tmp = data[ 1 ];
  9856. data[ 1 ] = sign * data[ 2 ];
  9857. data[ 2 ] = tmp;
  9858. break;
  9859. case 'ZtoX':
  9860. var tmp = data[ 0 ];
  9861. data[ 0 ] = data[ 1 ];
  9862. data[ 1 ] = data[ 2 ];
  9863. data[ 2 ] = tmp;
  9864. break;
  9865. case 'ZtoY':
  9866. var tmp = data[ 1 ];
  9867. data[ 1 ] = data[ 2 ];
  9868. data[ 2 ] = sign * tmp;
  9869. break;
  9870. }
  9871. };
  9872. function getConvertedVec3( data, offset ) {
  9873. var arr = [ data[ offset ], data[ offset + 1 ], data[ offset + 2 ] ];
  9874. fixCoords( arr, -1 );
  9875. return new THREE.Vector3( arr[ 0 ], arr[ 1 ], arr[ 2 ] );
  9876. };
  9877. function getConvertedMat4( data ) {
  9878. if ( options.convertUpAxis ) {
  9879. // First fix rotation and scale
  9880. // Columns first
  9881. var arr = [ data[ 0 ], data[ 4 ], data[ 8 ] ];
  9882. fixCoords( arr, -1 );
  9883. data[ 0 ] = arr[ 0 ];
  9884. data[ 4 ] = arr[ 1 ];
  9885. data[ 8 ] = arr[ 2 ];
  9886. arr = [ data[ 1 ], data[ 5 ], data[ 9 ] ];
  9887. fixCoords( arr, -1 );
  9888. data[ 1 ] = arr[ 0 ];
  9889. data[ 5 ] = arr[ 1 ];
  9890. data[ 9 ] = arr[ 2 ];
  9891. arr = [ data[ 2 ], data[ 6 ], data[ 10 ] ];
  9892. fixCoords( arr, -1 );
  9893. data[ 2 ] = arr[ 0 ];
  9894. data[ 6 ] = arr[ 1 ];
  9895. data[ 10 ] = arr[ 2 ];
  9896. // Rows second
  9897. arr = [ data[ 0 ], data[ 1 ], data[ 2 ] ];
  9898. fixCoords( arr, -1 );
  9899. data[ 0 ] = arr[ 0 ];
  9900. data[ 1 ] = arr[ 1 ];
  9901. data[ 2 ] = arr[ 2 ];
  9902. arr = [ data[ 4 ], data[ 5 ], data[ 6 ] ];
  9903. fixCoords( arr, -1 );
  9904. data[ 4 ] = arr[ 0 ];
  9905. data[ 5 ] = arr[ 1 ];
  9906. data[ 6 ] = arr[ 2 ];
  9907. arr = [ data[ 8 ], data[ 9 ], data[ 10 ] ];
  9908. fixCoords( arr, -1 );
  9909. data[ 8 ] = arr[ 0 ];
  9910. data[ 9 ] = arr[ 1 ];
  9911. data[ 10 ] = arr[ 2 ];
  9912. // Now fix translation
  9913. arr = [ data[ 3 ], data[ 7 ], data[ 11 ] ];
  9914. fixCoords( arr, -1 );
  9915. data[ 3 ] = arr[ 0 ];
  9916. data[ 7 ] = arr[ 1 ];
  9917. data[ 11 ] = arr[ 2 ];
  9918. }
  9919. return new THREE.Matrix4(
  9920. data[0], data[1], data[2], data[3],
  9921. data[4], data[5], data[6], data[7],
  9922. data[8], data[9], data[10], data[11],
  9923. data[12], data[13], data[14], data[15]
  9924. );
  9925. };
  9926. function getConvertedIndex( index ) {
  9927. if ( index > -1 && index < 3 ) {
  9928. var members = ['X', 'Y', 'Z'],
  9929. indices = { X: 0, Y: 1, Z: 2 };
  9930. index = getConvertedMember( members[ index ] );
  9931. index = indices[ index ];
  9932. }
  9933. return index;
  9934. };
  9935. function getConvertedMember( member ) {
  9936. if ( options.convertUpAxis ) {
  9937. switch ( member ) {
  9938. case 'X':
  9939. switch ( upConversion ) {
  9940. case 'XtoY':
  9941. case 'XtoZ':
  9942. case 'YtoX':
  9943. member = 'Y';
  9944. break;
  9945. case 'ZtoX':
  9946. member = 'Z';
  9947. break;
  9948. }
  9949. break;
  9950. case 'Y':
  9951. switch ( upConversion ) {
  9952. case 'XtoY':
  9953. case 'YtoX':
  9954. case 'ZtoX':
  9955. member = 'X';
  9956. break;
  9957. case 'XtoZ':
  9958. case 'YtoZ':
  9959. case 'ZtoY':
  9960. member = 'Z';
  9961. break;
  9962. }
  9963. break;
  9964. case 'Z':
  9965. switch ( upConversion ) {
  9966. case 'XtoZ':
  9967. member = 'X';
  9968. break;
  9969. case 'YtoZ':
  9970. case 'ZtoX':
  9971. case 'ZtoY':
  9972. member = 'Y';
  9973. break;
  9974. }
  9975. break;
  9976. }
  9977. }
  9978. return member;
  9979. };
  9980. return {
  9981. load: load,
  9982. parse: parse,
  9983. setPreferredShading: setPreferredShading,
  9984. applySkin: applySkin,
  9985. geometries : geometries,
  9986. options: options
  9987. };
  9988. };
  9989. /**
  9990. * @author mrdoob / http://mrdoob.com/
  9991. * @author alteredq / http://alteredqualia.com/
  9992. */
  9993. THREE.JSONLoader = function ( showStatus ) {
  9994. THREE.Loader.call( this, showStatus );
  9995. };
  9996. THREE.JSONLoader.prototype = new THREE.Loader();
  9997. THREE.JSONLoader.prototype.constructor = THREE.JSONLoader;
  9998. THREE.JSONLoader.prototype.supr = THREE.Loader.prototype;
  9999. THREE.JSONLoader.prototype.load = function ( url, callback, texturePath ) {
  10000. var worker, scope = this;
  10001. texturePath = texturePath ? texturePath : this.extractUrlBase( url );
  10002. this.onLoadStart();
  10003. this.loadAjaxJSON( this, url, callback, texturePath );
  10004. };
  10005. THREE.JSONLoader.prototype.loadAjaxJSON = function ( context, url, callback, texturePath, callbackProgress ) {
  10006. var xhr = new XMLHttpRequest();
  10007. var length = 0;
  10008. xhr.onreadystatechange = function () {
  10009. if ( xhr.readyState === xhr.DONE ) {
  10010. if ( xhr.status === 200 || xhr.status === 0 ) {
  10011. if ( xhr.responseText ) {
  10012. var json = JSON.parse( xhr.responseText );
  10013. context.createModel( json, callback, texturePath );
  10014. } else {
  10015. console.warn( "THREE.JSONLoader: [" + url + "] seems to be unreachable or file there is empty" );
  10016. }
  10017. // in context of more complex asset initialization
  10018. // do not block on single failed file
  10019. // maybe should go even one more level up
  10020. context.onLoadComplete();
  10021. } else {
  10022. console.error( "THREE.JSONLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  10023. }
  10024. } else if ( xhr.readyState === xhr.LOADING ) {
  10025. if ( callbackProgress ) {
  10026. if ( length === 0 ) {
  10027. length = xhr.getResponseHeader( "Content-Length" );
  10028. }
  10029. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  10030. }
  10031. } else if ( xhr.readyState === xhr.HEADERS_RECEIVED ) {
  10032. length = xhr.getResponseHeader( "Content-Length" );
  10033. }
  10034. };
  10035. xhr.open( "GET", url, true );
  10036. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  10037. xhr.setRequestHeader( "Content-Type", "text/plain" );
  10038. xhr.send( null );
  10039. };
  10040. THREE.JSONLoader.prototype.createModel = function ( json, callback, texturePath ) {
  10041. var scope = this,
  10042. geometry = new THREE.Geometry(),
  10043. scale = ( json.scale !== undefined ) ? 1.0 / json.scale : 1.0;
  10044. this.initMaterials( geometry, json.materials, texturePath );
  10045. parseModel( scale );
  10046. parseSkin();
  10047. parseMorphing( scale );
  10048. geometry.computeCentroids();
  10049. geometry.computeFaceNormals();
  10050. if ( this.hasNormals( geometry ) ) geometry.computeTangents();
  10051. function parseModel( scale ) {
  10052. function isBitSet( value, position ) {
  10053. return value & ( 1 << position );
  10054. }
  10055. var i, j, fi,
  10056. offset, zLength, nVertices,
  10057. colorIndex, normalIndex, uvIndex, materialIndex,
  10058. type,
  10059. isQuad,
  10060. hasMaterial,
  10061. hasFaceUv, hasFaceVertexUv,
  10062. hasFaceNormal, hasFaceVertexNormal,
  10063. hasFaceColor, hasFaceVertexColor,
  10064. vertex, face, color, normal,
  10065. uvLayer, uvs, u, v,
  10066. faces = json.faces,
  10067. vertices = json.vertices,
  10068. normals = json.normals,
  10069. colors = json.colors,
  10070. nUvLayers = 0;
  10071. // disregard empty arrays
  10072. for ( i = 0; i < json.uvs.length; i++ ) {
  10073. if ( json.uvs[ i ].length ) nUvLayers ++;
  10074. }
  10075. for ( i = 0; i < nUvLayers; i++ ) {
  10076. geometry.faceUvs[ i ] = [];
  10077. geometry.faceVertexUvs[ i ] = [];
  10078. }
  10079. offset = 0;
  10080. zLength = vertices.length;
  10081. while ( offset < zLength ) {
  10082. vertex = new THREE.Vertex();
  10083. vertex.x = vertices[ offset ++ ] * scale;
  10084. vertex.y = vertices[ offset ++ ] * scale;
  10085. vertex.z = vertices[ offset ++ ] * scale;
  10086. geometry.vertices.push( vertex );
  10087. }
  10088. offset = 0;
  10089. zLength = faces.length;
  10090. while ( offset < zLength ) {
  10091. type = faces[ offset ++ ];
  10092. isQuad = isBitSet( type, 0 );
  10093. hasMaterial = isBitSet( type, 1 );
  10094. hasFaceUv = isBitSet( type, 2 );
  10095. hasFaceVertexUv = isBitSet( type, 3 );
  10096. hasFaceNormal = isBitSet( type, 4 );
  10097. hasFaceVertexNormal = isBitSet( type, 5 );
  10098. hasFaceColor = isBitSet( type, 6 );
  10099. hasFaceVertexColor = isBitSet( type, 7 );
  10100. //console.log("type", type, "bits", isQuad, hasMaterial, hasFaceUv, hasFaceVertexUv, hasFaceNormal, hasFaceVertexNormal, hasFaceColor, hasFaceVertexColor);
  10101. if ( isQuad ) {
  10102. face = new THREE.Face4();
  10103. face.a = faces[ offset ++ ];
  10104. face.b = faces[ offset ++ ];
  10105. face.c = faces[ offset ++ ];
  10106. face.d = faces[ offset ++ ];
  10107. nVertices = 4;
  10108. } else {
  10109. face = new THREE.Face3();
  10110. face.a = faces[ offset ++ ];
  10111. face.b = faces[ offset ++ ];
  10112. face.c = faces[ offset ++ ];
  10113. nVertices = 3;
  10114. }
  10115. if ( hasMaterial ) {
  10116. materialIndex = faces[ offset ++ ];
  10117. face.materialIndex = materialIndex;
  10118. }
  10119. // to get face <=> uv index correspondence
  10120. fi = geometry.faces.length;
  10121. if ( hasFaceUv ) {
  10122. for ( i = 0; i < nUvLayers; i++ ) {
  10123. uvLayer = json.uvs[ i ];
  10124. uvIndex = faces[ offset ++ ];
  10125. u = uvLayer[ uvIndex * 2 ];
  10126. v = uvLayer[ uvIndex * 2 + 1 ];
  10127. geometry.faceUvs[ i ][ fi ] = new THREE.UV( u, v );
  10128. }
  10129. }
  10130. if ( hasFaceVertexUv ) {
  10131. for ( i = 0; i < nUvLayers; i++ ) {
  10132. uvLayer = json.uvs[ i ];
  10133. uvs = [];
  10134. for ( j = 0; j < nVertices; j ++ ) {
  10135. uvIndex = faces[ offset ++ ];
  10136. u = uvLayer[ uvIndex * 2 ];
  10137. v = uvLayer[ uvIndex * 2 + 1 ];
  10138. uvs[ j ] = new THREE.UV( u, v );
  10139. }
  10140. geometry.faceVertexUvs[ i ][ fi ] = uvs;
  10141. }
  10142. }
  10143. if ( hasFaceNormal ) {
  10144. normalIndex = faces[ offset ++ ] * 3;
  10145. normal = new THREE.Vector3();
  10146. normal.x = normals[ normalIndex ++ ];
  10147. normal.y = normals[ normalIndex ++ ];
  10148. normal.z = normals[ normalIndex ];
  10149. face.normal = normal;
  10150. }
  10151. if ( hasFaceVertexNormal ) {
  10152. for ( i = 0; i < nVertices; i++ ) {
  10153. normalIndex = faces[ offset ++ ] * 3;
  10154. normal = new THREE.Vector3();
  10155. normal.x = normals[ normalIndex ++ ];
  10156. normal.y = normals[ normalIndex ++ ];
  10157. normal.z = normals[ normalIndex ];
  10158. face.vertexNormals.push( normal );
  10159. }
  10160. }
  10161. if ( hasFaceColor ) {
  10162. colorIndex = faces[ offset ++ ];
  10163. color = new THREE.Color( colors[ colorIndex ] );
  10164. face.color = color;
  10165. }
  10166. if ( hasFaceVertexColor ) {
  10167. for ( i = 0; i < nVertices; i++ ) {
  10168. colorIndex = faces[ offset ++ ];
  10169. color = new THREE.Color( colors[ colorIndex ] );
  10170. face.vertexColors.push( color );
  10171. }
  10172. }
  10173. geometry.faces.push( face );
  10174. }
  10175. };
  10176. function parseSkin() {
  10177. var i, l, x, y, z, w, a, b, c, d;
  10178. if ( json.skinWeights ) {
  10179. for ( i = 0, l = json.skinWeights.length; i < l; i += 2 ) {
  10180. x = json.skinWeights[ i ];
  10181. y = json.skinWeights[ i + 1 ];
  10182. z = 0;
  10183. w = 0;
  10184. geometry.skinWeights.push( new THREE.Vector4( x, y, z, w ) );
  10185. }
  10186. }
  10187. if ( json.skinIndices ) {
  10188. for ( i = 0, l = json.skinIndices.length; i < l; i += 2 ) {
  10189. a = json.skinIndices[ i ];
  10190. b = json.skinIndices[ i + 1 ];
  10191. c = 0;
  10192. d = 0;
  10193. geometry.skinIndices.push( new THREE.Vector4( a, b, c, d ) );
  10194. }
  10195. }
  10196. geometry.bones = json.bones;
  10197. geometry.animation = json.animation;
  10198. };
  10199. function parseMorphing( scale ) {
  10200. if ( json.morphTargets !== undefined ) {
  10201. var i, l, v, vl, x, y, z, dstVertices, srcVertices;
  10202. for ( i = 0, l = json.morphTargets.length; i < l; i ++ ) {
  10203. geometry.morphTargets[ i ] = {};
  10204. geometry.morphTargets[ i ].name = json.morphTargets[ i ].name;
  10205. geometry.morphTargets[ i ].vertices = [];
  10206. dstVertices = geometry.morphTargets[ i ].vertices;
  10207. srcVertices = json.morphTargets [ i ].vertices;
  10208. for( v = 0, vl = srcVertices.length; v < vl; v += 3 ) {
  10209. x = srcVertices[ v ] * scale;
  10210. y = srcVertices[ v + 1 ] * scale;
  10211. z = srcVertices[ v + 2 ] * scale;
  10212. dstVertices.push( new THREE.Vertex( x, y, z ) );
  10213. }
  10214. }
  10215. }
  10216. if ( json.morphColors !== undefined ) {
  10217. var i, l, c, cl, dstColors, srcColors, color;
  10218. for ( i = 0, l = json.morphColors.length; i < l; i++ ) {
  10219. geometry.morphColors[ i ] = {};
  10220. geometry.morphColors[ i ].name = json.morphColors[ i ].name;
  10221. geometry.morphColors[ i ].colors = [];
  10222. dstColors = geometry.morphColors[ i ].colors;
  10223. srcColors = json.morphColors [ i ].colors;
  10224. for ( c = 0, cl = srcColors.length; c < cl; c += 3 ) {
  10225. color = new THREE.Color( 0xffaa00 );
  10226. color.setRGB( srcColors[ c ], srcColors[ c + 1 ], srcColors[ c + 2 ] );
  10227. dstColors.push( color );
  10228. }
  10229. }
  10230. }
  10231. };
  10232. callback( geometry );
  10233. };
  10234. /**
  10235. * @author alteredq / http://alteredqualia.com/
  10236. */
  10237. THREE.SceneLoader = function () {
  10238. this.onLoadStart = function () {};
  10239. this.onLoadProgress = function() {};
  10240. this.onLoadComplete = function () {};
  10241. this.callbackSync = function () {};
  10242. this.callbackProgress = function () {};
  10243. };
  10244. THREE.SceneLoader.prototype.constructor = THREE.SceneLoader;
  10245. THREE.SceneLoader.prototype.load = function( url, callbackFinished ) {
  10246. var context = this;
  10247. var xhr = new XMLHttpRequest();
  10248. xhr.onreadystatechange = function () {
  10249. if ( xhr.readyState == 4 ) {
  10250. if ( xhr.status == 200 || xhr.status == 0 ) {
  10251. var json = JSON.parse( xhr.responseText );
  10252. context.createScene( json, callbackFinished, url );
  10253. } else {
  10254. console.error( "THREE.SceneLoader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  10255. }
  10256. }
  10257. };
  10258. xhr.open( "GET", url, true );
  10259. if ( xhr.overrideMimeType ) xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
  10260. xhr.setRequestHeader( "Content-Type", "text/plain" );
  10261. xhr.send( null );
  10262. };
  10263. THREE.SceneLoader.prototype.createScene = function ( json, callbackFinished, url ) {
  10264. var scope = this;
  10265. var urlBase = THREE.Loader.prototype.extractUrlBase( url );
  10266. var dg, dm, dd, dl, dc, df, dt,
  10267. g, o, m, l, d, p, r, q, s, c, t, f, tt, pp, u,
  10268. geometry, material, camera, fog,
  10269. texture, images,
  10270. light,
  10271. data, binLoader, jsonLoader,
  10272. counter_models, counter_textures,
  10273. total_models, total_textures,
  10274. result;
  10275. data = json;
  10276. binLoader = new THREE.BinaryLoader();
  10277. jsonLoader = new THREE.JSONLoader();
  10278. counter_models = 0;
  10279. counter_textures = 0;
  10280. result = {
  10281. scene: new THREE.Scene(),
  10282. geometries: {},
  10283. materials: {},
  10284. textures: {},
  10285. objects: {},
  10286. cameras: {},
  10287. lights: {},
  10288. fogs: {},
  10289. empties: {}
  10290. };
  10291. if ( data.transform ) {
  10292. var position = data.transform.position,
  10293. rotation = data.transform.rotation,
  10294. scale = data.transform.scale;
  10295. if ( position )
  10296. result.scene.position.set( position[ 0 ], position[ 1 ], position [ 2 ] );
  10297. if ( rotation )
  10298. result.scene.rotation.set( rotation[ 0 ], rotation[ 1 ], rotation [ 2 ] );
  10299. if ( scale )
  10300. result.scene.scale.set( scale[ 0 ], scale[ 1 ], scale [ 2 ] );
  10301. if ( position || rotation || scale ) {
  10302. result.scene.updateMatrix();
  10303. result.scene.updateMatrixWorld();
  10304. }
  10305. }
  10306. function get_url( source_url, url_type ) {
  10307. if ( url_type == "relativeToHTML" ) {
  10308. return source_url;
  10309. } else {
  10310. return urlBase + "/" + source_url;
  10311. }
  10312. };
  10313. function handle_objects() {
  10314. var object;
  10315. for( dd in data.objects ) {
  10316. if ( !result.objects[ dd ] ) {
  10317. o = data.objects[ dd ];
  10318. if ( o.geometry !== undefined ) {
  10319. geometry = result.geometries[ o.geometry ];
  10320. // geometry already loaded
  10321. if ( geometry ) {
  10322. var hasNormals = false;
  10323. // not anymore support for multiple materials
  10324. // shouldn't really be array
  10325. material = result.materials[ o.materials[ 0 ] ];
  10326. hasNormals = material instanceof THREE.ShaderMaterial;
  10327. if ( hasNormals ) {
  10328. geometry.computeTangents();
  10329. }
  10330. p = o.position;
  10331. r = o.rotation;
  10332. q = o.quaternion;
  10333. s = o.scale;
  10334. // turn off quaternions, for the moment
  10335. q = 0;
  10336. if ( o.materials.length == 0 ) {
  10337. material = new THREE.MeshFaceMaterial();
  10338. }
  10339. // dirty hack to handle meshes with multiple materials
  10340. // just use face materials defined in model
  10341. if ( o.materials.length > 1 ) {
  10342. material = new THREE.MeshFaceMaterial();
  10343. }
  10344. object = new THREE.Mesh( geometry, material );
  10345. object.name = dd;
  10346. object.position.set( p[0], p[1], p[2] );
  10347. if ( q ) {
  10348. object.quaternion.set( q[0], q[1], q[2], q[3] );
  10349. object.useQuaternion = true;
  10350. } else {
  10351. object.rotation.set( r[0], r[1], r[2] );
  10352. }
  10353. object.scale.set( s[0], s[1], s[2] );
  10354. object.visible = o.visible;
  10355. object.doubleSided = o.doubleSided;
  10356. object.castShadow = o.castShadow;
  10357. object.receiveShadow = o.receiveShadow;
  10358. result.scene.add( object );
  10359. result.objects[ dd ] = object;
  10360. }
  10361. // pure Object3D
  10362. } else {
  10363. p = o.position;
  10364. r = o.rotation;
  10365. q = o.quaternion;
  10366. s = o.scale;
  10367. // turn off quaternions, for the moment
  10368. q = 0;
  10369. object = new THREE.Object3D();
  10370. object.name = dd;
  10371. object.position.set( p[0], p[1], p[2] );
  10372. if ( q ) {
  10373. object.quaternion.set( q[0], q[1], q[2], q[3] );
  10374. object.useQuaternion = true;
  10375. } else {
  10376. object.rotation.set( r[0], r[1], r[2] );
  10377. }
  10378. object.scale.set( s[0], s[1], s[2] );
  10379. object.visible = ( o.visible !== undefined ) ? o.visible : false;
  10380. result.scene.add( object );
  10381. result.objects[ dd ] = object;
  10382. result.empties[ dd ] = object;
  10383. }
  10384. }
  10385. }
  10386. };
  10387. function handle_mesh( geo, id ) {
  10388. result.geometries[ id ] = geo;
  10389. handle_objects();
  10390. };
  10391. function create_callback( id ) {
  10392. return function( geo ) {
  10393. handle_mesh( geo, id );
  10394. counter_models -= 1;
  10395. scope.onLoadComplete();
  10396. async_callback_gate();
  10397. }
  10398. };
  10399. function create_callback_embed( id ) {
  10400. return function( geo ) {
  10401. result.geometries[ id ] = geo;
  10402. }
  10403. };
  10404. function async_callback_gate() {
  10405. var progress = {
  10406. totalModels : total_models,
  10407. totalTextures : total_textures,
  10408. loadedModels : total_models - counter_models,
  10409. loadedTextures : total_textures - counter_textures
  10410. };
  10411. scope.callbackProgress( progress, result );
  10412. scope.onLoadProgress();
  10413. if( counter_models == 0 && counter_textures == 0 ) {
  10414. callbackFinished( result );
  10415. }
  10416. };
  10417. var callbackTexture = function( images ) {
  10418. counter_textures -= 1;
  10419. async_callback_gate();
  10420. scope.onLoadComplete();
  10421. };
  10422. // first go synchronous elements
  10423. // cameras
  10424. for( dc in data.cameras ) {
  10425. c = data.cameras[ dc ];
  10426. if ( c.type == "perspective" ) {
  10427. camera = new THREE.PerspectiveCamera( c.fov, c.aspect, c.near, c.far );
  10428. } else if ( c.type == "ortho" ) {
  10429. camera = new THREE.OrthographicCamera( c.left, c.right, c.top, c.bottom, c.near, c.far );
  10430. }
  10431. p = c.position;
  10432. t = c.target;
  10433. u = c.up;
  10434. camera.position.set( p[0], p[1], p[2] );
  10435. camera.target = new THREE.Vector3( t[0], t[1], t[2] );
  10436. if ( u ) camera.up.set( u[0], u[1], u[2] );
  10437. result.cameras[ dc ] = camera;
  10438. }
  10439. // lights
  10440. var hex, intensity;
  10441. for ( dl in data.lights ) {
  10442. l = data.lights[ dl ];
  10443. hex = ( l.color !== undefined ) ? l.color : 0xffffff;
  10444. intensity = ( l.intensity !== undefined ) ? l.intensity : 1;
  10445. if ( l.type == "directional" ) {
  10446. p = l.direction;
  10447. light = new THREE.DirectionalLight( hex, intensity );
  10448. light.position.set( p[0], p[1], p[2] );
  10449. light.position.normalize();
  10450. } else if ( l.type == "point" ) {
  10451. p = l.position;
  10452. d = l.distance;
  10453. light = new THREE.PointLight( hex, intensity, d );
  10454. light.position.set( p[0], p[1], p[2] );
  10455. } else if ( l.type == "ambient" ) {
  10456. light = new THREE.AmbientLight( hex );
  10457. }
  10458. result.scene.add( light );
  10459. result.lights[ dl ] = light;
  10460. }
  10461. // fogs
  10462. for( df in data.fogs ) {
  10463. f = data.fogs[ df ];
  10464. if ( f.type == "linear" ) {
  10465. fog = new THREE.Fog( 0x000000, f.near, f.far );
  10466. } else if ( f.type == "exp2" ) {
  10467. fog = new THREE.FogExp2( 0x000000, f.density );
  10468. }
  10469. c = f.color;
  10470. fog.color.setRGB( c[0], c[1], c[2] );
  10471. result.fogs[ df ] = fog;
  10472. }
  10473. // defaults
  10474. if ( result.cameras && data.defaults.camera ) {
  10475. result.currentCamera = result.cameras[ data.defaults.camera ];
  10476. }
  10477. if ( result.fogs && data.defaults.fog ) {
  10478. result.scene.fog = result.fogs[ data.defaults.fog ];
  10479. }
  10480. c = data.defaults.bgcolor;
  10481. result.bgColor = new THREE.Color();
  10482. result.bgColor.setRGB( c[0], c[1], c[2] );
  10483. result.bgColorAlpha = data.defaults.bgalpha;
  10484. // now come potentially asynchronous elements
  10485. // geometries
  10486. // count how many models will be loaded asynchronously
  10487. for( dg in data.geometries ) {
  10488. g = data.geometries[ dg ];
  10489. if ( g.type == "bin_mesh" || g.type == "ascii_mesh" ) {
  10490. counter_models += 1;
  10491. scope.onLoadStart();
  10492. }
  10493. }
  10494. total_models = counter_models;
  10495. for ( dg in data.geometries ) {
  10496. g = data.geometries[ dg ];
  10497. if ( g.type == "cube" ) {
  10498. geometry = new THREE.CubeGeometry( g.width, g.height, g.depth, g.segmentsWidth, g.segmentsHeight, g.segmentsDepth, null, g.flipped, g.sides );
  10499. result.geometries[ dg ] = geometry;
  10500. } else if ( g.type == "plane" ) {
  10501. geometry = new THREE.PlaneGeometry( g.width, g.height, g.segmentsWidth, g.segmentsHeight );
  10502. result.geometries[ dg ] = geometry;
  10503. } else if ( g.type == "sphere" ) {
  10504. geometry = new THREE.SphereGeometry( g.radius, g.segmentsWidth, g.segmentsHeight );
  10505. result.geometries[ dg ] = geometry;
  10506. } else if ( g.type == "cylinder" ) {
  10507. geometry = new THREE.CylinderGeometry( g.topRad, g.botRad, g.height, g.radSegs, g.heightSegs );
  10508. result.geometries[ dg ] = geometry;
  10509. } else if ( g.type == "torus" ) {
  10510. geometry = new THREE.TorusGeometry( g.radius, g.tube, g.segmentsR, g.segmentsT );
  10511. result.geometries[ dg ] = geometry;
  10512. } else if ( g.type == "icosahedron" ) {
  10513. geometry = new THREE.IcosahedronGeometry( g.radius, g.subdivisions );
  10514. result.geometries[ dg ] = geometry;
  10515. } else if ( g.type == "bin_mesh" ) {
  10516. binLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  10517. } else if ( g.type == "ascii_mesh" ) {
  10518. jsonLoader.load( get_url( g.url, data.urlBaseType ), create_callback( dg ) );
  10519. } else if ( g.type == "embedded_mesh" ) {
  10520. var modelJson = data.embeds[ g.id ],
  10521. texture_path = "";
  10522. // Pass metadata along to jsonLoader so it knows the format version.
  10523. modelJson.metadata = data.metadata;
  10524. if ( modelJson ) {
  10525. jsonLoader.createModel( modelJson, create_callback_embed( dg ), texture_path );
  10526. }
  10527. }
  10528. }
  10529. // textures
  10530. // count how many textures will be loaded asynchronously
  10531. for( dt in data.textures ) {
  10532. tt = data.textures[ dt ];
  10533. if( tt.url instanceof Array ) {
  10534. counter_textures += tt.url.length;
  10535. for( var n = 0; n < tt.url.length; n ++ ) {
  10536. scope.onLoadStart();
  10537. }
  10538. } else {
  10539. counter_textures += 1;
  10540. scope.onLoadStart();
  10541. }
  10542. }
  10543. total_textures = counter_textures;
  10544. for( dt in data.textures ) {
  10545. tt = data.textures[ dt ];
  10546. if ( tt.mapping != undefined && THREE[ tt.mapping ] != undefined ) {
  10547. tt.mapping = new THREE[ tt.mapping ]();
  10548. }
  10549. if( tt.url instanceof Array ) {
  10550. var url_array = [];
  10551. for( var i = 0; i < tt.url.length; i ++ ) {
  10552. url_array[ i ] = get_url( tt.url[ i ], data.urlBaseType );
  10553. }
  10554. texture = THREE.ImageUtils.loadTextureCube( url_array, tt.mapping, callbackTexture );
  10555. } else {
  10556. texture = THREE.ImageUtils.loadTexture( get_url( tt.url, data.urlBaseType ), tt.mapping, callbackTexture );
  10557. if ( THREE[ tt.minFilter ] != undefined )
  10558. texture.minFilter = THREE[ tt.minFilter ];
  10559. if ( THREE[ tt.magFilter ] != undefined )
  10560. texture.magFilter = THREE[ tt.magFilter ];
  10561. if ( tt.repeat ) {
  10562. texture.repeat.set( tt.repeat[ 0 ], tt.repeat[ 1 ] );
  10563. if ( tt.repeat[ 0 ] != 1 ) texture.wrapS = THREE.RepeatWrapping;
  10564. if ( tt.repeat[ 1 ] != 1 ) texture.wrapT = THREE.RepeatWrapping;
  10565. }
  10566. if ( tt.offset ) {
  10567. texture.offset.set( tt.offset[ 0 ], tt.offset[ 1 ] );
  10568. }
  10569. // handle wrap after repeat so that default repeat can be overriden
  10570. if ( tt.wrap ) {
  10571. var wrapMap = {
  10572. "repeat" : THREE.RepeatWrapping,
  10573. "mirror" : THREE.MirroredRepeatWrapping
  10574. }
  10575. if ( wrapMap[ tt.wrap[ 0 ] ] !== undefined ) texture.wrapS = wrapMap[ tt.wrap[ 0 ] ];
  10576. if ( wrapMap[ tt.wrap[ 1 ] ] !== undefined ) texture.wrapT = wrapMap[ tt.wrap[ 1 ] ];
  10577. }
  10578. }
  10579. result.textures[ dt ] = texture;
  10580. }
  10581. // materials
  10582. for ( dm in data.materials ) {
  10583. m = data.materials[ dm ];
  10584. for ( pp in m.parameters ) {
  10585. if ( pp == "envMap" || pp == "map" || pp == "lightMap" ) {
  10586. m.parameters[ pp ] = result.textures[ m.parameters[ pp ] ];
  10587. } else if ( pp == "shading" ) {
  10588. m.parameters[ pp ] = ( m.parameters[ pp ] == "flat" ) ? THREE.FlatShading : THREE.SmoothShading;
  10589. } else if ( pp == "blending" ) {
  10590. m.parameters[ pp ] = THREE[ m.parameters[ pp ] ] ? THREE[ m.parameters[ pp ] ] : THREE.NormalBlending;
  10591. } else if ( pp == "combine" ) {
  10592. m.parameters[ pp ] = ( m.parameters[ pp ] == "MixOperation" ) ? THREE.MixOperation : THREE.MultiplyOperation;
  10593. } else if ( pp == "vertexColors" ) {
  10594. if ( m.parameters[ pp ] == "face" ) {
  10595. m.parameters[ pp ] = THREE.FaceColors;
  10596. // default to vertex colors if "vertexColors" is anything else face colors or 0 / null / false
  10597. } else if ( m.parameters[ pp ] ) {
  10598. m.parameters[ pp ] = THREE.VertexColors;
  10599. }
  10600. }
  10601. }
  10602. if ( m.parameters.opacity !== undefined && m.parameters.opacity < 1.0 ) {
  10603. m.parameters.transparent = true;
  10604. }
  10605. if ( m.parameters.normalMap ) {
  10606. var shader = THREE.ShaderUtils.lib[ "normal" ];
  10607. var uniforms = THREE.UniformsUtils.clone( shader.uniforms );
  10608. var diffuse = m.parameters.color;
  10609. var specular = m.parameters.specular;
  10610. var ambient = m.parameters.ambient;
  10611. var shininess = m.parameters.shininess;
  10612. uniforms[ "tNormal" ].texture = result.textures[ m.parameters.normalMap ];
  10613. if ( m.parameters.normalMapFactor ) {
  10614. uniforms[ "uNormalScale" ].value = m.parameters.normalMapFactor;
  10615. }
  10616. if ( m.parameters.map ) {
  10617. uniforms[ "tDiffuse" ].texture = m.parameters.map;
  10618. uniforms[ "enableDiffuse" ].value = true;
  10619. }
  10620. if ( m.parameters.lightMap ) {
  10621. uniforms[ "tAO" ].texture = m.parameters.lightMap;
  10622. uniforms[ "enableAO" ].value = true;
  10623. }
  10624. if ( m.parameters.specularMap ) {
  10625. uniforms[ "tSpecular" ].texture = result.textures[ m.parameters.specularMap ];
  10626. uniforms[ "enableSpecular" ].value = true;
  10627. }
  10628. uniforms[ "uDiffuseColor" ].value.setHex( diffuse );
  10629. uniforms[ "uSpecularColor" ].value.setHex( specular );
  10630. uniforms[ "uAmbientColor" ].value.setHex( ambient );
  10631. uniforms[ "uShininess" ].value = shininess;
  10632. if ( m.parameters.opacity ) {
  10633. uniforms[ "uOpacity" ].value = m.parameters.opacity;
  10634. }
  10635. var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, fog: true };
  10636. material = new THREE.ShaderMaterial( parameters );
  10637. } else {
  10638. material = new THREE[ m.type ]( m.parameters );
  10639. }
  10640. result.materials[ dm ] = material;
  10641. }
  10642. // objects ( synchronous init of procedural primitives )
  10643. handle_objects();
  10644. // synchronous callback
  10645. scope.callbackSync( result );
  10646. // just in case there are no async elements:
  10647. async_callback_gate();
  10648. };
  10649. /**
  10650. * Loader for UTF8 encoded models generated by:
  10651. * http://code.google.com/p/webgl-loader/
  10652. *
  10653. * Limitations:
  10654. * - number of vertices < 65536 (this is after optimizations in compressor, input OBJ may have even less)
  10655. * - models must have normals and texture coordinates
  10656. * - texture coordinates must be only from <0,1>
  10657. * - no materials support yet
  10658. * - models are scaled and offset (copy numbers from compressor and use them as parameters in UTF8Loader.load() )
  10659. *
  10660. * @author alteredq / http://alteredqualia.com/
  10661. * @author won3d / http://twitter.com/won3d
  10662. */
  10663. THREE.UTF8Loader = function () {};
  10664. THREE.UTF8Loader.prototype.load = function ( url, callback, metadata ) {
  10665. var xhr = new XMLHttpRequest(),
  10666. callbackProgress = null,
  10667. scale = metadata.scale !== undefined ? metadata.scale : 1,
  10668. offsetX = metadata.offsetX !== undefined ? metadata.offsetX : 0,
  10669. offsetY = metadata.offsetY !== undefined ? metadata.offsetY : 0,
  10670. offsetZ = metadata.offsetZ !== undefined ? metadata.offsetZ : 0;
  10671. var length = 0;
  10672. xhr.onreadystatechange = function() {
  10673. if ( xhr.readyState == 4 ) {
  10674. if ( xhr.status == 200 || xhr.status == 0 ) {
  10675. THREE.UTF8Loader.prototype.createModel( xhr.responseText, callback, scale, offsetX, offsetY, offsetZ );
  10676. } else {
  10677. console.error( "THREE.UTF8Loader: Couldn't load [" + url + "] [" + xhr.status + "]" );
  10678. }
  10679. } else if ( xhr.readyState == 3 ) {
  10680. if ( callbackProgress ) {
  10681. if ( length == 0 ) {
  10682. length = xhr.getResponseHeader( "Content-Length" );
  10683. }
  10684. callbackProgress( { total: length, loaded: xhr.responseText.length } );
  10685. }
  10686. } else if ( xhr.readyState == 2 ) {
  10687. length = xhr.getResponseHeader( "Content-Length" );
  10688. }
  10689. }
  10690. xhr.open( "GET", url, true );
  10691. xhr.send( null );
  10692. };
  10693. // UTF-8 decoder from webgl-loader
  10694. // http://code.google.com/p/webgl-loader/
  10695. // Copyright 2011 Google Inc. All Rights Reserved.
  10696. //
  10697. // Licensed under the Apache License, Version 2.0 (the "License"); you
  10698. // may not use this file except in compliance with the License. You
  10699. // may obtain a copy of the License at
  10700. //
  10701. // http://www.apache.org/licenses/LICENSE-2.0
  10702. //
  10703. // Unless required by applicable law or agreed to in writing, software
  10704. // distributed under the License is distributed on an "AS IS" BASIS,
  10705. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  10706. // implied. See the License for the specific language governing
  10707. // permissions and limitations under the License.
  10708. THREE.UTF8Loader.prototype.decompressMesh = function ( str ) {
  10709. var num_verts = str.charCodeAt( 0 );
  10710. if ( num_verts >= 0xE000 ) {
  10711. num_verts -= 0x0800;
  10712. }
  10713. num_verts ++;
  10714. var attribs_out = new Float32Array( 8 * num_verts );
  10715. var offset = 1;
  10716. for ( var i = 0; i < 8; i ++ ) {
  10717. var prev_attrib = 0;
  10718. for ( var j = 0; j < num_verts; ++ j ) {
  10719. var code = str.charCodeAt( j + offset );
  10720. prev_attrib += ( code >> 1 ) ^ ( - ( code & 1 ) );
  10721. attribs_out[ 8 * j + i ] = prev_attrib;
  10722. }
  10723. offset += num_verts;
  10724. }
  10725. var num_indices = str.length - offset;
  10726. var indices_out = new Uint16Array( num_indices );
  10727. var index_high_water_mark = 0;
  10728. for ( var i = 0; i < num_indices; i ++ ) {
  10729. var code = str.charCodeAt( i + offset );
  10730. indices_out[ i ] = index_high_water_mark - code;
  10731. if ( code == 0 ) {
  10732. index_high_water_mark ++;
  10733. }
  10734. }
  10735. return [ attribs_out, indices_out ];
  10736. };
  10737. THREE.UTF8Loader.prototype.createModel = function ( data, callback, scale, offsetX, offsetY, offsetZ ) {
  10738. var Model = function ( texture_path ) {
  10739. //var s = (new Date).getTime();
  10740. var scope = this;
  10741. scope.materials = [];
  10742. THREE.Geometry.call( this );
  10743. var buffers = THREE.UTF8Loader.prototype.decompressMesh( data );
  10744. var normals = [],
  10745. uvs = [];
  10746. init_vertices( buffers[ 0 ], 8, 0 );
  10747. init_uvs( buffers[ 0 ], 8, 3 );
  10748. init_normals( buffers[ 0 ], 8, 5 );
  10749. init_faces( buffers[ 1 ] );
  10750. this.computeCentroids();
  10751. this.computeFaceNormals();
  10752. //this.computeTangents();
  10753. //var e = (new Date).getTime();
  10754. //console.log( "utf8 data parse time: " + (e-s) + " ms" );
  10755. function init_vertices( data, stride, offset ) {
  10756. var i, x, y, z,
  10757. end = data.length;
  10758. for( i = offset; i < end; i += stride ) {
  10759. x = data[ i ];
  10760. y = data[ i + 1 ];
  10761. z = data[ i + 2 ];
  10762. // fix scale and offsets
  10763. x = ( x / 16383 ) * scale;
  10764. y = ( y / 16383 ) * scale;
  10765. z = ( z / 16383 ) * scale;
  10766. x += offsetX;
  10767. y += offsetY;
  10768. z += offsetZ;
  10769. vertex( scope, x, y, z );
  10770. }
  10771. };
  10772. function init_normals( data, stride, offset ) {
  10773. var i, x, y, z,
  10774. end = data.length;
  10775. for( i = offset; i < end; i += stride ) {
  10776. x = data[ i ];
  10777. y = data[ i + 1 ];
  10778. z = data[ i + 2 ];
  10779. // normalize to <-1,1>
  10780. x = ( x - 512 ) / 511;
  10781. y = ( y - 512 ) / 511;
  10782. z = ( z - 512 ) / 511;
  10783. normals.push( x, y, z );
  10784. }
  10785. };
  10786. function init_uvs( data, stride, offset ) {
  10787. var i, u, v,
  10788. end = data.length;
  10789. for( i = offset; i < end; i += stride ) {
  10790. u = data[ i ];
  10791. v = data[ i + 1 ];
  10792. // normalize to <0,1>
  10793. u /= 1023;
  10794. v /= 1023;
  10795. uvs.push( u, 1 - v );
  10796. }
  10797. };
  10798. function init_faces( indices ) {
  10799. var i,
  10800. a, b, c,
  10801. u1, v1, u2, v2, u3, v3,
  10802. m,
  10803. end = indices.length;
  10804. m = 0; // all faces defaulting to material 0
  10805. for( i = 0; i < end; i += 3 ) {
  10806. a = indices[ i ];
  10807. b = indices[ i + 1 ];
  10808. c = indices[ i + 2 ];
  10809. f3n( scope, normals, a, b, c, m, a, b, c );
  10810. u1 = uvs[ a * 2 ];
  10811. v1 = uvs[ a * 2 + 1 ];
  10812. u2 = uvs[ b * 2 ];
  10813. v2 = uvs[ b * 2 + 1 ];
  10814. u3 = uvs[ c * 2 ];
  10815. v3 = uvs[ c * 2 + 1 ];
  10816. uv3( scope.faceVertexUvs[ 0 ], u1, v1, u2, v2, u3, v3 );
  10817. }
  10818. }
  10819. };
  10820. function vertex ( scope, x, y, z ) {
  10821. scope.vertices.push( new THREE.Vertex( x, y, z ) );
  10822. };
  10823. function f3n ( scope, normals, a, b, c, mi, nai, nbi, nci ) {
  10824. var nax = normals[ nai * 3 ],
  10825. nay = normals[ nai * 3 + 1 ],
  10826. naz = normals[ nai * 3 + 2 ],
  10827. nbx = normals[ nbi * 3 ],
  10828. nby = normals[ nbi * 3 + 1 ],
  10829. nbz = normals[ nbi * 3 + 2 ],
  10830. ncx = normals[ nci * 3 ],
  10831. ncy = normals[ nci * 3 + 1 ],
  10832. ncz = normals[ nci * 3 + 2 ];
  10833. var na = new THREE.Vector3( nax, nay, naz ),
  10834. nb = new THREE.Vector3( nbx, nby, nbz ),
  10835. nc = new THREE.Vector3( ncx, ncy, ncz );
  10836. scope.faces.push( new THREE.Face3( a, b, c, [ na, nb, nc ], null, mi ) );
  10837. };
  10838. function uv3 ( where, u1, v1, u2, v2, u3, v3 ) {
  10839. var uv = [];
  10840. uv.push( new THREE.UV( u1, v1 ) );
  10841. uv.push( new THREE.UV( u2, v2 ) );
  10842. uv.push( new THREE.UV( u3, v3 ) );
  10843. where.push( uv );
  10844. };
  10845. Model.prototype = new THREE.Geometry();
  10846. Model.prototype.constructor = Model;
  10847. callback( new Model() );
  10848. };
  10849. /**
  10850. * @author alteredq / http://alteredqualia.com/
  10851. */
  10852. THREE.ImmediateRenderObject = function ( ) {
  10853. THREE.Object3D.call( this );
  10854. this.render = function( renderCallback ) {
  10855. };
  10856. };
  10857. THREE.ImmediateRenderObject.prototype = new THREE.Object3D();
  10858. THREE.ImmediateRenderObject.prototype.constructor = THREE.ImmediateRenderObject;
  10859. /**
  10860. * @author mikael emtinger / http://gomo.se/
  10861. * @author alteredq / http://alteredqualia.com/
  10862. */
  10863. THREE.LensFlare = function ( texture, size, distance, blending, color ) {
  10864. THREE.Object3D.call( this );
  10865. this.lensFlares = [];
  10866. this.positionScreen = new THREE.Vector3();
  10867. this.customUpdateCallback = undefined;
  10868. if( texture !== undefined ) {
  10869. this.add( texture, size, distance, blending, color );
  10870. }
  10871. };
  10872. THREE.LensFlare.prototype = new THREE.Object3D();
  10873. THREE.LensFlare.prototype.constructor = THREE.LensFlare;
  10874. THREE.LensFlare.prototype.supr = THREE.Object3D.prototype;
  10875. /*
  10876. * Add: adds another flare
  10877. */
  10878. THREE.LensFlare.prototype.add = function ( texture, size, distance, blending, color, opacity ) {
  10879. if( size === undefined ) size = -1;
  10880. if( distance === undefined ) distance = 0;
  10881. if( opacity === undefined ) opacity = 1;
  10882. if( color === undefined ) color = new THREE.Color( 0xffffff );
  10883. if( blending === undefined ) blending = THREE.NormalBlending;
  10884. distance = Math.min( distance, Math.max( 0, distance ) );
  10885. this.lensFlares.push( { texture: texture, // THREE.Texture
  10886. size: size, // size in pixels (-1 = use texture.width)
  10887. distance: distance, // distance (0-1) from light source (0=at light source)
  10888. x: 0, y: 0, z: 0, // screen position (-1 => 1) z = 0 is ontop z = 1 is back
  10889. scale: 1, // scale
  10890. rotation: 1, // rotation
  10891. opacity: opacity, // opacity
  10892. color: color, // color
  10893. blending: blending } ); // blending
  10894. };
  10895. /*
  10896. * Update lens flares update positions on all flares based on the screen position
  10897. * Set myLensFlare.customUpdateCallback to alter the flares in your project specific way.
  10898. */
  10899. THREE.LensFlare.prototype.updateLensFlares = function () {
  10900. var f, fl = this.lensFlares.length;
  10901. var flare;
  10902. var vecX = -this.positionScreen.x * 2;
  10903. var vecY = -this.positionScreen.y * 2;
  10904. for( f = 0; f < fl; f ++ ) {
  10905. flare = this.lensFlares[ f ];
  10906. flare.x = this.positionScreen.x + vecX * flare.distance;
  10907. flare.y = this.positionScreen.y + vecY * flare.distance;
  10908. flare.wantedRotation = flare.x * Math.PI * 0.25;
  10909. flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
  10910. }
  10911. };
  10912. /**
  10913. * @author alteredq / http://alteredqualia.com/
  10914. */
  10915. THREE.MorphBlendMesh = function( geometry, material ) {
  10916. THREE.Mesh.call( this, geometry, material );
  10917. this.animationsMap = {};
  10918. this.animationsList = [];
  10919. // prepare default animation
  10920. // (all frames played together in 1 second)
  10921. var numFrames = this.geometry.morphTargets.length;
  10922. var name = "__default";
  10923. var startFrame = 0;
  10924. var endFrame = numFrames - 1;
  10925. var fps = numFrames / 1;
  10926. this.createAnimation( name, startFrame, endFrame, fps );
  10927. this.setAnimationWeight( name, 1 );
  10928. };
  10929. THREE.MorphBlendMesh.prototype = new THREE.Mesh();
  10930. THREE.MorphBlendMesh.prototype.constructor = THREE.MorphBlendMesh;
  10931. THREE.MorphBlendMesh.prototype.createAnimation = function ( name, start, end, fps ) {
  10932. var animation = {
  10933. startFrame: start,
  10934. endFrame: end,
  10935. length: end - start + 1,
  10936. fps: fps,
  10937. duration: ( end - start ) / fps,
  10938. lastFrame: 0,
  10939. currentFrame: 0,
  10940. active: false,
  10941. time: 0,
  10942. direction: 1,
  10943. weight: 1,
  10944. directionBackwards: false,
  10945. mirroredLoop: false
  10946. };
  10947. this.animationsMap[ name ] = animation;
  10948. this.animationsList.push( animation );
  10949. };
  10950. THREE.MorphBlendMesh.prototype.autoCreateAnimations = function ( fps ) {
  10951. var pattern = /([a-z]+)(\d+)/;
  10952. var firstAnimation, frameRanges = {};
  10953. var geometry = this.geometry;
  10954. for ( var i = 0, il = geometry.morphTargets.length; i < il; i ++ ) {
  10955. var morph = geometry.morphTargets[ i ];
  10956. var chunks = morph.name.match( pattern );
  10957. if ( chunks && chunks.length > 1 ) {
  10958. var name = chunks[ 1 ];
  10959. var num = chunks[ 2 ];
  10960. if ( ! frameRanges[ name ] ) frameRanges[ name ] = { start: Infinity, end: -Infinity };
  10961. var range = frameRanges[ name ];
  10962. if ( i < range.start ) range.start = i;
  10963. if ( i > range.end ) range.end = i;
  10964. if ( ! firstAnimation ) firstAnimation = name;
  10965. }
  10966. }
  10967. for ( var name in frameRanges ) {
  10968. var range = frameRanges[ name ];
  10969. this.createAnimation( name, range.start, range.end, fps );
  10970. }
  10971. this.firstAnimation = firstAnimation;
  10972. };
  10973. THREE.MorphBlendMesh.prototype.setAnimationDirectionForward = function ( name ) {
  10974. var animation = this.animationsMap[ name ];
  10975. if ( animation ) {
  10976. animation.direction = 1;
  10977. animation.directionBackwards = false;
  10978. }
  10979. };
  10980. THREE.MorphBlendMesh.prototype.setAnimationDirectionBackward = function ( name ) {
  10981. var animation = this.animationsMap[ name ];
  10982. if ( animation ) {
  10983. animation.direction = -1;
  10984. animation.directionBackwards = true;
  10985. }
  10986. };
  10987. THREE.MorphBlendMesh.prototype.setAnimationFPS = function ( name, fps ) {
  10988. var animation = this.animationsMap[ name ];
  10989. if ( animation ) {
  10990. animation.fps = fps;
  10991. animation.duration = ( animation.end - animation.start ) / animation.fps;
  10992. }
  10993. };
  10994. THREE.MorphBlendMesh.prototype.setAnimationDuration = function ( name, duration ) {
  10995. var animation = this.animationsMap[ name ];
  10996. if ( animation ) {
  10997. animation.duration = duration;
  10998. animation.fps = ( animation.end - animation.start ) / animation.duration;
  10999. }
  11000. };
  11001. THREE.MorphBlendMesh.prototype.setAnimationWeight = function ( name, weight ) {
  11002. var animation = this.animationsMap[ name ];
  11003. if ( animation ) {
  11004. animation.weight = weight;
  11005. }
  11006. };
  11007. THREE.MorphBlendMesh.prototype.setAnimationTime = function ( name, time ) {
  11008. var animation = this.animationsMap[ name ];
  11009. if ( animation ) {
  11010. animation.time = time;
  11011. }
  11012. };
  11013. THREE.MorphBlendMesh.prototype.getAnimationTime = function ( name ) {
  11014. var time = 0;
  11015. var animation = this.animationsMap[ name ];
  11016. if ( animation ) {
  11017. time = animation.time;
  11018. }
  11019. return time;
  11020. };
  11021. THREE.MorphBlendMesh.prototype.getAnimationDuration = function ( name ) {
  11022. var duration = -1;
  11023. var animation = this.animationsMap[ name ];
  11024. if ( animation ) {
  11025. duration = animation.duration;
  11026. }
  11027. return duration;
  11028. };
  11029. THREE.MorphBlendMesh.prototype.playAnimation = function ( name ) {
  11030. var animation = this.animationsMap[ name ];
  11031. if ( animation ) {
  11032. animation.time = 0;
  11033. animation.active = true;
  11034. } else {
  11035. console.warn( "animation[" + name + "] undefined" );
  11036. }
  11037. };
  11038. THREE.MorphBlendMesh.prototype.stopAnimation = function ( name ) {
  11039. var animation = this.animationsMap[ name ];
  11040. if ( animation ) {
  11041. animation.active = false;
  11042. }
  11043. };
  11044. THREE.MorphBlendMesh.prototype.update = function ( delta ) {
  11045. for ( var i = 0, il = this.animationsList.length; i < il; i ++ ) {
  11046. var animation = this.animationsList[ i ];
  11047. if ( ! animation.active ) continue;
  11048. var frameTime = animation.duration / animation.length;
  11049. animation.time += animation.direction * delta;
  11050. if ( animation.mirroredLoop ) {
  11051. if ( animation.time > animation.duration || animation.time < 0 ) {
  11052. animation.direction *= -1;
  11053. if ( animation.time > animation.duration ) {
  11054. animation.time = animation.duration;
  11055. animation.directionBackwards = true;
  11056. }
  11057. if ( animation.time < 0 ) {
  11058. animation.time = 0;
  11059. animation.directionBackwards = false;
  11060. }
  11061. }
  11062. } else {
  11063. animation.time = animation.time % animation.duration;
  11064. if ( animation.time < 0 ) animation.time += animation.duration;
  11065. }
  11066. var keyframe = animation.startFrame + THREE.Math.clamp( Math.floor( animation.time / frameTime ), 0, animation.length - 1 );
  11067. var weight = animation.weight;
  11068. if ( keyframe !== animation.currentFrame ) {
  11069. this.morphTargetInfluences[ animation.lastFrame ] = 0;
  11070. this.morphTargetInfluences[ animation.currentFrame ] = 1 * weight;
  11071. this.morphTargetInfluences[ keyframe ] = 0;
  11072. animation.lastFrame = animation.currentFrame;
  11073. animation.currentFrame = keyframe;
  11074. }
  11075. var mix = ( animation.time % frameTime ) / frameTime;
  11076. if ( animation.directionBackwards ) mix = 1 - mix;
  11077. this.morphTargetInfluences[ animation.currentFrame ] = mix * weight;
  11078. this.morphTargetInfluences[ animation.lastFrame ] = ( 1 - mix ) * weight;
  11079. }
  11080. };
  11081. /**
  11082. * @author mikael emtinger / http://gomo.se/
  11083. * @author alteredq / http://alteredqualia.com/
  11084. */
  11085. THREE.LensFlarePlugin = function ( ) {
  11086. var _gl, _renderer, _lensFlare = {};
  11087. this.init = function ( renderer ) {
  11088. _gl = renderer.context;
  11089. _renderer = renderer;
  11090. _lensFlare.vertices = new Float32Array( 8 + 8 );
  11091. _lensFlare.faces = new Uint16Array( 6 );
  11092. var i = 0;
  11093. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = -1; // vertex
  11094. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 0; // uv... etc.
  11095. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = -1;
  11096. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 0;
  11097. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  11098. _lensFlare.vertices[ i++ ] = 1; _lensFlare.vertices[ i++ ] = 1;
  11099. _lensFlare.vertices[ i++ ] = -1; _lensFlare.vertices[ i++ ] = 1;
  11100. _lensFlare.vertices[ i++ ] = 0; _lensFlare.vertices[ i++ ] = 1;
  11101. i = 0;
  11102. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 1; _lensFlare.faces[ i++ ] = 2;
  11103. _lensFlare.faces[ i++ ] = 0; _lensFlare.faces[ i++ ] = 2; _lensFlare.faces[ i++ ] = 3;
  11104. // buffers
  11105. _lensFlare.vertexBuffer = _gl.createBuffer();
  11106. _lensFlare.elementBuffer = _gl.createBuffer();
  11107. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  11108. _gl.bufferData( _gl.ARRAY_BUFFER, _lensFlare.vertices, _gl.STATIC_DRAW );
  11109. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  11110. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.faces, _gl.STATIC_DRAW );
  11111. // textures
  11112. _lensFlare.tempTexture = _gl.createTexture();
  11113. _lensFlare.occlusionTexture = _gl.createTexture();
  11114. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  11115. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, 16, 16, 0, _gl.RGB, _gl.UNSIGNED_BYTE, null );
  11116. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  11117. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  11118. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  11119. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  11120. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  11121. _gl.texImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, 16, 16, 0, _gl.RGBA, _gl.UNSIGNED_BYTE, null );
  11122. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_S, _gl.CLAMP_TO_EDGE );
  11123. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_WRAP_T, _gl.CLAMP_TO_EDGE );
  11124. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MAG_FILTER, _gl.NEAREST );
  11125. _gl.texParameteri( _gl.TEXTURE_2D, _gl.TEXTURE_MIN_FILTER, _gl.NEAREST );
  11126. if ( _gl.getParameter( _gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS ) <= 0 ) {
  11127. _lensFlare.hasVertexTexture = false;
  11128. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlare" ] );
  11129. } else {
  11130. _lensFlare.hasVertexTexture = true;
  11131. _lensFlare.program = createProgram( THREE.ShaderFlares[ "lensFlareVertexTexture" ] );
  11132. }
  11133. _lensFlare.attributes = {};
  11134. _lensFlare.uniforms = {};
  11135. _lensFlare.attributes.vertex = _gl.getAttribLocation ( _lensFlare.program, "position" );
  11136. _lensFlare.attributes.uv = _gl.getAttribLocation ( _lensFlare.program, "uv" );
  11137. _lensFlare.uniforms.renderType = _gl.getUniformLocation( _lensFlare.program, "renderType" );
  11138. _lensFlare.uniforms.map = _gl.getUniformLocation( _lensFlare.program, "map" );
  11139. _lensFlare.uniforms.occlusionMap = _gl.getUniformLocation( _lensFlare.program, "occlusionMap" );
  11140. _lensFlare.uniforms.opacity = _gl.getUniformLocation( _lensFlare.program, "opacity" );
  11141. _lensFlare.uniforms.color = _gl.getUniformLocation( _lensFlare.program, "color" );
  11142. _lensFlare.uniforms.scale = _gl.getUniformLocation( _lensFlare.program, "scale" );
  11143. _lensFlare.uniforms.rotation = _gl.getUniformLocation( _lensFlare.program, "rotation" );
  11144. _lensFlare.uniforms.screenPosition = _gl.getUniformLocation( _lensFlare.program, "screenPosition" );
  11145. _lensFlare.attributesEnabled = false;
  11146. };
  11147. /*
  11148. * Render lens flares
  11149. * Method: renders 16x16 0xff00ff-colored points scattered over the light source area,
  11150. * reads these back and calculates occlusion.
  11151. * Then _lensFlare.update_lensFlares() is called to re-position and
  11152. * update transparency of flares. Then they are rendered.
  11153. *
  11154. */
  11155. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  11156. var flares = scene.__webglFlares,
  11157. nFlares = flares.length;
  11158. if ( ! nFlares ) return;
  11159. var tempPosition = new THREE.Vector3();
  11160. var invAspect = viewportHeight / viewportWidth,
  11161. halfViewportWidth = viewportWidth * 0.5,
  11162. halfViewportHeight = viewportHeight * 0.5;
  11163. var size = 16 / viewportHeight,
  11164. scale = new THREE.Vector2( size * invAspect, size );
  11165. var screenPosition = new THREE.Vector3( 1, 1, 0 ),
  11166. screenPositionPixels = new THREE.Vector2( 1, 1 );
  11167. var uniforms = _lensFlare.uniforms,
  11168. attributes = _lensFlare.attributes;
  11169. // set _lensFlare program and reset blending
  11170. _gl.useProgram( _lensFlare.program );
  11171. if ( ! _lensFlare.attributesEnabled ) {
  11172. _gl.enableVertexAttribArray( _lensFlare.attributes.vertex );
  11173. _gl.enableVertexAttribArray( _lensFlare.attributes.uv );
  11174. _lensFlare.attributesEnabled = true;
  11175. }
  11176. // loop through all lens flares to update their occlusion and positions
  11177. // setup gl and common used attribs/unforms
  11178. _gl.uniform1i( uniforms.occlusionMap, 0 );
  11179. _gl.uniform1i( uniforms.map, 1 );
  11180. _gl.bindBuffer( _gl.ARRAY_BUFFER, _lensFlare.vertexBuffer );
  11181. _gl.vertexAttribPointer( attributes.vertex, 2, _gl.FLOAT, false, 2 * 8, 0 );
  11182. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  11183. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _lensFlare.elementBuffer );
  11184. _gl.disable( _gl.CULL_FACE );
  11185. _gl.depthMask( false );
  11186. var i, j, jl, flare, sprite;
  11187. for ( i = 0; i < nFlares; i ++ ) {
  11188. size = 16 / viewportHeight;
  11189. scale.set( size * invAspect, size );
  11190. // calc object screen position
  11191. flare = flares[ i ];
  11192. tempPosition.set( flare.matrixWorld.elements[12], flare.matrixWorld.elements[13], flare.matrixWorld.elements[14] );
  11193. camera.matrixWorldInverse.multiplyVector3( tempPosition );
  11194. camera.projectionMatrix.multiplyVector3( tempPosition );
  11195. // setup arrays for gl programs
  11196. screenPosition.copy( tempPosition )
  11197. screenPositionPixels.x = screenPosition.x * halfViewportWidth + halfViewportWidth;
  11198. screenPositionPixels.y = screenPosition.y * halfViewportHeight + halfViewportHeight;
  11199. // screen cull
  11200. if ( _lensFlare.hasVertexTexture || (
  11201. screenPositionPixels.x > 0 &&
  11202. screenPositionPixels.x < viewportWidth &&
  11203. screenPositionPixels.y > 0 &&
  11204. screenPositionPixels.y < viewportHeight ) ) {
  11205. // save current RGB to temp texture
  11206. _gl.activeTexture( _gl.TEXTURE1 );
  11207. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  11208. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGB, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  11209. // render pink quad
  11210. _gl.uniform1i( uniforms.renderType, 0 );
  11211. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  11212. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  11213. _gl.disable( _gl.BLEND );
  11214. _gl.enable( _gl.DEPTH_TEST );
  11215. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  11216. // copy result to occlusionMap
  11217. _gl.activeTexture( _gl.TEXTURE0 );
  11218. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.occlusionTexture );
  11219. _gl.copyTexImage2D( _gl.TEXTURE_2D, 0, _gl.RGBA, screenPositionPixels.x - 8, screenPositionPixels.y - 8, 16, 16, 0 );
  11220. // restore graphics
  11221. _gl.uniform1i( uniforms.renderType, 1 );
  11222. _gl.disable( _gl.DEPTH_TEST );
  11223. _gl.activeTexture( _gl.TEXTURE1 );
  11224. _gl.bindTexture( _gl.TEXTURE_2D, _lensFlare.tempTexture );
  11225. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  11226. // update object positions
  11227. flare.positionScreen.copy( screenPosition )
  11228. if ( flare.customUpdateCallback ) {
  11229. flare.customUpdateCallback( flare );
  11230. } else {
  11231. flare.updateLensFlares();
  11232. }
  11233. // render flares
  11234. _gl.uniform1i( uniforms.renderType, 2 );
  11235. _gl.enable( _gl.BLEND );
  11236. for ( j = 0, jl = flare.lensFlares.length; j < jl; j ++ ) {
  11237. sprite = flare.lensFlares[ j ];
  11238. if ( sprite.opacity > 0.001 && sprite.scale > 0.001 ) {
  11239. screenPosition.x = sprite.x;
  11240. screenPosition.y = sprite.y;
  11241. screenPosition.z = sprite.z;
  11242. size = sprite.size * sprite.scale / viewportHeight;
  11243. scale.x = size * invAspect;
  11244. scale.y = size;
  11245. _gl.uniform3f( uniforms.screenPosition, screenPosition.x, screenPosition.y, screenPosition.z );
  11246. _gl.uniform2f( uniforms.scale, scale.x, scale.y );
  11247. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  11248. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  11249. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  11250. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  11251. _renderer.setTexture( sprite.texture, 1 );
  11252. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  11253. }
  11254. }
  11255. }
  11256. }
  11257. // restore gl
  11258. _gl.enable( _gl.CULL_FACE );
  11259. _gl.enable( _gl.DEPTH_TEST );
  11260. _gl.depthMask( true );
  11261. };
  11262. function createProgram ( shader ) {
  11263. var program = _gl.createProgram();
  11264. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  11265. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  11266. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  11267. _gl.shaderSource( vertexShader, shader.vertexShader );
  11268. _gl.compileShader( fragmentShader );
  11269. _gl.compileShader( vertexShader );
  11270. _gl.attachShader( program, fragmentShader );
  11271. _gl.attachShader( program, vertexShader );
  11272. _gl.linkProgram( program );
  11273. return program;
  11274. };
  11275. };/**
  11276. * @author alteredq / http://alteredqualia.com/
  11277. */
  11278. THREE.ShadowMapPlugin = function ( ) {
  11279. var _gl,
  11280. _renderer,
  11281. _depthMaterial, _depthMaterialMorph,
  11282. _frustum = new THREE.Frustum(),
  11283. _projScreenMatrix = new THREE.Matrix4(),
  11284. _min = new THREE.Vector3(),
  11285. _max = new THREE.Vector3();
  11286. this.init = function ( renderer ) {
  11287. _gl = renderer.context;
  11288. _renderer = renderer;
  11289. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  11290. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  11291. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  11292. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  11293. _depthMaterial._shadowPass = true;
  11294. _depthMaterialMorph._shadowPass = true;
  11295. };
  11296. this.render = function ( scene, camera ) {
  11297. if ( ! ( _renderer.shadowMapEnabled && _renderer.shadowMapAutoUpdate ) ) return;
  11298. this.update( scene, camera );
  11299. };
  11300. this.update = function ( scene, camera ) {
  11301. var i, il, j, jl, n,
  11302. shadowMap, shadowMatrix, shadowCamera,
  11303. program, buffer, material,
  11304. webglObject, object, light,
  11305. renderList,
  11306. lights = [],
  11307. k = 0,
  11308. fog = null;
  11309. // set GL state for depth map
  11310. _gl.clearColor( 1, 1, 1, 1 );
  11311. _gl.disable( _gl.BLEND );
  11312. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.FRONT );
  11313. _renderer.setDepthTest( true );
  11314. // preprocess lights
  11315. // - skip lights that are not casting shadows
  11316. // - create virtual lights for cascaded shadow maps
  11317. for ( i = 0, il = scene.__lights.length; i < il; i ++ ) {
  11318. light = scene.__lights[ i ];
  11319. if ( ! light.castShadow ) continue;
  11320. if ( ( light instanceof THREE.DirectionalLight ) && light.shadowCascade ) {
  11321. for ( n = 0; n < light.shadowCascadeCount; n ++ ) {
  11322. var virtualLight;
  11323. if ( ! light.shadowCascadeArray[ n ] ) {
  11324. virtualLight = createVirtualLight( light, n );
  11325. virtualLight.originalCamera = camera;
  11326. var gyro = new THREE.Gyroscope();
  11327. gyro.position = light.shadowCascadeOffset;
  11328. gyro.add( virtualLight );
  11329. gyro.add( virtualLight.target );
  11330. camera.add( gyro );
  11331. light.shadowCascadeArray[ n ] = virtualLight;
  11332. console.log( "Created virtualLight", virtualLight );
  11333. } else {
  11334. virtualLight = light.shadowCascadeArray[ n ];
  11335. }
  11336. updateVirtualLight( light, n );
  11337. lights[ k ] = virtualLight;
  11338. k ++;
  11339. }
  11340. } else {
  11341. lights[ k ] = light;
  11342. k ++;
  11343. }
  11344. }
  11345. // render depth map
  11346. for ( i = 0, il = lights.length; i < il; i ++ ) {
  11347. light = lights[ i ];
  11348. if ( ! light.shadowMap ) {
  11349. var pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat };
  11350. light.shadowMap = new THREE.WebGLRenderTarget( light.shadowMapWidth, light.shadowMapHeight, pars );
  11351. light.shadowMapSize = new THREE.Vector2( light.shadowMapWidth, light.shadowMapHeight );
  11352. light.shadowMatrix = new THREE.Matrix4();
  11353. }
  11354. if ( ! light.shadowCamera ) {
  11355. if ( light instanceof THREE.SpotLight ) {
  11356. light.shadowCamera = new THREE.PerspectiveCamera( light.shadowCameraFov, light.shadowMapWidth / light.shadowMapHeight, light.shadowCameraNear, light.shadowCameraFar );
  11357. } else if ( light instanceof THREE.DirectionalLight ) {
  11358. light.shadowCamera = new THREE.OrthographicCamera( light.shadowCameraLeft, light.shadowCameraRight, light.shadowCameraTop, light.shadowCameraBottom, light.shadowCameraNear, light.shadowCameraFar );
  11359. } else {
  11360. console.error( "Unsupported light type for shadow" );
  11361. continue;
  11362. }
  11363. scene.add( light.shadowCamera );
  11364. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  11365. }
  11366. if ( light.shadowCameraVisible && ! light.cameraHelper ) {
  11367. light.cameraHelper = new THREE.CameraHelper( light.shadowCamera );
  11368. light.shadowCamera.add( light.cameraHelper );
  11369. }
  11370. if ( light.isVirtual && virtualLight.originalCamera == camera ) {
  11371. updateShadowCamera( camera, light );
  11372. }
  11373. shadowMap = light.shadowMap;
  11374. shadowMatrix = light.shadowMatrix;
  11375. shadowCamera = light.shadowCamera;
  11376. shadowCamera.position.copy( light.matrixWorld.getPosition() );
  11377. shadowCamera.lookAt( light.target.matrixWorld.getPosition() );
  11378. shadowCamera.updateMatrixWorld();
  11379. shadowCamera.matrixWorldInverse.getInverse( shadowCamera.matrixWorld );
  11380. if ( light.cameraHelper ) light.cameraHelper.lines.visible = light.shadowCameraVisible;
  11381. if ( light.shadowCameraVisible ) light.cameraHelper.update();
  11382. // compute shadow matrix
  11383. shadowMatrix.set( 0.5, 0.0, 0.0, 0.5,
  11384. 0.0, 0.5, 0.0, 0.5,
  11385. 0.0, 0.0, 0.5, 0.5,
  11386. 0.0, 0.0, 0.0, 1.0 );
  11387. shadowMatrix.multiplySelf( shadowCamera.projectionMatrix );
  11388. shadowMatrix.multiplySelf( shadowCamera.matrixWorldInverse );
  11389. // update camera matrices and frustum
  11390. if ( ! shadowCamera._viewMatrixArray ) shadowCamera._viewMatrixArray = new Float32Array( 16 );
  11391. if ( ! shadowCamera._projectionMatrixArray ) shadowCamera._projectionMatrixArray = new Float32Array( 16 );
  11392. shadowCamera.matrixWorldInverse.flattenToArray( shadowCamera._viewMatrixArray );
  11393. shadowCamera.projectionMatrix.flattenToArray( shadowCamera._projectionMatrixArray );
  11394. _projScreenMatrix.multiply( shadowCamera.projectionMatrix, shadowCamera.matrixWorldInverse );
  11395. _frustum.setFromMatrix( _projScreenMatrix );
  11396. // render shadow map
  11397. _renderer.setRenderTarget( shadowMap );
  11398. _renderer.clear();
  11399. // set object matrices & frustum culling
  11400. renderList = scene.__webglObjects;
  11401. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11402. webglObject = renderList[ j ];
  11403. object = webglObject.object;
  11404. webglObject.render = false;
  11405. if ( object.visible && object.castShadow ) {
  11406. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11407. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  11408. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  11409. webglObject.render = true;
  11410. }
  11411. }
  11412. }
  11413. // render regular objects
  11414. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11415. webglObject = renderList[ j ];
  11416. if ( webglObject.render ) {
  11417. object = webglObject.object;
  11418. buffer = webglObject.buffer;
  11419. _renderer.setObjectFaces( object );
  11420. if ( object.customDepthMaterial ) {
  11421. material = object.customDepthMaterial;
  11422. } else if ( object.geometry.morphTargets.length ) {
  11423. material = _depthMaterialMorph;
  11424. } else {
  11425. material = _depthMaterial;
  11426. }
  11427. if ( buffer instanceof THREE.BufferGeometry ) {
  11428. _renderer.renderBufferDirect( shadowCamera, scene.__lights, fog, material, buffer, object );
  11429. } else {
  11430. _renderer.renderBuffer( shadowCamera, scene.__lights, fog, material, buffer, object );
  11431. }
  11432. }
  11433. }
  11434. // set matrices and render immediate objects
  11435. renderList = scene.__webglObjectsImmediate;
  11436. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11437. webglObject = renderList[ j ];
  11438. object = webglObject.object;
  11439. if ( object.visible && object.castShadow ) {
  11440. if( object.matrixAutoUpdate ) {
  11441. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  11442. }
  11443. object._modelViewMatrix.multiply( shadowCamera.matrixWorldInverse, object.matrixWorld);
  11444. _renderer.renderImmediateObject( shadowCamera, scene.__lights, fog, _depthMaterial, object );
  11445. }
  11446. }
  11447. }
  11448. // restore GL state
  11449. var clearColor = _renderer.getClearColor(),
  11450. clearAlpha = _renderer.getClearAlpha();
  11451. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  11452. _gl.enable( _gl.BLEND );
  11453. if ( _renderer.shadowMapCullFrontFaces ) _gl.cullFace( _gl.BACK );
  11454. };
  11455. function createVirtualLight( light, cascade ) {
  11456. var virtualLight = new THREE.DirectionalLight();
  11457. virtualLight.isVirtual = true;
  11458. virtualLight.onlyShadow = true;
  11459. virtualLight.castShadow = true;
  11460. virtualLight.shadowCameraNear = light.shadowCameraNear;
  11461. virtualLight.shadowCameraFar = light.shadowCameraFar;
  11462. virtualLight.shadowCameraLeft = light.shadowCameraLeft;
  11463. virtualLight.shadowCameraRight = light.shadowCameraRight;
  11464. virtualLight.shadowCameraBottom = light.shadowCameraBottom;
  11465. virtualLight.shadowCameraTop = light.shadowCameraTop;
  11466. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  11467. virtualLight.shadowDarkness = light.shadowDarkness;
  11468. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  11469. virtualLight.shadowMapWidth = light.shadowCascadeWidth[ cascade ];
  11470. virtualLight.shadowMapHeight = light.shadowCascadeHeight[ cascade ];
  11471. virtualLight.pointsWorld = [];
  11472. virtualLight.pointsFrustum = [];
  11473. var pointsWorld = virtualLight.pointsWorld,
  11474. pointsFrustum = virtualLight.pointsFrustum;
  11475. for ( var i = 0; i < 8; i ++ ) {
  11476. pointsWorld[ i ] = new THREE.Vector3();
  11477. pointsFrustum[ i ] = new THREE.Vector3();
  11478. }
  11479. var nearZ = light.shadowCascadeNearZ[ cascade ];
  11480. var farZ = light.shadowCascadeFarZ[ cascade ];
  11481. pointsFrustum[ 0 ].set( -1, -1, nearZ );
  11482. pointsFrustum[ 1 ].set( 1, -1, nearZ );
  11483. pointsFrustum[ 2 ].set( -1, 1, nearZ );
  11484. pointsFrustum[ 3 ].set( 1, 1, nearZ );
  11485. pointsFrustum[ 4 ].set( -1, -1, farZ );
  11486. pointsFrustum[ 5 ].set( 1, -1, farZ );
  11487. pointsFrustum[ 6 ].set( -1, 1, farZ );
  11488. pointsFrustum[ 7 ].set( 1, 1, farZ );
  11489. return virtualLight;
  11490. }
  11491. // Synchronize virtual light with the original light
  11492. function updateVirtualLight( light, cascade ) {
  11493. var virtualLight = light.shadowCascadeArray[ cascade ];
  11494. virtualLight.position.copy( light.position );
  11495. virtualLight.target.position.copy( light.target.position );
  11496. virtualLight.lookAt( virtualLight.target );
  11497. virtualLight.shadowCameraVisible = light.shadowCameraVisible;
  11498. virtualLight.shadowDarkness = light.shadowDarkness;
  11499. virtualLight.shadowBias = light.shadowCascadeBias[ cascade ];
  11500. var nearZ = light.shadowCascadeNearZ[ cascade ];
  11501. var farZ = light.shadowCascadeFarZ[ cascade ];
  11502. var pointsFrustum = virtualLight.pointsFrustum;
  11503. pointsFrustum[ 0 ].z = nearZ;
  11504. pointsFrustum[ 1 ].z = nearZ;
  11505. pointsFrustum[ 2 ].z = nearZ;
  11506. pointsFrustum[ 3 ].z = nearZ;
  11507. pointsFrustum[ 4 ].z = farZ;
  11508. pointsFrustum[ 5 ].z = farZ;
  11509. pointsFrustum[ 6 ].z = farZ;
  11510. pointsFrustum[ 7 ].z = farZ;
  11511. }
  11512. // Fit shadow camera's ortho frustum to camera frustum
  11513. function updateShadowCamera( camera, light ) {
  11514. var shadowCamera = light.shadowCamera,
  11515. pointsFrustum = light.pointsFrustum,
  11516. pointsWorld = light.pointsWorld;
  11517. _min.set( Infinity, Infinity, Infinity );
  11518. _max.set( -Infinity, -Infinity, -Infinity );
  11519. for ( var i = 0; i < 8; i ++ ) {
  11520. var p = pointsWorld[ i ];
  11521. p.copy( pointsFrustum[ i ] );
  11522. THREE.ShadowMapPlugin.__projector.unprojectVector( p, camera );
  11523. shadowCamera.matrixWorldInverse.multiplyVector3( p );
  11524. if ( p.x < _min.x ) _min.x = p.x;
  11525. if ( p.x > _max.x ) _max.x = p.x;
  11526. if ( p.y < _min.y ) _min.y = p.y;
  11527. if ( p.y > _max.y ) _max.y = p.y;
  11528. if ( p.z < _min.z ) _min.z = p.z;
  11529. if ( p.z > _max.z ) _max.z = p.z;
  11530. }
  11531. shadowCamera.left = _min.x;
  11532. shadowCamera.right = _max.x;
  11533. shadowCamera.top = _max.y;
  11534. shadowCamera.bottom = _min.y;
  11535. // can't really fit near/far
  11536. //shadowCamera.near = _min.z;
  11537. //shadowCamera.far = _max.z;
  11538. shadowCamera.updateProjectionMatrix();
  11539. }
  11540. };
  11541. THREE.ShadowMapPlugin.__projector = new THREE.Projector();
  11542. /**
  11543. * @author mikael emtinger / http://gomo.se/
  11544. * @author alteredq / http://alteredqualia.com/
  11545. */
  11546. THREE.SpritePlugin = function ( ) {
  11547. var _gl, _renderer, _sprite = {};
  11548. this.init = function ( renderer ) {
  11549. _gl = renderer.context;
  11550. _renderer = renderer;
  11551. _sprite.vertices = new Float32Array( 8 + 8 );
  11552. _sprite.faces = new Uint16Array( 6 );
  11553. var i = 0;
  11554. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = -1; // vertex 0
  11555. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 1; // uv 0
  11556. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = -1; // vertex 1
  11557. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // uv 1
  11558. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 1; // vertex 2
  11559. _sprite.vertices[ i++ ] = 1; _sprite.vertices[ i++ ] = 0; // uv 2
  11560. _sprite.vertices[ i++ ] = -1; _sprite.vertices[ i++ ] = 1; // vertex 3
  11561. _sprite.vertices[ i++ ] = 0; _sprite.vertices[ i++ ] = 0; // uv 3
  11562. i = 0;
  11563. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 1; _sprite.faces[ i++ ] = 2;
  11564. _sprite.faces[ i++ ] = 0; _sprite.faces[ i++ ] = 2; _sprite.faces[ i++ ] = 3;
  11565. _sprite.vertexBuffer = _gl.createBuffer();
  11566. _sprite.elementBuffer = _gl.createBuffer();
  11567. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  11568. _gl.bufferData( _gl.ARRAY_BUFFER, _sprite.vertices, _gl.STATIC_DRAW );
  11569. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  11570. _gl.bufferData( _gl.ELEMENT_ARRAY_BUFFER, _sprite.faces, _gl.STATIC_DRAW );
  11571. _sprite.program = createProgram( THREE.ShaderSprite[ "sprite" ] );
  11572. _sprite.attributes = {};
  11573. _sprite.uniforms = {};
  11574. _sprite.attributes.position = _gl.getAttribLocation ( _sprite.program, "position" );
  11575. _sprite.attributes.uv = _gl.getAttribLocation ( _sprite.program, "uv" );
  11576. _sprite.uniforms.uvOffset = _gl.getUniformLocation( _sprite.program, "uvOffset" );
  11577. _sprite.uniforms.uvScale = _gl.getUniformLocation( _sprite.program, "uvScale" );
  11578. _sprite.uniforms.rotation = _gl.getUniformLocation( _sprite.program, "rotation" );
  11579. _sprite.uniforms.scale = _gl.getUniformLocation( _sprite.program, "scale" );
  11580. _sprite.uniforms.alignment = _gl.getUniformLocation( _sprite.program, "alignment" );
  11581. _sprite.uniforms.color = _gl.getUniformLocation( _sprite.program, "color" );
  11582. _sprite.uniforms.map = _gl.getUniformLocation( _sprite.program, "map" );
  11583. _sprite.uniforms.opacity = _gl.getUniformLocation( _sprite.program, "opacity" );
  11584. _sprite.uniforms.useScreenCoordinates = _gl.getUniformLocation( _sprite.program, "useScreenCoordinates" );
  11585. _sprite.uniforms.affectedByDistance = _gl.getUniformLocation( _sprite.program, "affectedByDistance" );
  11586. _sprite.uniforms.screenPosition = _gl.getUniformLocation( _sprite.program, "screenPosition" );
  11587. _sprite.uniforms.modelViewMatrix = _gl.getUniformLocation( _sprite.program, "modelViewMatrix" );
  11588. _sprite.uniforms.projectionMatrix = _gl.getUniformLocation( _sprite.program, "projectionMatrix" );
  11589. _sprite.attributesEnabled = false;
  11590. };
  11591. this.render = function ( scene, camera, viewportWidth, viewportHeight ) {
  11592. var sprites = scene.__webglSprites,
  11593. nSprites = sprites.length;
  11594. if ( ! nSprites ) return;
  11595. var attributes = _sprite.attributes,
  11596. uniforms = _sprite.uniforms;
  11597. var invAspect = viewportHeight / viewportWidth;
  11598. var halfViewportWidth = viewportWidth * 0.5,
  11599. halfViewportHeight = viewportHeight * 0.5;
  11600. var mergeWith3D = true;
  11601. // setup gl
  11602. _gl.useProgram( _sprite.program );
  11603. if ( ! _sprite.attributesEnabled ) {
  11604. _gl.enableVertexAttribArray( attributes.position );
  11605. _gl.enableVertexAttribArray( attributes.uv );
  11606. _sprite.attributesEnabled = true;
  11607. }
  11608. _gl.disable( _gl.CULL_FACE );
  11609. _gl.enable( _gl.BLEND );
  11610. _gl.depthMask( true );
  11611. _gl.bindBuffer( _gl.ARRAY_BUFFER, _sprite.vertexBuffer );
  11612. _gl.vertexAttribPointer( attributes.position, 2, _gl.FLOAT, false, 2 * 8, 0 );
  11613. _gl.vertexAttribPointer( attributes.uv, 2, _gl.FLOAT, false, 2 * 8, 8 );
  11614. _gl.bindBuffer( _gl.ELEMENT_ARRAY_BUFFER, _sprite.elementBuffer );
  11615. _gl.uniformMatrix4fv( uniforms.projectionMatrix, false, camera._projectionMatrixArray );
  11616. _gl.activeTexture( _gl.TEXTURE0 );
  11617. _gl.uniform1i( uniforms.map, 0 );
  11618. // update positions and sort
  11619. var i, sprite, screenPosition, size, scale = [];
  11620. for( i = 0; i < nSprites; i ++ ) {
  11621. sprite = sprites[ i ];
  11622. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  11623. if( ! sprite.useScreenCoordinates ) {
  11624. sprite._modelViewMatrix.multiply( camera.matrixWorldInverse, sprite.matrixWorld);
  11625. sprite.z = - sprite._modelViewMatrix.elements[14];
  11626. } else {
  11627. sprite.z = - sprite.position.z;
  11628. }
  11629. }
  11630. sprites.sort( painterSort );
  11631. // render all sprites
  11632. for( i = 0; i < nSprites; i ++ ) {
  11633. sprite = sprites[ i ];
  11634. if ( ! sprite.visible || sprite.opacity === 0 ) continue;
  11635. if ( sprite.map && sprite.map.image && sprite.map.image.width ) {
  11636. if ( sprite.useScreenCoordinates ) {
  11637. _gl.uniform1i( uniforms.useScreenCoordinates, 1 );
  11638. _gl.uniform3f( uniforms.screenPosition, ( sprite.position.x - halfViewportWidth ) / halfViewportWidth,
  11639. ( halfViewportHeight - sprite.position.y ) / halfViewportHeight,
  11640. Math.max( 0, Math.min( 1, sprite.position.z ) ) );
  11641. } else {
  11642. _gl.uniform1i( uniforms.useScreenCoordinates, 0 );
  11643. _gl.uniform1i( uniforms.affectedByDistance, sprite.affectedByDistance ? 1 : 0 );
  11644. _gl.uniformMatrix4fv( uniforms.modelViewMatrix, false, sprite._modelViewMatrix.elements);
  11645. }
  11646. size = sprite.map.image.width / ( sprite.scaleByViewport ? viewportHeight : 1 );
  11647. scale[ 0 ] = size * invAspect * sprite.scale.x;
  11648. scale[ 1 ] = size * sprite.scale.y;
  11649. _gl.uniform2f( uniforms.uvScale, sprite.uvScale.x, sprite.uvScale.y );
  11650. _gl.uniform2f( uniforms.uvOffset, sprite.uvOffset.x, sprite.uvOffset.y );
  11651. _gl.uniform2f( uniforms.alignment, sprite.alignment.x, sprite.alignment.y );
  11652. _gl.uniform1f( uniforms.opacity, sprite.opacity );
  11653. _gl.uniform3f( uniforms.color, sprite.color.r, sprite.color.g, sprite.color.b );
  11654. _gl.uniform1f( uniforms.rotation, sprite.rotation );
  11655. _gl.uniform2fv( uniforms.scale, scale );
  11656. if ( sprite.mergeWith3D && !mergeWith3D ) {
  11657. _gl.enable( _gl.DEPTH_TEST );
  11658. mergeWith3D = true;
  11659. } else if ( ! sprite.mergeWith3D && mergeWith3D ) {
  11660. _gl.disable( _gl.DEPTH_TEST );
  11661. mergeWith3D = false;
  11662. }
  11663. _renderer.setBlending( sprite.blending, sprite.blendEquation, sprite.blendSrc, sprite.blendDst );
  11664. _renderer.setTexture( sprite.map, 0 );
  11665. _gl.drawElements( _gl.TRIANGLES, 6, _gl.UNSIGNED_SHORT, 0 );
  11666. }
  11667. }
  11668. // restore gl
  11669. _gl.enable( _gl.CULL_FACE );
  11670. _gl.enable( _gl.DEPTH_TEST );
  11671. _gl.depthMask( true );
  11672. };
  11673. function createProgram ( shader ) {
  11674. var program = _gl.createProgram();
  11675. var fragmentShader = _gl.createShader( _gl.FRAGMENT_SHADER );
  11676. var vertexShader = _gl.createShader( _gl.VERTEX_SHADER );
  11677. _gl.shaderSource( fragmentShader, shader.fragmentShader );
  11678. _gl.shaderSource( vertexShader, shader.vertexShader );
  11679. _gl.compileShader( fragmentShader );
  11680. _gl.compileShader( vertexShader );
  11681. _gl.attachShader( program, fragmentShader );
  11682. _gl.attachShader( program, vertexShader );
  11683. _gl.linkProgram( program );
  11684. return program;
  11685. };
  11686. function painterSort ( a, b ) {
  11687. return b.z - a.z;
  11688. };
  11689. };/**
  11690. * @author alteredq / http://alteredqualia.com/
  11691. */
  11692. THREE.DepthPassPlugin = function ( ) {
  11693. this.enabled = false;
  11694. this.renderTarget = null;
  11695. var _gl,
  11696. _renderer,
  11697. _depthMaterial, _depthMaterialMorph,
  11698. _frustum = new THREE.Frustum(),
  11699. _projScreenMatrix = new THREE.Matrix4();
  11700. this.init = function ( renderer ) {
  11701. _gl = renderer.context;
  11702. _renderer = renderer;
  11703. var depthShader = THREE.ShaderLib[ "depthRGBA" ];
  11704. var depthUniforms = THREE.UniformsUtils.clone( depthShader.uniforms );
  11705. _depthMaterial = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms } );
  11706. _depthMaterialMorph = new THREE.ShaderMaterial( { fragmentShader: depthShader.fragmentShader, vertexShader: depthShader.vertexShader, uniforms: depthUniforms, morphTargets: true } );
  11707. _depthMaterial._shadowPass = true;
  11708. _depthMaterialMorph._shadowPass = true;
  11709. };
  11710. this.render = function ( scene, camera ) {
  11711. if ( ! this.enabled ) return;
  11712. this.update( scene, camera );
  11713. };
  11714. this.update = function ( scene, camera ) {
  11715. var i, il, j, jl, n,
  11716. program, buffer, material,
  11717. webglObject, object, light,
  11718. renderList,
  11719. fog = null;
  11720. // set GL state for depth map
  11721. _gl.clearColor( 1, 1, 1, 1 );
  11722. _gl.disable( _gl.BLEND );
  11723. _renderer.setDepthTest( true );
  11724. // update scene
  11725. if ( _renderer.autoUpdateScene ) scene.updateMatrixWorld();
  11726. // update camera matrices and frustum
  11727. if ( ! camera._viewMatrixArray ) camera._viewMatrixArray = new Float32Array( 16 );
  11728. if ( ! camera._projectionMatrixArray ) camera._projectionMatrixArray = new Float32Array( 16 );
  11729. camera.matrixWorldInverse.getInverse( camera.matrixWorld );
  11730. camera.matrixWorldInverse.flattenToArray( camera._viewMatrixArray );
  11731. camera.projectionMatrix.flattenToArray( camera._projectionMatrixArray );
  11732. _projScreenMatrix.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
  11733. _frustum.setFromMatrix( _projScreenMatrix );
  11734. // render depth map
  11735. _renderer.setRenderTarget( this.renderTarget );
  11736. _renderer.clear();
  11737. // set object matrices & frustum culling
  11738. renderList = scene.__webglObjects;
  11739. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11740. webglObject = renderList[ j ];
  11741. object = webglObject.object;
  11742. webglObject.render = false;
  11743. if ( object.visible ) {
  11744. if ( ! ( object instanceof THREE.Mesh ) || ! ( object.frustumCulled ) || _frustum.contains( object ) ) {
  11745. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  11746. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  11747. webglObject.render = true;
  11748. }
  11749. }
  11750. }
  11751. // render regular objects
  11752. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11753. webglObject = renderList[ j ];
  11754. if ( webglObject.render ) {
  11755. object = webglObject.object;
  11756. buffer = webglObject.buffer;
  11757. _renderer.setObjectFaces( object );
  11758. if ( object.customDepthMaterial ) {
  11759. material = object.customDepthMaterial;
  11760. } else if ( object.geometry.morphTargets.length ) {
  11761. material = _depthMaterialMorph;
  11762. } else {
  11763. material = _depthMaterial;
  11764. }
  11765. if ( buffer instanceof THREE.BufferGeometry ) {
  11766. _renderer.renderBufferDirect( camera, scene.__lights, fog, material, buffer, object );
  11767. } else {
  11768. _renderer.renderBuffer( camera, scene.__lights, fog, material, buffer, object );
  11769. }
  11770. }
  11771. }
  11772. // set matrices and render immediate objects
  11773. renderList = scene.__webglObjectsImmediate;
  11774. for ( j = 0, jl = renderList.length; j < jl; j ++ ) {
  11775. webglObject = renderList[ j ];
  11776. object = webglObject.object;
  11777. if ( object.visible && object.castShadow ) {
  11778. if( object.matrixAutoUpdate ) {
  11779. //object.matrixWorld.flattenToArray( object._objectMatrixArray );
  11780. }
  11781. object._modelViewMatrix.multiply( camera.matrixWorldInverse, object.matrixWorld);
  11782. _renderer.renderImmediateObject( camera, scene.__lights, fog, _depthMaterial, object );
  11783. }
  11784. }
  11785. // restore GL state
  11786. var clearColor = _renderer.getClearColor(),
  11787. clearAlpha = _renderer.getClearAlpha();
  11788. _gl.clearColor( clearColor.r, clearColor.g, clearColor.b, clearAlpha );
  11789. _gl.enable( _gl.BLEND );
  11790. };
  11791. };
  11792. /**
  11793. * @author mrdoob / http://mrdoob.com/
  11794. * @author marklundin / http://mark-lundin.com/
  11795. * @author alteredq / http://alteredqualia.com/
  11796. */
  11797. if ( THREE.WebGLRenderer ) {
  11798. THREE.AnaglyphWebGLRenderer = function ( parameters ) {
  11799. THREE.WebGLRenderer.call( this, parameters );
  11800. this.autoUpdateScene = false;
  11801. var _this = this, _setSize = this.setSize, _render = this.render;
  11802. var _cameraL = new THREE.PerspectiveCamera(),
  11803. _cameraR = new THREE.PerspectiveCamera();
  11804. var eyeRight = new THREE.Matrix4(),
  11805. eyeLeft = new THREE.Matrix4(),
  11806. focalLength = 125,
  11807. _aspect, _near, _far, _fov;
  11808. _cameraL.matrixAutoUpdate = _cameraR.matrixAutoUpdate = false;
  11809. var _params = { minFilter: THREE.LinearFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  11810. var _renderTargetL = new THREE.WebGLRenderTarget( 512, 512, _params ),
  11811. _renderTargetR = new THREE.WebGLRenderTarget( 512, 512, _params );
  11812. var _camera = new THREE.PerspectiveCamera( 53, 1, 1, 10000 );
  11813. _camera.position.z = 2;
  11814. var _material = new THREE.ShaderMaterial( {
  11815. uniforms: {
  11816. "mapLeft": { type: "t", value: 0, texture: _renderTargetL },
  11817. "mapRight": { type: "t", value: 1, texture: _renderTargetR }
  11818. },
  11819. vertexShader: [
  11820. "varying vec2 vUv;",
  11821. "void main() {",
  11822. "vUv = vec2( uv.x, 1.0 - uv.y );",
  11823. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  11824. "}"
  11825. ].join("\n"),
  11826. fragmentShader: [
  11827. "uniform sampler2D mapLeft;",
  11828. "uniform sampler2D mapRight;",
  11829. "varying vec2 vUv;",
  11830. "void main() {",
  11831. "vec4 colorL, colorR;",
  11832. "vec2 uv = vUv;",
  11833. "colorL = texture2D( mapLeft, uv );",
  11834. "colorR = texture2D( mapRight, uv );",
  11835. // http://3dtv.at/Knowhow/AnaglyphComparison_en.aspx
  11836. "gl_FragColor = vec4( colorL.g * 0.7 + colorL.b * 0.3, colorR.g, colorR.b, colorL.a + colorR.a ) * 1.1;",
  11837. "}"
  11838. ].join("\n")
  11839. } );
  11840. var _scene = new THREE.Scene();
  11841. var mesh = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), _material );
  11842. mesh.rotation.x = Math.PI / 2;
  11843. _scene.add( mesh );
  11844. _scene.add( _camera );
  11845. this.setSize = function ( width, height ) {
  11846. _setSize.call( _this, width, height );
  11847. _renderTargetL.width = width;
  11848. _renderTargetL.height = height;
  11849. _renderTargetR.width = width;
  11850. _renderTargetR.height = height;
  11851. };
  11852. /*
  11853. * Renderer now uses an asymmetric perspective projection (http://paulbourke.net/miscellaneous/stereographics/stereorender/).
  11854. * Each camera is offset by the eye seperation and its projection matrix is also skewed asymetrically back to converge on the same
  11855. * projection plane. Added a focal length parameter to, this is where the parallax is equal to 0.
  11856. */
  11857. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11858. scene.updateMatrixWorld();
  11859. var hasCameraChanged = ( _aspect !== camera.aspect ) || ( _near !== camera.near ) || ( _far !== camera.far ) || ( _fov !== camera.fov );
  11860. if( hasCameraChanged ) {
  11861. _aspect = camera.aspect;
  11862. _near = camera.near;
  11863. _far = camera.far;
  11864. _fov = camera.fov;
  11865. var projectionMatrix = camera.projectionMatrix.clone(),
  11866. eyeSep = focalLength / 30 * 0.5,
  11867. eyeSepOnProjection = eyeSep * _near / focalLength,
  11868. ymax = _near * Math.tan( _fov * Math.PI / 360 ),
  11869. xmin, xmax;
  11870. // translate xOffset
  11871. eyeRight.elements[12] = eyeSep;
  11872. eyeLeft.elements[12] = -eyeSep;
  11873. // for left eye
  11874. xmin = -ymax * _aspect + eyeSepOnProjection;
  11875. xmax = ymax * _aspect + eyeSepOnProjection;
  11876. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  11877. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  11878. _cameraL.projectionMatrix.copy( projectionMatrix );
  11879. // for right eye
  11880. xmin = -ymax * _aspect - eyeSepOnProjection;
  11881. xmax = ymax * _aspect - eyeSepOnProjection;
  11882. projectionMatrix.elements[0] = 2 * _near / ( xmax - xmin );
  11883. projectionMatrix.elements[8] = ( xmax + xmin ) / ( xmax - xmin );
  11884. _cameraR.projectionMatrix.copy( projectionMatrix );
  11885. }
  11886. _cameraL.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeLeft );
  11887. _cameraL.position.copy( camera.position );
  11888. _cameraL.near = camera.near;
  11889. _cameraL.far = camera.far;
  11890. _render.call( _this, scene, _cameraL, _renderTargetL, true );
  11891. _cameraR.matrixWorld.copy( camera.matrixWorld ).multiplySelf( eyeRight );
  11892. _cameraR.position.copy( camera.position );
  11893. _cameraR.near = camera.near;
  11894. _cameraR.far = camera.far;
  11895. _render.call( _this, scene, _cameraR, _renderTargetR, true );
  11896. _scene.updateMatrixWorld();
  11897. _render.call( _this, _scene, _camera );
  11898. };
  11899. };
  11900. };
  11901. /**
  11902. * @author alteredq / http://alteredqualia.com/
  11903. */
  11904. if ( THREE.WebGLRenderer ) {
  11905. THREE.CrosseyedWebGLRenderer = function ( parameters ) {
  11906. THREE.WebGLRenderer.call( this, parameters );
  11907. this.autoClear = false;
  11908. var _this = this, _setSize = this.setSize, _render = this.render;
  11909. var _width, _height;
  11910. var _cameraL = new THREE.PerspectiveCamera();
  11911. _cameraL.target = new THREE.Vector3( 0, 0, 0 );
  11912. var _cameraR = new THREE.PerspectiveCamera();
  11913. _cameraR.target = new THREE.Vector3( 0, 0, 0 );
  11914. _this.separation = 10;
  11915. if ( parameters && parameters.separation !== undefined ) _this.separation = parameters.separation;
  11916. var SCREEN_WIDTH = window.innerWidth;
  11917. var SCREEN_HEIGHT = window.innerHeight;
  11918. var HALF_WIDTH = SCREEN_WIDTH / 2;
  11919. this.setSize = function ( width, height ) {
  11920. _setSize.call( _this, width, height );
  11921. _width = width/2;
  11922. _height = height;
  11923. };
  11924. this.render = function ( scene, camera, renderTarget, forceClear ) {
  11925. this.clear();
  11926. _cameraL.fov = camera.fov;
  11927. _cameraL.aspect = 0.5 * camera.aspect;
  11928. _cameraL.near = camera.near;
  11929. _cameraL.far = camera.far;
  11930. _cameraL.updateProjectionMatrix();
  11931. _cameraL.position.copy( camera.position );
  11932. _cameraL.target.copy( camera.target );
  11933. _cameraL.translateX( _this.separation );
  11934. _cameraL.lookAt( _cameraL.target );
  11935. _cameraR.projectionMatrix = _cameraL.projectionMatrix;
  11936. _cameraR.position.copy( camera.position );
  11937. _cameraR.target.copy( camera.target );
  11938. _cameraR.translateX( - _this.separation );
  11939. _cameraR.lookAt( _cameraR.target );
  11940. this.setViewport( 0, 0, _width, _height );
  11941. _render.call( _this, scene, _cameraL );
  11942. this.setViewport( _width, 0, _width, _height );
  11943. _render.call( _this, scene, _cameraR, false );
  11944. };
  11945. };
  11946. }
  11947. /**
  11948. * @author mikael emtinger / http://gomo.se/
  11949. *
  11950. */
  11951. THREE.ShaderFlares = {
  11952. 'lensFlareVertexTexture': {
  11953. vertexShader: [
  11954. "uniform vec3 screenPosition;",
  11955. "uniform vec2 scale;",
  11956. "uniform float rotation;",
  11957. "uniform int renderType;",
  11958. "uniform sampler2D occlusionMap;",
  11959. "attribute vec2 position;",
  11960. "attribute vec2 uv;",
  11961. "varying vec2 vUV;",
  11962. "varying float vVisibility;",
  11963. "void main() {",
  11964. "vUV = uv;",
  11965. "vec2 pos = position;",
  11966. "if( renderType == 2 ) {",
  11967. "vec4 visibility = texture2D( occlusionMap, vec2( 0.1, 0.1 ) ) +",
  11968. "texture2D( occlusionMap, vec2( 0.5, 0.1 ) ) +",
  11969. "texture2D( occlusionMap, vec2( 0.9, 0.1 ) ) +",
  11970. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ) +",
  11971. "texture2D( occlusionMap, vec2( 0.9, 0.9 ) ) +",
  11972. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ) +",
  11973. "texture2D( occlusionMap, vec2( 0.1, 0.9 ) ) +",
  11974. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ) +",
  11975. "texture2D( occlusionMap, vec2( 0.5, 0.5 ) );",
  11976. "vVisibility = ( visibility.r / 9.0 ) *",
  11977. "( 1.0 - visibility.g / 9.0 ) *",
  11978. "( visibility.b / 9.0 ) *",
  11979. "( 1.0 - visibility.a / 9.0 );",
  11980. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  11981. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  11982. "}",
  11983. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  11984. "}"
  11985. ].join( "\n" ),
  11986. fragmentShader: [
  11987. "precision mediump float;",
  11988. "uniform sampler2D map;",
  11989. "uniform float opacity;",
  11990. "uniform int renderType;",
  11991. "uniform vec3 color;",
  11992. "varying vec2 vUV;",
  11993. "varying float vVisibility;",
  11994. "void main() {",
  11995. // pink square
  11996. "if( renderType == 0 ) {",
  11997. "gl_FragColor = vec4( 1.0, 0.0, 1.0, 0.0 );",
  11998. // restore
  11999. "} else if( renderType == 1 ) {",
  12000. "gl_FragColor = texture2D( map, vUV );",
  12001. // flare
  12002. "} else {",
  12003. "vec4 texture = texture2D( map, vUV );",
  12004. "texture.a *= opacity * vVisibility;",
  12005. "gl_FragColor = texture;",
  12006. "gl_FragColor.rgb *= color;",
  12007. "}",
  12008. "}"
  12009. ].join( "\n" )
  12010. },
  12011. 'lensFlare': {
  12012. vertexShader: [
  12013. "uniform vec3 screenPosition;",
  12014. "uniform vec2 scale;",
  12015. "uniform float rotation;",
  12016. "uniform int renderType;",
  12017. "attribute vec2 position;",
  12018. "attribute vec2 uv;",
  12019. "varying vec2 vUV;",
  12020. "void main() {",
  12021. "vUV = uv;",
  12022. "vec2 pos = position;",
  12023. "if( renderType == 2 ) {",
  12024. "pos.x = cos( rotation ) * position.x - sin( rotation ) * position.y;",
  12025. "pos.y = sin( rotation ) * position.x + cos( rotation ) * position.y;",
  12026. "}",
  12027. "gl_Position = vec4( ( pos * scale + screenPosition.xy ).xy, screenPosition.z, 1.0 );",
  12028. "}"
  12029. ].join( "\n" ),
  12030. fragmentShader: [
  12031. "precision mediump float;",
  12032. "uniform sampler2D map;",
  12033. "uniform sampler2D occlusionMap;",
  12034. "uniform float opacity;",
  12035. "uniform int renderType;",
  12036. "uniform vec3 color;",
  12037. "varying vec2 vUV;",
  12038. "void main() {",
  12039. // pink square
  12040. "if( renderType == 0 ) {",
  12041. "gl_FragColor = vec4( texture2D( map, vUV ).rgb, 0.0 );",
  12042. // restore
  12043. "} else if( renderType == 1 ) {",
  12044. "gl_FragColor = texture2D( map, vUV );",
  12045. // flare
  12046. "} else {",
  12047. "float visibility = texture2D( occlusionMap, vec2( 0.5, 0.1 ) ).a +",
  12048. "texture2D( occlusionMap, vec2( 0.9, 0.5 ) ).a +",
  12049. "texture2D( occlusionMap, vec2( 0.5, 0.9 ) ).a +",
  12050. "texture2D( occlusionMap, vec2( 0.1, 0.5 ) ).a;",
  12051. "visibility = ( 1.0 - visibility / 4.0 );",
  12052. "vec4 texture = texture2D( map, vUV );",
  12053. "texture.a *= opacity * visibility;",
  12054. "gl_FragColor = texture;",
  12055. "gl_FragColor.rgb *= color;",
  12056. "}",
  12057. "}"
  12058. ].join( "\n" )
  12059. }
  12060. };
  12061. /**
  12062. * @author mikael emtinger / http://gomo.se/
  12063. *
  12064. */
  12065. THREE.ShaderSprite = {
  12066. 'sprite': {
  12067. vertexShader: [
  12068. "uniform int useScreenCoordinates;",
  12069. "uniform int affectedByDistance;",
  12070. "uniform vec3 screenPosition;",
  12071. "uniform mat4 modelViewMatrix;",
  12072. "uniform mat4 projectionMatrix;",
  12073. "uniform float rotation;",
  12074. "uniform vec2 scale;",
  12075. "uniform vec2 alignment;",
  12076. "uniform vec2 uvOffset;",
  12077. "uniform vec2 uvScale;",
  12078. "attribute vec2 position;",
  12079. "attribute vec2 uv;",
  12080. "varying vec2 vUV;",
  12081. "void main() {",
  12082. "vUV = uvOffset + uv * uvScale;",
  12083. "vec2 alignedPosition = position + alignment;",
  12084. "vec2 rotatedPosition;",
  12085. "rotatedPosition.x = ( cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y ) * scale.x;",
  12086. "rotatedPosition.y = ( sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y ) * scale.y;",
  12087. "vec4 finalPosition;",
  12088. "if( useScreenCoordinates != 0 ) {",
  12089. "finalPosition = vec4( screenPosition.xy + rotatedPosition, screenPosition.z, 1.0 );",
  12090. "} else {",
  12091. "finalPosition = projectionMatrix * modelViewMatrix * vec4( 0.0, 0.0, 0.0, 1.0 );",
  12092. "finalPosition.xy += rotatedPosition * ( affectedByDistance == 1 ? 1.0 : finalPosition.z );",
  12093. "}",
  12094. "gl_Position = finalPosition;",
  12095. "}"
  12096. ].join( "\n" ),
  12097. fragmentShader: [
  12098. "precision mediump float;",
  12099. "uniform vec3 color;",
  12100. "uniform sampler2D map;",
  12101. "uniform float opacity;",
  12102. "varying vec2 vUV;",
  12103. "void main() {",
  12104. "vec4 texture = texture2D( map, vUV );",
  12105. "gl_FragColor = vec4( color * texture.xyz, texture.a * opacity );",
  12106. "}"
  12107. ].join( "\n" )
  12108. }
  12109. };
粤ICP备19079148号